如何获取input.time选定K线的高低价?自定义索引函数问题求助
问题分析与解决方案
你的自定义索引函数逻辑存在问题:Pine Script中bar_index是从左到右递增的(首根K线为0,最新K线数值最大),而你的函数在bar_1 < time时会持续更新i为当前bar_index,最终得到的a_是最新K线的索引。此时用high[a_]相当于从最新K线往左偏移a_根,完全取不到目标K线的价格。
以下是两种直接解决问题的方案:
方案一:用ta.valuewhen直接提取目标K线价格(推荐)
无需手动计算索引,利用内置函数直接匹配目标时间对应的高低价:
//@version=5 indicator("目标K线均价计算", overlay=true) bar_1 = input.time(title="选择目标K线", defval=timestamp("0900-01-01"), confirm=true) // 匹配目标时间,提取对应K线的高低价 target_high = ta.valuewhen(time == bar_1, high, 0) target_low = ta.valuewhen(time == bar_1, low, 0) // 计算均价 average_price = (target_high + target_low) / 2 // 可视化输出 plot(average_price, color=color.blue, title="目标K线均价") label.new(bar_index, average_price, str.tostring(average_price, "%.2f"), color=color.yellow)
ta.valuewhen(条件, 目标序列, 偏移量):这里偏移量设为0,会提取第一次满足time == bar_1时的高低价,完全匹配目标K线。
方案二:用数组存储K线数据并查找索引
适合需要多次查询不同K线的场景:
//@version=5 indicator("目标K线均价计算(数组版)", overlay=true) bar_1 = input.time(title="选择目标K线", defval=timestamp("0900-01-01"), confirm=true) // 初始化数组存储每根K线的时间、最高价、最低价 var array<int> time_list = array.new_int() var array<float> high_list = array.new_float() var array<float> low_list = array.new_float() // 每根K线追加数据到数组 array.push(time_list, time) array.push(high_list, high) array.push(low_list, low) // 查找目标时间在数组中的索引 target_idx = array.indexof(time_list, bar_1) // 获取对应价格并计算均价 average_price = na if target_idx != -1 target_high = array.get(high_list, target_idx) target_low = array.get(low_list, target_idx) average_price = (target_high + target_low) / 2 // 可视化输出 plot(average_price, color=color.red, title="目标K线均价")
array.indexof会返回目标时间在数组中的位置,数组按K线从左到右的顺序存储,因此索引直接对应目标K线。
内容的提问来源于stack exchange,提问作者Sanket Kolte
相关产品推荐
相关产品推荐

