You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在TradingView Pine Script中计算金字塔仓位的总入场价格总和

计算Pine Script金字塔仓位的总买入价格

嘿,这个需求很实用——要追踪金字塔开仓的总入场成本对吧?我来给你调整下策略代码,实现这个功能:

核心思路是用持久化变量var关键字)保存总买入价和入场次数,每次触发买入信号并成功开仓后,把本次入场的价格加到总和里。

修改后的完整代码:

//@version=5
strategy("RSI Check", overlay=true, pyramiding=5000)

// 初始化总买入价和入场计数,var确保变量只在脚本启动时初始化一次
var float total_entry_price = 0.0
var int entry_count = 0

rsi3 = ta.rsi(close, 3)

if (rsi3 <= 20)
    strategy.entry("Buy", strategy.long)
    // 每次新增开仓时,累加本次入场价格
    if (strategy.opentrades > entry_count)
        // 取最新一次开仓的入场价格(索引从0开始,所以用opentrades-1)
        total_entry_price += strategy.opentrades.entry_price(strategy.opentrades - 1)
        entry_count += 1

// 把结果可视化出来,方便查看
plot(total_entry_price, title="Total Entry Price", color=color.new(color.green, 0), display=display.data_window)
plotchar(entry_count, title="Entry Count", location=location.top, color=color.new(color.red, 0), char="📊")

关键部分解释:

  • var关键字:这是核心!如果不用var,变量会在每根K线都重置,根本存不住历史数据。用var后,变量只会在脚本第一次运行时初始化一次,之后一直保留值。
  • strategy.opentrades:这个函数返回当前持有的开仓数量,我们用它判断是否新增了仓位。每次成功开仓后,strategy.opentrades会比之前的entry_count大1,这时候就可以获取最新开仓的价格并累加。
  • strategy.opentrades.entry_price():通过索引获取指定开仓的入场价格,最新开仓的索引是strategy.opentrades - 1(因为索引从0开始)。

如果你只想计算前100次入场的总和,可以把累加逻辑改成这样:

if (strategy.opentrades > entry_count and entry_count < 100)
    total_entry_price += strategy.opentrades.entry_price(strategy.opentrades - 1)
    entry_count += 1

这样就会在达到100次入场后停止累加啦~

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

火山引擎 最新活动