I've used the code listed below and it seems to work sometimes but not in all cases. I'm using Norgate data and the backtest with the issue has a filter set to "S&P 500 current and past" but there are a number of trades at the beginning of the period that are in stocks that were delisted BEFORE the trade entry occurred. The code below was provided by someone else that has been very helpful but it doesn't appear to be working so I'm not going to list him as a source here.
Any guidance you can offer would be much appreciated.
ThisIsLastBar = BarIndex() == LastValue( BarIndex() );
Buy = Buy AND NOT Ref(ThisIsLastBar, 1) AND NOT Ref(ThisIsLastBar,2);
Sell = Sell OR Ref(ThisIsLastBar, 2);
This maybe because of Trade delays, you should detect this "trade delay days" earlier.
So if you have 1 day as trade delay, then
bi = BarIndex();
ThisIsLastBar = bi == LastValue( bi -1 ); // important -1
I see your Ref() but your Trade Delay is not known.
The order is not clear of intent, you should Sell on Ref( ,1) or 2
if ref is confusing
bi = BarIndex();
TradeDelayDay = 1;
ValidBuyBar = bi < LastValue( bi - TradeDelayDay ); // this is state, not signal
LastSellBar = bi == LastValue( bi -TradeDelayDay ); // important -1
Buy = Buy AND ValidBuyBar; // and so on