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

PineScript v4:如何将line.new生成的止盈线值存入变量

解决Pine Script中策略止盈价格固定为线条生成时价格的问题

核心解决逻辑是在绘制止盈线的触发条件下,将当时的目标价格存入独立变量,避免后续K线更新时覆盖初始值:

  • 首先声明一个持久化的变量来存储止盈价格,确保仅在触发条件时更新:
    var float takeProfitPrice = na  // 初始化变量,仅执行一次
    
  • 在绘制止盈线的同一条件分支中,给这个变量赋值(此时的highPrice就是线条生成时的价格):
    // 替换成你实际的触发条件,比如开仓信号成立
    if (entryCondition)
        takeProfitPrice := highPrice  // 固定线条生成时的价格
        Line := line.new(bar_index, highPrice, bar_index+1, highPrice, width=2, color=color.red, extend=extend.both, style=line.style_dashed)
    
  • 在strategy.exit中直接使用这个存储好的变量,就能拿到线条生成时的价格,而非当前K线价格:
    strategy.exit("Exit Position", limit=takeProfitPrice, stop=stopLossPrice)
    

如果是多仓位策略,需要用数组来分别存储每个仓位的止盈价格,示例如下:

var float[] takeProfitArray = array.new_float()

if (entryCondition)
    takeProfitValue = highPrice
    array.push(takeProfitArray, takeProfitValue)
    Line := line.new(bar_index, highPrice, bar_index+1, highPrice, width=2, color=color.red, extend=extend.both, style=line.style_dashed)
    // 开仓时记录仓位索引
    strategy.entry("Long", strategy.long)
    currentIdx = strategy.opentrades - 1

// 平仓时对应取出数组中的价格
if (exitCondition)
    takeProfitPrice = array.get(takeProfitArray, currentIdx)
    strategy.exit("Exit", limit=takeProfitPrice)
    array.remove(takeProfitArray, currentIdx)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:45:59