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

如何在Pine Script指标中实现strategy.position_avg_price功能?

指标中模拟策略持仓均价功能的实现方案

由于strategy.position_avg_price是策略专属函数,仅能在策略脚本中调用,指标脚本无法访问策略的持仓状态,因此需要手动模拟持仓逻辑来跟踪多头入场价格。

修改后的完整代码

indicator("testDMI", shorttitle="TDMI", overlay=true)

lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
len = input.int(14, minval=1, title="DI Length")
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / trur)
minus = fixnan(100 * ta.rma(minusDM, len) / trur)
sum = plus + minus
med = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
sub = plus - med
sig = plus - minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)

Entrylong = sig >= 0 
// 初始化跨bar状态变量,记录持仓状态和入场价格
var bool isLong = false
var float PriceEntrylong = na

// 多头入场逻辑:触发信号且无持仓时,记录入场价格并标记持仓
if (Entrylong and not isLong)
    isLong := true
    PriceEntrylong := close // 可根据需求替换为open/high/low等价格

// 多头出场逻辑:需根据你的交易规则补充,示例为sig<0时平仓
Exitlong = sig < 0
if (Exitlong and isLong)
    isLong := false
    PriceEntrylong := na

// 可选:在图表上标记多头入场价
plot(isLong ? PriceEntrylong : na, color=color.green, style=plot.style_circles, title="多头入场价")

关键逻辑说明

  • 使用var关键字定义状态变量,确保变量值在不同K线之间持续保留,不会每根K线重新初始化
  • 手动模拟持仓的开平仓状态:当触发多头信号且当前无持仓时,记录入场价格并标记为持仓;当触发出场信号且当前持仓时,重置状态和入场价格
  • 入场价格可根据实际需求调整,比如使用信号触发时的开盘价open、最高价high,或者自定义的入场价位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:03:34