Search code examples
pine-scriptalgorithmic-trading

How to check if a buy condition met in the last X days in Pine Script?


I have screener function in TradingView. In this script, I want to check if my BUY condition met in the last X days. I tried the code below but it didn't work. How can I achive it?

screener() =>
    //Calculations

    // Determine sell and buy signals
    buyCondition = c[2] == color.red and c[1] == color.red and c == color.green
    buyCondition = buyCondition and timenow - 10 * 24 * 60 * 60 * 1000 <= time

    [buyCondition ]

Solution

  • You need to compare the time of the last condition to the time of the current bar:

    //@version=5
    indicator("Condition in last 10D", "", true)
    buyCondition = ta.rising(close, 5)
    buyInLastTenDays = time - time[nz(ta.barssince(buyCondition))] < 10 * 24 * 60 * 60 * 1000
    
    plotchar(buyCondition, "buyCondition", "•", location.top)
    plotchar(buyInLastTenDays, "buyInLastTenDays", "—", location.bottom)
    plot(ta.barssince(buyCondition), "ta.barssince(buyCondition)", display = display.data_window)