如何在Pine Script中实现数组关联(主从数组)?
在Pine Script中实现数组同步排序的两种方案
针对你遇到的多数组关联排序错位问题,以下两种高效方案完全适配你的使用场景:
方案一:使用结构体数组(Pine Script v5及以上推荐)
这是最简洁的解决思路——把同一事件的所有字段(high、low、open、close、time)封装成自定义结构体,将结构体实例存入单个数组。排序时整个结构体同步移动,从根源避免索引错位问题。
代码示例:
//@version=5 indicator("结构体数组同步排序示例") // 定义存储K线事件的结构体 struct CandleEvent float high float low float open float close int time // 创建结构体数组 candleEvents = array.new<CandleEvent>() // 当出现上涨K线时,存入数据 if close > open newEvent = CandleEvent.new(high, low, open, close, time) array.push(candleEvents, newEvent) // 按high值降序排序结构体数组(最高值在首位) array.sort(candleEvents, (a, b) => b.high - a.high) // 获取排序后的第一个(最高high)事件数据 if array.size(candleEvents) > 0 topEvent = array.get(candleEvents, 0) label.new(bar_index, topEvent.high, str.format("最高high: {0}\n时间: {1}", topEvent.high, timestamp_to_string(topEvent.time)))
这种方式下,所有关联数据绑定在一起,排序、查询时无需担心字段错位,代码可读性和维护性更强。
方案二:索引数组同步法(兼容Pine Script旧版本)
如果使用不支持结构体的旧版本,可通过索引数组实现同步排序:
- 创建存储原数组索引的数组(如
indices) - 对索引数组按目标字段(如high)的值排序
- 根据排序后的索引数组,重新构建所有关联数组(low、open等)
代码示例:
//@version=5 indicator("索引数组同步排序示例") // 初始化各字段数组 highs = array.new_float() lows = array.new_float() opens = array.new_float() closes = array.new_float() times = array.new_int() // 存储上涨K线数据 if close > open array.push(highs, high) array.push(lows, low) array.push(opens, open) array.push(closes, close) array.push(times, time) // 当数组有数据时执行同步排序 if array.size(highs) > 0 // 创建索引数组(0到数组长度-1) indices = array.new_int() for i = 0 to array.size(highs) - 1 array.push(indices, i) // 按high值降序排序索引数组 array.sort(indices, (i, j) => array.get(highs, j) - array.get(highs, i)) // 根据排序后的索引,重新构建所有关联数组 newHighs = array.new_float() newLows = array.new_float() newOpens = array.new_float() newCloses = array.new_float() newTimes = array.new_int() for idx in indices array.push(newHighs, array.get(highs, idx)) array.push(newLows, array.get(lows, idx)) array.push(newOpens, array.get(opens, idx)) array.push(newCloses, array.get(closes, idx)) array.push(newTimes, array.get(times, idx)) // 替换原数组为排序后的新数组 highs := newHighs lows := newLows opens := newOpens closes := newCloses times := newTimes // 获取最高high对应的完整数据 topHigh = array.get(highs, 0) topLow = array.get(lows, 0) topTime = array.get(times, 0) label.new(bar_index, topHigh, str.format("最高high: {0}\n对应low: {1}\n时间: {2}", topHigh, topLow, timestamp_to_string(topTime)))
这种方法通过索引映射维持字段间关联,排序后所有数组的索引仍一一对应,解决了排序错位问题。
内容的提问来源于stack exchange,提问作者Hannes
相关产品推荐
相关产品推荐

