I see you already have a piece of code at the end of the OnTimer() function that handles object deletion, however it's incorrect.
First, you need to cycle through objects backwards because you'll be deleting them.
Second, you already have a relevant ticket in each object. Just get that ticket value and check whether a respective position exists (using PositionSelectByTicket
) and if not, delete the object.
PS: If you are hard set on using HistoryOrdersTotal
, you need to call HistorySelect
first.