Page 1 of 1

I want to write a code for a buy condition: closing price has been rising for the last 5 bars

Posted: Tue Jun 22, 2021 2:33 pm
by leopjy
Let's say my strategy is to buy a stock that has been rising for the past 5 bars.

I would write something like this:

longCondition = (close > close[1]) and (close[1] > close[2]) and (close[2] > close[3]) and (close[3] > close[4]) and (close[4] > close[5])

However, I have a feeling that there's a simpler way to code this by using a variable that updates itself. I'm not so sure though. How could I improve this?

Re: I want to write a code for a buy condition: closing price has been rising for the last 5 bars

Posted: Tue Jun 29, 2021 6:10 am
by CanYouCatchMe01
You can improve this by making a loop. Then you can easily choose how many days the stock should have gone up before you make a trading decision. I made a script that plots an "X" when the price has gone up for 5 days.

Image

This function checks if the price had gone down the 5 previous days. If all prices had gone up, then the function returns true. If a price has gone down, the function returns false.

Code: Select all

days_up = input(defval = 5, title = "Buys when value has been up this many days")

multiple_days_up()=>
    all_up=true //considers all days are up
    
    //Loops throught the 5 previous days
    for i = 0 to days_up-1 //"-1" becuse "+1" in "if statement"
        if (close[i] < close[i+1]) //if price has gone DOWN set "all_up" to false. "break" means the loop stops. No need to continue looping if one bar is DOWN.
            all_up:=false
            break
    
    all_up //Returning
Here is the full script. You can change the value of the "days_up" to choose how many days.

Code: Select all

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CanYouCatchMe

//@version=4
strategy("Up 5 days", overlay=true)
days_up = input(defval = 5, title = "Buys when value has been up this many days")

multiple_days_up()=>
    all_up=true //considers all days are up
    
    //Loops throught the 5 previous days
    for i = 0 to days_up-1 //"-1" becuse "+1" in "if statement"
        if (close[i] < close[i+1]) //if price has gone DOWN set "all_up" to false. "break" means the loop stops. No need to continue looping if one bar is DOWN.
            all_up:=false
            break
    
    all_up //Returning

plotshape(multiple_days_up(), style=shape.xcross, color=color.green)