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

PineScript:实时K线指标触发时保存实时价格及当日收益统计问询

PineScript 实时触发价格记录与当日收益统计方案

问题核心

你之前的方案失效原因有两点:

  1. 单个varip变量只能存储最后一次触发的价格,无法保留当日所有触发点的记录;
  2. ta.valuewhen(myindicator == true, close, 0)本质和直接取close效果一致,但没解决多数据存储的问题。

可行解决方案

要实现实时价格记录+当日收益统计,需用数组存储多触发点价格,结合每日重置逻辑,具体代码如下:

//@version=5
indicator("实时触发统计工具", overlay=true)

// 替换为你的实际触发指标
myindicator = ta.rsi(close, 14) < 30  // 示例:RSI低于30时触发

// 存储当日所有触发价格的数组(varip确保实时更新且保留数据)
varip float[] triggerPrices = array.new_float()

// 每日开盘时清空数组,仅统计当日数据
if ta.change(time("D"))
    array.clear(triggerPrices)

// 指标触发时,存入实时价格(实时K线中close即为当前最新成交价)
if myindicator
    array.push(triggerPrices, close)
    // 可选:在K线上标记触发价格
    label.new(bar_index, close, str.tostring(close, "#.##"), color=color.green, textcolor=color.white, style=label.style_label_down)

// 计算当日总收益:当前价格与所有触发价格的差值之和
totalDailyProfit = array.size(triggerPrices) * close - array.sum(triggerPrices)

// 输出总收益到数据窗口
plot(totalDailyProfit, title="当日总收益", color=color.red, display=display.data_window)

// 显示触发次数与总收益(调试用)
var label statsLabel = label.new(bar_index, high, "", color=color.navy, textcolor=color.white)
label.set_xy(statsLabel, bar_index, high)
label.set_text(statsLabel, "触发次数: " + str.tostring(array.size(triggerPrices)) + "\n总收益: " + str.tostring(totalDailyProfit, "#.##"))

关键逻辑说明

  • 数组存储:用array.new_float()创建动态数组,每次触发时通过array.push()添加实时价格,避免单个变量的覆盖问题;
  • 当日重置:ta.change(time("D"))检测每日K线切换,清空数组确保统计范围仅限当日;
  • 实时价格获取:实时K线中close字段会持续更新为最新成交价,触发时直接取close即可得到触发瞬间的实时价格;
  • 高效收益计算:通过array.size()和array.sum()替代循环计算,提升脚本运行效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:07:18