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

如何在Pine Script交叉策略中设置单笔交易最大5%回撤平仓规则

Pine语言交叉策略新增5%回撤止损修改方案

本次修改完全保留原有KD交叉开平仓逻辑,仅新增浮亏5%收盘平仓规则,实现逻辑如下:

  • 开仓后自动记录多单的进场成本价
  • 以收盘价计算持仓浮亏比例,浮亏达到或超过5%时触发平仓
  • 止损条件和原有看跌交叉平仓条件并行生效,互不干扰
  • 所有平仓判断均在K线收盘时执行,符合你的需求

修改后完整代码如下:

buy= crossunder (k,d)
sell= crossover(k,d)

// 新增:记录持仓成本&计算5%回撤止损触发条件
var float entry_price = na
// 开仓时记录进场价
if strategy.position_size > 0 and na(entry_price)
    entry_price := strategy.opentrades.entry_price(0)
// 平仓后重置进场价
if strategy.position_size == 0
    entry_price := na
// 浮亏≥5%时触发止损
stop_loss_condition = strategy.position_size > 0 and (entry_price - close) / entry_price >= 0.05

// strategy
strategy.entry ("long", strategy.long, 100, when = buy) 
// 原有平仓逻辑叠加止损条件
strategy.close ("long", when = sell or stop_loss_condition)

若你的策略后续支持加仓,可将strategy.opentrades.entry_price(0)替换为strategy.position_avg_price,即可按整体持仓平均成本计算回撤比例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:18:04