0
votes

Let's dive right into it. So I'm currently working on an indicator and so, I want to be able to average the closes of red candles only. Problem is, that the solution I've came to averages green candles too for some odd reason, I'll appreciate some help on this one.

averagePastRedCandles(amount) =>
    currentnum = 0.0
    currentreds = 0.0
    for i = 0 to 99999
        if currentreds == amount // end the loop if amount averaged is met
            break
        else
            if open > close // check if the candles is red
                currentreds := currentreds + 1 // basically the current
amount that's already averaged
                currentnum := currentnum + close[i] // the sum of the closes of the red candles only
            continue

    currentnum / amount
2

2 Answers

0
votes

I didn't have yet written a single line of "pine-script" but looking at your code I suppose the problem is here

if open > close // check if the candles is red

you are always doing the check on the last bar.

Maybe the code should be something like:

if open[i] > close[i] // check if the candles is red

?

0
votes

Welcome to Stack overflow. Here is a neat code for you with comments.

//@author=lucemanb
//@version=4
study("Red Candles Average")

averagePastRedCandles(amount) =>
    // number of counted candles
    candles = 0
    // current average
    sum = 0.0
    // check if the number of candles so far has exceeded the amount of bars on the chart
    if bar_index > amount
        // start counting with a limit of the current bars in chart
        for i=0 to bar_index - 1
            // confirm if the candle is red
            if open[i] > close[i]
                // add the average
                sum := sum + close[i]
                // add count of the candles we have counted
                candles := candles + 1
            // check if we have reached the amount of the candles that we want
            if candles == amount
                //close the loop
                break
    // return the average
    avarege = sum/amount

s = averagePastRedCandles(10)
plot(s)

Enjoy 😋