Get number of bars elapsed after buy and buying price in backtest

I am trying to get the number of bars that have elapsed after buying in backtest. I am also trying to get the buying price.

Here is what I did. I am not sure if it works all the time.

bars_elapsed = BarsSince(buy);
buying_price = ValueWhen(Close, buy);

One problem I face is that buy array can be populated with true values after a buy transaction has taken place while the trade is still in place (sell transaction has yet to occur). This will distort the values of bars_elapsed and buying_price.

Did I miss out anything else? What are some better ways to get the number of bars elapsed after buy and buying price?

What are you using for your Buy criteria?

State v Impulse.


1 Like

I will answer my own question.

The repetitive true signals can be removed using ExRem(). So, it shouldn't matter whether the signal is state or impulse as mentioned by @TrendSurfer. Even if it is impulse signal, there will still be repetitive signals except that the signals are less frequent.

ExRem() should be a better solution. Not tested and verified to be working solution yet for me.

buy = ExRem( buy, sell );
sell = ExRem( sell, buy );