PineScript:实时K线指标触发时保存实时价格及当日收益统计问询
PineScript 实时触发价格记录与当日收益统计方案
问题核心
你之前的方案失效原因有两点:
- 单个
varip变量只能存储最后一次触发的价格,无法保留当日所有触发点的记录; 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
相关产品推荐
相关产品推荐

