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

Pine脚本编写求助:SPY周涨幅达标时卖出AAPL并回补

Pine脚本问题修复:SPY触发AAPL平仓及重新入场逻辑

原脚本存在的核心问题

  • 初始开仓无仓位判断,每根K线重复执行开仓指令,导致策略逻辑混乱
  • 平仓指令的订单ID与开仓ID不匹配(开仓用"long",平仓写"sell"),无法触发平仓操作
  • 涨幅阈值不符合需求:要求SPY单周涨5%,但脚本写了10%(1.10)
  • 重新入场逻辑错误:直接引用2根K线前的SPY涨幅,未关联平仓事件,会导致无意义的重复开仓

修正后的脚本

//@version=5
strategy("Sell AAPL when SPY rally", initial_capital=1000, default_qty_type=strategy.cash, default_qty_value=1000, commission_type=strategy.commission.percent, commission_value=0.1)

// 初始做多:仅在无仓位时执行
if (strategy.position_size == 0)
    strategy.entry("Long AAPL", strategy.long)

// 获取SPY周线开盘价和收盘价
[spy_close, spy_open] = request.security("SPY", "W", [close, open])
spy_weekly_return = spy_close / spy_open

// 跟踪平仓信号的触发时间(记录周线K线索引)
var int exit_bar_index = na

// 条件1:SPY单周涨幅≥5%时,平仓全部AAPL多头
if (spy_weekly_return >= 1.05 and strategy.position_size > 0)
    strategy.close("Long AAPL", comment="Close on SPY rally")
    exit_bar_index = bar_index  // 记录平仓时的K线位置

// 条件2:平仓后满2根周K线,重新100%做多AAPL
if (not na(exit_bar_index) and bar_index >= exit_bar_index + 2 and strategy.position_size == 0)
    strategy.entry("Long AAPL", strategy.long)
    exit_bar_index = na  // 重置跟踪变量

// 绘制SPY周线涨幅
plot(spy_weekly_return, title="SPY Weekly Return", color=color.blue)

关键修改说明

  • 使用strategy.position_size判断仓位状态,避免重复开仓
  • 平仓指令与开仓使用相同的订单ID"Long AAPL",确保能正确匹配平仓
  • 将涨幅阈值修正为1.05(对应5%涨幅)
  • 新增exit_bar_index变量跟踪平仓发生的K线位置,确保在平仓后**两周(2根周K线)**才重新入场
  • 设置default_qty_type=strategy.cash和default_qty_value=1000,确保每次入场都是100%资金做多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:05:34