Pine script - 试图计算盘前低点的平均值

Pine script - Trying to calculate the average of lows in premarket

我是 pine 脚本的新手,正在尝试计算和绘制上市前的平均低价 不幸的是,我的代码似乎无法正常工作,我找不到原因

var preMarketSession = "0400-0930" //setting the premarket time
isPreMarket = not na(time(timeframe.period, "0400-0930")) //boolean for if the session is currently in premarket

var int barsInPreMarket = 0
var float averageLow = na


// Confirming first bar of premarket
if isPreMarket and not isPreMarket[1]
    averageLow := 0


//Counting the number of bars in premarket
if (isPreMarket and barstate.isnew)
    barsInPreMarket := barsInPreMarket + 1


//Calculating the avg of low prices on end of bar
if isPreMarket and barstate.isconfirmed
    for i=0 to barsInPreMarket - 1
        averageLow := (averageLow + low) / barsInPreMarket

// Resseting the car count and avarage upon exiting premarket
if not isPreMarket
    barsInPreMarket := 0
    averageLow := na


plot(averageLow)

这段代码导致了这个混乱: Graph

如果有人能指出正确的方向,我将不胜感激!

问题似乎是当值是 na 时的处理,或使用 barstate。关于 na 值,脚本允许计算 na 值的可能性,您必须使用 nz() 呈现值 0 或使用 na() 测试条件并采取相应行动。我不确定 barstate 是否导致了问题,但没有必要。

//@version=4
study("My Script",overlay=true)
var preMarketSession = "0400-0930" //setting the premarket time
isPreMarket = not na(time(timeframe.period, "0400-0930")) //boolean for if the session is currently in premarket

var int barsInPreMarket = 0
var float lowSum = na
var float averageLow = na


if isPreMarket
    if na(lowSum)
        barsInPreMarket := 1
        lowSum := low
        averageLow := low
    else
        barsInPreMarket := barsInPreMarket + 1
        lowSum := lowSum + low
        averageLow := lowSum / barsInPreMarket
else if isPreMarket[1]
    lowSum := na
    barsInPreMarket := 0

plot(averageLow)

注意 na 值很重要,因为您不知道脚本何时开始执行。它可以在盘前中期开始,这意味着当 averageLow 为 na 时,它使用 averageLow 来计算 averageLow。