Your question is a bit confusing because you left the part about the averages out of it. In your image there are three averages – two going up and one going down!
Your code only compares the close of the current candle to the opening prices of the previous candles. If you want to know if they were red or green then you need to do this:
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.