Hi all,
Not too sure why my live trading - after it runs the algo and fits the criteria, it bought the options, but it didnt subsequently submitted the profit taking limit order in the algo. Can someone please assist with this.
The following is the code i use to check if it should buy the call options or not.
def BuyCall(self,chains):
self.S = self.Securities[self.equity].Close
expiry = sorted(chains,key = lambda x: x.Expiry, reverse=True)[0].Expiry
calls = [i for i in chains if i.Expiry == expiry and i.Right == OptionRight.Call]
call_contracts = sorted(calls,key = lambda x: abs(x.Strike - x.UnderlyingLastPrice < 0))
if len(call_contracts) == 0:
self.Debug("No Contracts Found")
return
self.Log("Contracts Found!")
self.call = call_contracts[0]
self.K = self.call.Strike
self.T = ((self.call.Expiry - self.Time).days)/(365)
option_invested = [x.Key for x in self.Portfolio if x.Value.Invested and x.Value.Type==SecurityType.Option]
if (option_invested):
for i in range(len(option_invested)):
if (str(self.Portfolio[option_invested[i]].Symbol.Value) == str(self.call)):
self.Log("Already bought the Contract")
return
if self.r is None:
history = self.History(USTreasuryYieldCurveRate, self.yieldCurveTwo, 60, Resolution.Daily)
twoyear = history['twoyear'][-1]
self.r = twoyear / 100
self.Debug((f"| Previous Rates Used -- Succesful {self.Time} -- {self.r}"))
self.option_price = self.BlackScholesCall(self.S, self.K, self.T, self.r, self.sigma)
self.Log((f"| Option Price Calculated - Succesful {self.Time} [+]-- Contracts {str(self.call)} || Stock @ {str(self.call.UnderlyingLastPrice)} Option Price BS @ {(self.option_price)} rates: {self.r} Option Price Market @ {self.call.AskPrice} DTE @ {(self.call.Expiry - self.Time).days}"))
if self.call.AskPrice > self.option_price:
self.Log((f"| Option too Expensive! {self.Time})"))
return
if self.call.AskPrice == 0: return
self.SetHoldings(self.call.Symbol, 0.5)
quantity = self.Portfolio[self.call.Symbol].Quantity # <-- quantity is zero and the following orders will be invalid
if quantity != 0:
self.LimitOrder(self.call.Symbol, -quantity, (self.call.AskPrice * self.Profit_Taking))
self.Log ("\r+-------------")
self.Log (f"| {self.Time} [+] Bought Contracts -- {str(self.call)}")
self.Log(f"Order Quantity filled: {self.Portfolio[self.call.Symbol].Quantity}; Fill price: {self.Portfolio[self.call.Symbol].AveragePrice} Limit price: {self.call.AskPrice * self.Profit_Taking}")
self.LastTime = self.Time.day
self.Log ("\r+-------------")
else: self.Log(f"| {self.Time} -- No Money")
Mia Alissi
From the code you've shared, it seems like you're trying to place a limit order to take profit after buying a call option. However, you're checking the quantity of the option in your portfolio immediately after placing the order to buy the option.
In live trading, orders are not filled immediately. It takes some time for the order to be sent to the exchange, executed, and the confirmation to be sent back. Therefore, the quantity of the option in your portfolio would still be zero immediately after you place the order.
To handle this, you should place the limit order in the
OnOrderEvent
method, which is called whenever an order event (like an order fill) happens. Here's an example of how you can do this:This code checks if an order has been filled. If it has, and the filled order is for an option that is currently in the portfolio, it places a limit order to sell the option at your profit taking price.
Please note that this is a simplified example and you might need to adjust it to fit your specific strategy and handle other order events. For more information on handling order events, you can refer to the QuantConnect documentation.
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.
Muhammad Yusuf Bin Salleh
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!