Hello, I am inexperienced at coding is anybody willing to help me get a program to work as intended?
Want the program to open one buy order if there are no open positions, buy every 5% drop from the current first open orders fill price, and close orders when at a 5% profit. Hope its not an easily fixable mistake!
# region imports
from AlgorithmImports import *
# endregion
class EmotionalSkyBlueCamel(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2005, 1, 1)
self.SetEndDate(2023, 1, 1)
self.SetCash(100000)
self.svxy = self.AddEquity("SVXY", Resolution.Hour).Symbol
def OnData(self, data):
AccountBalance = self.Portfolio.TotalPortfolioValue
price = self.Securities[self.svxy].Price
UnrealizedProfit = self.Portfolio.TotalUnrealisedProfit
OrderAmount = int((self.Portfolio.TotalPortfolioValue / 100 * 5) / price)
Price5PC = 0
PC = 0
if not self.Portfolio.Invested and not self.Transactions.GetOpenOrders(self.svxy):
Quantity = self.CalculateOrderQuantity(self.svxy, .3)
Price5PC = price * .95
PC = price
self.MarketOrder("SVXY", Quantity)
self.LimitOrder("SVXY", Quantity * -1, price*1.05)
if Price5PC > price:
Quantity = self.CalculateOrderQuantity(self.svxy, .3)
self.MarketOrder("SVXY", Quantity)
self.LimitOrder("SVXY", Quantity * -1, price*1.05)
Price5PC = Price5PC - (PC * .95)
Mia Alissi
Hello 'Benrashi',
From your code, it seems like you are trying to implement a strategy where you buy more of a security when its price drops by 5% from the initial purchase price and sell when the price is 5% higher than the purchase price.
However, there are a few issues with your current implementation:
The variables
Price5PC
andPC
are local to theOnData
method, which means they are reset every timeOnData
is called. You should make them instance variables (i.e., define them in theInitialize
method) so that their values persist across different calls toOnData
.You are not updating
PC
andPrice5PC
after making a new purchase when the price has dropped by 5%.You are not checking if the price has increased by 5% before placing a sell order. You should only place a sell order if the current price is 5% higher than the purchase price.
Here is a revised version of your code that should work as intended:
This code will buy more of the security when its price drops by 5% from the last purchase price and place a limit order to sell when the price is 5% higher than the current purchase price. The
Price5PC
andPC
variables are updated each time a new purchase is made.Please note that this code does not handle the case where the price increases by 5% before a new purchase is made. You might want to add additional logic to handle this case.
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.
Benrashi Jacobson
Hope you can help me here too!
Intent of this program is buying one call & one put at the same time profiting off high volatility. Watched the tutorial video about options trading and after getting the error below back-tested the copy pasted tutorial video code same error, than increased the initial cash balance no change.
“Order Error: ids: [1], Insufficient buying power to complete orders (Value:[498576]), Reason: Id: 1, Initial Margin: 249307.975, Free Margin: 100000.”
Mia Alissi
Hello 'Benrashi',
The error message you're seeing is due to insufficient buying power to complete the orders. This is because the initial margin required for the order is greater than the free margin available in your portfolio.
In your code, you're trying to buy options for the "SVXY" security. However, there are a few issues with your current implementation:
You're trying to set the leverage for the universe settings after adding the securities. The leverage setting should be applied before adding the securities.
In the
BuyOptions
method, you're trying to buy options based on the ask price of the call option. However, the ask price is not necessarily the price at which the order will be filled. It would be safer to use the last traded price or the mean of the bid and ask prices to estimate the order cost.You're trying to buy 1 contract of each option without checking if you have enough buying power. You should check if you have enough buying power before placing the order.
The
BuyOptions
method is not properly defined. It should be defined withself
as the first argument.Here is a revised version of your code that should work as intended:
This code will buy 1 contract of
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.
Benrashi Jacobson
Thanks for the critiques, not certain why it returned insufficient buying power if the code buys two option contracts valued under 200$ each assume I messed up! The code you put in seems a copy of the code I added, changed some of the initial code made no difference.
Mia Alissi
Hello 'Benrashi',
The error message "Insufficient buying power" is returned when the initial margin required for the order is greater than the free margin available in your portfolio. This can happen even if the cost of the contracts is less than your total portfolio value, due to the margin requirements of the brokerage or the leverage setting of your algorithm.
In the code I provided, I made some changes to your original code to address potential issues. However, if you're still encountering the same error, it might be due to the specific options contracts you're trying to buy. The margin requirements for options contracts can vary depending on the underlying security, the strike price, and the expiry date.
One way to debug this issue is to log the ask price, bid price, and last traded price of the options contracts before placing the order. This can give you a better idea of the cost of the contracts and whether you have enough buying power to buy them.
Here's how you can add logging to your code:
This will print the ask price, bid price, and last traded price of the call option to the console. You can do the same for the put option.
If the ask price is significantly higher than your total portfolio value, this could be the reason why you're getting the "Insufficient buying power" error. In this case, you might need to adjust your strategy to only buy contracts that you can afford.
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.
Benrashi Jacobson
Problem fixed, new problem! Wondering how to get this code to work as intended, there are no logs visible in the back-tester even when added to the initialize function, and no buy orders are executing.
Benrashi Jacobson
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!