I'm getting the error below when running the code below. I've been trying many things to try and format the ‘stop_loss’ and ‘take_profit’ variables, but I can't seem to fix it.
#region imports
from AlgorithmImports import *
#endregion
import numpy as np
import pandas as pd
class GapAndGoAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2023, 1, 1) # Set start date
self.SetEndDate(2023, 1, 31) # Set end date
self.SetCash(100000) # Set strategy cash
# Add SPY to the universe and request daily data for it
self.AddEquity("SPY", Resolution.Daily)
# Use universe selection to select a universe of stocks that are gapping up
self.UniverseSettings.Resolution = Resolution.Daily
self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
self.SelectionCount = 10
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin) # Set brokerage model
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen("SPY", 30), self.GapAndGo) # Schedule GapAndGo function to run after market open
def CoarseSelectionFunction(self, coarse):
# Select only stocks with a price above $5 and a daily dollar volume above $10,000,000
selected = [x.Symbol for x in coarse if x.Price > 5 and x.DollarVolume > 10000000]
return selected
def FineSelectionFunction(self, fine):
# Select stocks that gapped up at least 1% and have positive earnings and revenue growth
fine = [x for x in fine if hasattr(x.EarningReports, 'BasicEPSGrowth') and x.EarningReports.BasicEPSGrowth.OneYear > 0 and x.FinancialStatements.RevenueGrowth.OneYear > 0]
fine = [x for x in fine if (x.Open - x.Close[-2])/x.Close[-2] > 0.01]
fine = sorted(fine, key=lambda x: (x.Volume, x.Price), reverse=True)[:self.SelectionCount]
return [x.Symbol for x in fine]
def GapAndGo(self):
# Loop over all securities in the portfolio
for security in self.Portfolio.Values:
# Check if the security is currently tradable
if not self.Securities[security.Symbol].IsTradable:
continue
# Get daily historical data for the last 2 days
history = self.History([security.Symbol], 2, Resolution.Daily)
# Get opening and closing prices for the last 2 days
opens = history.loc[security.Symbol].open.values
closes = history.loc[security.Symbol].close.values
# Check if the open price today is greater than the close price of yesterday
if opens[-1] > closes[-2]:
# Calculate the percentage change between the two days
pct_change = (closes[-1] - closes[-2]) / closes[-2]
# If the percentage change is greater than 1% (i.e., a gap), execute a trade
if pct_change > 0.01:
# Calculate the stop loss and take profit levels based on the current price
current_price = self.Securities[security.Symbol].Price
stop_loss = np.array([current_price * 0.98]).item()
take_profit = np.array([current_price * 1.02]).item()
# Place the market order with stop loss and take profit levels
self.MarketOrder(security.Symbol, 100, False, None, stop_loss, take_profit)
Runtime Error: Trying to dynamically access a method that does not exist throws a TypeError exception. To prevent the exception, ensure each parameter type matches those required by the 'float'>) method. Please checkout the API documentation.
at GapAndGo
self.MarketOrder(security.Symbol in main.py: line 65
Non Compete
Where did you see you can set the market order with the stop price / take profit price? i think those would need to be different orders. for example
by the way, if you look at your orders in cloud backtest results, it will always say the stop order is filled when you submit it. It actually closes when the price is hit, but the orders doesnt show that.
Nico Xenox
Hey Michael Kvalvik,
Non Compete is right. The way that you set up the MarketOrder is not right. If you want to set SL&TP you could use Limit and stop orders. I also modified the code a little bit so that the sl&tp is calculated from the average fill price and not the price of the stock. Furthermore I added the OnorderEvent so that it cancels open orders if either the stop loss or take profit is hit.
Hope it helps 😊
Best, Nico
Michael Kvalvik
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!