简体   繁体   中英

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

I'm new to pine script and trying to calculate and plot the average low prices in premarket unfortunately my code does not seems to work properly and I cannot find the reason as to why

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)

This code results in this mess: Graph

Would be very thankful if someone could point me in the right direction!

The issue seems to be either the handling of when values are na, or using barstate. Regarding na values the script allows for the possibility of calculating on na values, you must either use nz() to render the value 0 that or use na() to test for the condition and act accordingly. I'm not certain if barstate is causing the issues, but it shouldn't be necessary.

//@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)

It is important to be careful with na values, as you don't know when your script will begin execution. It could start in the middle of pre-market, meaning that it's using averageLow to calculate averageLow when averageLow is na.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM