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: