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:
How can I specify to execute SELL orders first when the trigger for my event is OnSecuritiesChange?
Alexandre Catarino
Hi Miguel Pascual ,
The liquidation orders are executed first.
I don't have the algorithm to verify a thesis, but it looks like the issue arises from this statement:
count = len(change.AddedSecurities)
Say that the algorithm starts with 2 securities A and B:
count = 2 -> 50% A and 50% B
In the next update, B is dropped and C is added:
0% B
count = 1 -> 100% C (invalid because leverage is 1 and A has 50%)
Therefore you need to fix the logic to account for the securities that were not removed in count.
Miguel Pascual
Alexandre,
Thank you for your reply! I will attempt this resolution or post a backtest for further discussion. Thank you for your time.
Miguel Pascual
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!