Search code examples
pine-scripttradingtradingview-apiback-testing

Back Test - Check if previous candle has variable or shape was plotted


Im trying to back test and open positions when hidden divergence is detected followed by a stochatic cross up or down.

I'm using this script to detect divergence which just sets a variable pos_hid_div_detected or neg_hid_div_detected when hidden divergence is found. https://uk.tradingview.com/script/n8AGnIZd-Divergence-for-Many-Indicators-v4/

The back test works if hidden divergence and the cross happen on the same candle but the cross up/down can happen after the divergence.

Below has 3 positive hidden divergence found. The first 2 positions do not open as the cross up happens after. In which case the back test positions do not open.

So my question is, is it possible to somehow set a variable on a previous candle to check it had divergence so i can back test these positions opening?

Looking for something like:

openLong = crossUp and (close[1].hasHiddenDivergence or close[2].hasHiddenDivergence)

enter image description here


Solution

  • You should be able to do it using the built in barssince() function. For example, if a div was detected within the last three bars :

    openLong = crossUp and barssince(pos_hid_div_detected) <= 3