Hello all,
I am trying to figure out how to initiate a StopLossOrder in Python.
Here is the code that I have. I'm not sure if I even have the format correct:
# Use 100% of the portfolio to buy XIV.
self.SetHoldings(self.xiv, 1)
# Get the current price of XIV which should be equal to the price that XIV was bought.
StopPrice = self.Securities['XIV'].Price
# Sell all of the XIV holdings if the price drops below StopPrice
self.StopMarketOrder(self.xiv, 0, StopPrice, StopPrice)
Once again, I'm sure that this format is completely wrong, but I can't find a simple "black and white" example.
The end goal of the above code is to buy XIV with all of the portfolio. If the price drops a percentage below what the purchase price was, sell all holdings in XIV.
Thanks in advance
JayJayD
Hey Malachi Bazar,
Please read the docs, there you’ll find the answer to all the basics.
Form the stop market order description you can read:
> Submit a market order when the stop price is reached.
Note that the second argument is quantity, not position.
So, here is an example of what you want to do:
# Use 100% of the portfolio to buy XIV. self.SetHoldings("XIV", 1) # Get the current price of XIV which should be equal to the price that XIV was bought. stop_price = self.Securities['XIV'].Price # Sell all of the XIV holdings if the price drops below StopPrice self.StopMarketOrder(self.xiv, -self.Portfolio['XIV'].Quantity, stop_price)
However, you should take some precautions if you are going to trade this kind of rules in live mode, you know partial fills, invalid order, etc. Also I'd suggest to give some buffer to the stop price, say:
stop_price = self.Securities['XIV'].Price * 0.98
Hope it helps, good luck!
Malachi Bazar
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!