Hello,

I'm using OnSecuritiesChange to trigger buy and sell the contents of the portfolio when the Universe selection changes. I'm also using self.UniverseSettings.Leverage = 1.0 for specific reasons. The challenge is the engine tries to execute both BUY and SELL as soon as it can, however, the buy orders are executed before the sell orders. The code is written with sales first but this has no impact. The result is the buy orders are marked 'invalid' due to lack of margin, and the portfolio is left empty for one iteration.

def OnSecuritiesChanged(self, change):
               
        # liquidate securities that were removed from the universe
        for security in change.RemovedSecurities:
            if self.Portfolio[security.Symbol].Invested:
                self.Liquidate(security.Symbol)

        count = len(change.AddedSecurities)
        
        # evenly invest on securities that were newly added to the universe
        for security in change.AddedSecurities:
            self.SetHoldings(security.Symbol, 1.0/count)

Resulting "invalid" trades:

77031_1572293375.jpg

How can I specify to execute SELL orders first when the trigger for my event is OnSecuritiesChange?