Search code examples
pine-scriptcandlesticks

Pinescript: Plot A Shape whenever candlestick that fulfills condition A crosses candlestick that fulfills condition B (within a lookback period)


Apologies if the below sounds elementary but basically I would like to plot a shape/signal whenever candlestick that fulfills condition A cross under candlestick that fulfills condition B (within a lookback period).

Example:

Condition A = low < low[1] and close > low[1] Condition B = close [1] < low[2] and open < close

Is there a way for me to do it while also adding a lookback period (example, 5 bars, so Condition A candlestick will look to the left 5 bars to see whether it cross any Condition B candlestick)?

Thanks!!

Crossover and lookback periods


Solution

  • inferring that you want to get a signal if ConditionA is true now, and conditionB has been true in 1 of the last X candles

    you have two options to do this:

    1- hardcoding:

    ConditionA = low < low[1] 
    ConditionB = close[1] < low[2] 
    signal = ConditionA and (ConditionB[1] or ConditionB[2] or ConditionB[3] or ConditionB[4] or ConditionB[5])
    

    this is not an optimal solution as you won't have control over the lookback period.

    2- Suggested Method: using a for loop

    lookback = 10
    conditionA = low < low[1] 
    conditionB = close[1] < low[2] 
    signal = false
    if conditionA
        for i = 1 to lookback 
            if conditionB[i]
                signal := true
                break
    

    this method is better since you can use an input for your look-back period and make it dynamic.

    you can then use

    plotshape()

    to plot a shape when the "Signal" variable is true

    Edit: for the crossover check, edit the "if conditionB[i]" line to the following.

    if conditionB[i] and open[0] > close[i] and close[0] < close[i]