如何修复Pine Script中enterShortLHClose_arr始终为0的数组赋值问题?
问题:数组enterShortLHClose_arr始终无法正确赋值
我需要实现的逻辑是:用enterShortClose_arr数组存储的值,在条件再次触发时检查该值是否大于收盘价。目前enterShortClose_arr的值能正确更新,但enterShortLHClose_arr始终是0。我希望当满足enterShortClose_arr[a] > price2_arr[a]的条件时,把收盘价存入enterShortLHClose_arr对应的位置。
代码运行无报错,但试了多种方法都没解决。以下是我试过的一种无效写法:
if barstate.isconfirmed for a=0 to array.size(shortCond_arr)-1 if array.get(shortCond_arr, a) and array.get(enterShortClose_arr, a) > array.get(price2_arr, a) closeShort := array.get(price2_arr, a) array.remove(enterShortClose_arr, a) array.insert(enterShortLHClose_arr, a, closeShort)
以下是我另一段尝试的代码:
var enterShortClose_arr = array.new_float(0) var enterShortLHClose_arr = array.new_float(0) // 初始化数组 if array.size(enterShortClose_arr) == 0 for i=0 to array.size(s_arr) -1 array.push(enterShortClose_arr, 0.0) array.push(enterShortLHClose_arr, 0.0) if barstate.isconfirmed for a=0 to array.size(shortCond_arr)-1 if array.get(shortCond_arr, a) closeShort = array.get(price2_arr, a) enterShort := array.get(shortCond_arr, a) array.remove(enterShortClose_arr, a) array.insert(enterShortClose_arr, a, closeShort) if array.get(enterShortClose_arr, a) < array.get(price2_arr, a) closeShort := array.get(price2_arr, a) array.insert(enterShortLHClose_arr, a, closeShort)
问题分析
第二段代码的核心问题在于逻辑时机和条件判断错误:
- 你在第一次触发
shortCond_arr[a]时,刚把当前收盘价存入enterShortClose_arr[a],紧接着判断enterShortClose_arr[a] < price2_arr[a]——此时两个值完全相等,这个条件永远不会成立,所以enterShortLHClose_arr根本不会被赋值。 - 你要实现的是再次触发条件时检查之前存储的价格,但当前逻辑是在第一次触发时就做判断,时机完全不对。
修复方案
正确逻辑应该拆分两次触发的场景:第一次触发时初始化enterShortClose_arr的值,再次触发时对比之前存储的值和当前收盘价,满足条件则更新enterShortLHClose_arr。修改后的代码如下:
var enterShortClose_arr = array.new_float(0) var enterShortLHClose_arr = array.new_float(0) // 初始化数组,确保长度与s_arr一致 if array.size(enterShortClose_arr) == 0 for i=0 to array.size(s_arr) -1 array.push(enterShortClose_arr, 0.0) array.push(enterShortLHClose_arr, 0.0) if barstate.isconfirmed for a=0 to array.size(shortCond_arr)-1 currentPrice = array.get(price2_arr, a) shortTriggered = array.get(shortCond_arr, a) storedPrice = array.get(enterShortClose_arr, a) // 再次触发条件,且之前已有存储的价格(非初始0) if shortTriggered and storedPrice != 0.0 // 检查存储值是否大于当前收盘价 if storedPrice > currentPrice array.set(enterShortLHClose_arr, a, currentPrice) // 更新存储的价格为当前收盘价 array.set(enterShortClose_arr, a, currentPrice) // 第一次触发条件,初始化存储价格 else if shortTriggered and storedPrice == 0.0 array.set(enterShortClose_arr, a, currentPrice)
关键修改点:
- 用
array.set()替代remove+insert,更高效且避免数组索引混乱 - 明确区分第一次触发和再次触发的逻辑,确保在再次触发时才做价格对比
- 增加对
enterShortClose_arr[a]初始值的判断,避免第一次触发就进入错误分支
内容的提问来源于stack exchange,提问作者mgoblue33
相关产品推荐
相关产品推荐

