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

Pine Script编写简化代码计算建仓后最高价并设置平仓规则

Pine Script 持仓最高价计算与平仓规则实现方案

一、最简持仓以来最高价计算实现

不需要依赖你原来复制的 pivot 高点相关冗余代码,仅需3行核心逻辑即可实现:

// 声明变量存储建仓以来最高价,空仓时重置
var float highest_after_entry = na
// 空仓时重置,持仓时持续更新最高价
if strategy.position_size == 0
    highest_after_entry := na
else
    highest_after_entry := math.max(nz(highest_after_entry, high), high)

逻辑说明:空仓状态下变量重置为空,开仓后每根K线都将当前最高价和历史持仓最高价比较取最大值,天然就是建仓以来的最高价格。

二、低于指定价格平仓规则实现

提供两种常用实现方式,可按需选择:

方式1:固定指定价格止损

新增参数让用户自定义触发平仓的价格阈值:

// 新增输入参数
fixed_stop_price = input.float(title="固定止损价格", defval=0.0, minval=0.0, step=0.01, tooltip="当前价格低于该值时自动平仓,填0则不启用该规则")
// 平仓条件判断
stop_condition = fixed_stop_price > 0 and close < fixed_stop_price

方式2:按持仓成本比例止损

更常用的动态止损方式,基于建仓均价的回撤比例触发:

// 新增输入参数
stop_loss_pct = input.float(title="止损比例(%)", defval=2.0, minval=0.1, step=0.1, tooltip="当前价格低于建仓均价的百分比时触发止损")
// 平仓条件判断
stop_condition = close < strategy.position_avg_price * (1 - stop_loss_pct / 100)

三、整合修改后的策略执行逻辑

你原来的代码存在两处明显错误:

  1. 收益率计算括号错误,会导致结果完全失真
  2. 平仓条件用==判断,几乎不可能触发,需改为小于判断
    修改后的策略代码如下:
// 修正原错误的收益率计算
exit_pct = (close - strategy.position_avg_price) / strategy.position_avg_price * 100

// -------------------------- 新增逻辑开始 --------------------------
var float highest_after_entry = na
if strategy.position_size == 0
    highest_after_entry := na
else
    highest_after_entry := math.max(nz(highest_after_entry, high), high)

// 回撤平仓比例参数,可自定义
drawdown_exit_pct = input.float(title="最高值回撤平仓比例(%)", defval=20.0, minval=0.1, step=0.1)
// 成本价止损比例
stop_loss_pct = input.float(title="成本价止损比例(%)", defval=2.0, minval=0.1, step=0.1)

// 平仓条件:1、从持仓最高价回撤指定比例 2、低于成本价止损比例 满足任意一个就平仓
long_exit_condition = (close < highest_after_entry * (1 - drawdown_exit_pct / 100)) or (close < strategy.position_avg_price * (1 - stop_loss_pct / 100))
// -------------------------- 新增逻辑结束 --------------------------

bull=(low>upper and BV>SV and BV>Davgvol)
bux =(close<Supper and close>Slower and volume<Wavgvol)
bear=(close<Slower and close<lower and SV>BV and SV>Wavgvol)
hi=highest(exit_pct,10)

// STRATEGY LONG //
if (bull and close>ma3 and ma20>ma60)
    strategy.entry("Long",strategy.long,1)
    
if (long_exit_condition)
    strategy.close("Long",1)

你不需要修改原有其他指标计算、pivot 画图的代码,仅需替换原策略部分的逻辑即可生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:15:02