How to deal with delisted stocks showing up in trade list

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

Also check Pad & align settings.

"How do I exit a position in a backtest prior to a stock being delisted?"

1 Like

The code you posted definitely will not work if you’re using Pad & Align.

Here is the solution that I found under another posting title. Many thanks to Trendsurfer for this. It seems to have fixed my issue.

// ====================================================================================
//>>>>>>>>>>>>>>   Code to control entries, exits of delisted stocks
//source: TrendSurfer
// ====================================================================================
dt = DateTime();
bi = BarIndex();
delistedSecurity = Nz(DateTimeDiff(dt, GetFnData("DelistingDate")) >= 0);
barsBeforeDelisting = LastValue(ValueWhen(dt == GetFnData("DelistingDate"), bi, 1)) -bi;
// Incorporate into your Buy rules (Don't Buy if true)
OnLastTwoBarsOfDelistedSecurity = barsBeforeDelisting == 2 OR barsBeforeDelisting == 1; 
Buy = Buy AND NOT (OnLastTwoBarsOfDelistedSecurity OR delistedSecurity);
Sell = Sell OR barsBeforeDelisting == 1;
// ===================================================================================