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

如何在Pine Script中设置定时平仓(可选3/15分钟,默认3分钟)

在Pine Script策略中实现定时平仓功能

实现思路

  • 添加可配置的平仓延迟参数,支持3/15分钟选项,默认3分钟
  • 记录每笔开仓的时间戳
  • 实时判断当前时间与开仓时间的差值,达到设定延迟后自动平仓

完整代码示例

//@version=5
strategy("带定时平仓的SMA交叉策略", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000)

// 定义平仓延迟参数
close_delay = input.int(3, title="平仓延迟(分钟)", options=[3, 15], tooltip="选择开仓后自动平仓的延迟时间")

// 初始化开仓时间记录变量(var关键字确保变量值在bar间保留)
var float long_entry_time = na
var float short_entry_time = na

// SMA交叉核心逻辑
fast_sma = ta.sma(close, 50)
slow_sma = ta.sma(close, 200)

long_condition = ta.crossover(fast_sma, slow_sma)
short_condition = ta.crossunder(fast_sma, slow_sma)

// 开仓并同步记录时间
if (long_condition)
    strategy.entry("Long", strategy.long)
    long_entry_time = time  // 记录多仓开仓时间(单位:毫秒)

if (short_condition)
    strategy.entry("Short", strategy.short)
    short_entry_time = time  // 记录空仓开仓时间

// 定时平仓逻辑
// 多仓平仓:持仓为正,且当前时间达到开仓+延迟的时间点
if (strategy.position_size > 0 and time >= long_entry_time + close_delay * 60 * 1000)
    strategy.close("Long")
    long_entry_time = na  // 平仓后重置开仓时间,避免重复触发

// 空仓平仓:持仓为负,且当前时间达到开仓+延迟的时间点
if (strategy.position_size < 0 and time >= short_entry_time + close_delay * 60 * 1000)
    strategy.close("Short")
    short_entry_time = na

// 绘制SMA均线
plot(fast_sma, color=color.new(color.blue, 0), title="快速SMA")
plot(slow_sma, color=color.new(color.red, 0), title="慢速SMA")

关键部分说明

  • 参数配置:用input.int限定可选的延迟时间,避免无效输入,同时保留用户自定义选择的灵活性
  • 开仓时间记录:var关键字声明的变量仅初始化一次,后续K线会保留上一次开仓的时间戳,确保持仓时长计算准确
  • 时间单位转换:Pine Script中time以毫秒为单位,因此需要将分钟数转换为毫秒(close_delay * 60 * 1000)来匹配时间戳计算
  • 重置机制:平仓后将开仓时间变量设为na,防止后续K线重复触发平仓逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:12:52