Hi Everyone,
Goal: For a filtered universe of stocks, each symbol is checked in OnData to verify that it isn't already invested and that it doesn't have open orders of any type (unfilled, partially filled, filled, etc.) because I don't want to accidently attempt to double place an order.
In an attempt to check for if I'm invested in a symbol, I tried using ‘and not Portfolio[symbol].Invested’ from another community post but it's not working, giving me an error, 'name 'Portfolio' is not defined at OnData'
Guidance on this is appreciated!
def Initialize(self):
#other stuff
self.Data = {}
def OnData(self, data):
for symbol in self.Data.keys():
symbolData = self.Data[symbol]
if not symbolData.IsReady:
continue
if symbolData.Bars[0].Open < symbolData.Bars[0].Close and not Portfolio[symbol].Invested: #error here
self.MarketOrder(symbol, 100)
self.Log("MarketOrder was placed for symbol " + str(symbol))
def CoarseSelectionFilter(self, coarse):
if self.Time <= self.rebalanceTime: #checks if it has been 1 day since rebalancing
return self.Universe.Unchanged #if not do not change the universe
self.rebalanceTime = self.Time + timedelta(1) #set rebalance time to 1 day
sortedByDollarVolume = sorted(coarse, key=lambda c: c.DollarVolume, reverse=True)
symbols_by_price = [c.Symbol for c in sortedByDollarVolume if c.Price > 50 and c.Price < 100 and c.HasFundamentalData and c.Volume > 100000]
self.filteredByPrice = symbols_by_price[:100]
return self.filteredByPrice
def FineSelectionFilter(self, fine):
sortedByMarketCap = sorted(fine, key=lambda c: c.MarketCap)
symbols_by_marketcap = [c.Symbol for c in sortedByMarketCap if c.MarketCap > 0]
self.filteredBymarketcap = symbols_by_marketcap[:100]
return self.filteredBymarketcap
def OnSecuritiesChanged(self, changes):
for security in changes.AddedSecurities:
symbol = security.Symbol
if symbol not in self.Data:
self.Data[symbol] = SymbolData(self, symbol)
for security in changes.RemovedSecurities:
symbol = security.Symbol
if symbol in self.Data:
symbolData = self.Data.pop(symbol, None)
self.SubscriptionManager.RemoveConsolidator(symbol, symbolData.consolidator)
class SymbolData:
def __init__(self, algorithm, symbol):
self.algorithm = algorithm
self.symbol = symbol
self.Bars = RollingWindow[TradeBar](10) # Rolling window for data bars
self.consolidator = TradeBarConsolidator(timedelta(days=1))
self.consolidator.DataConsolidated += self.OnDataConsolidated
algorithm.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
def OnDataConsolidated(self, sender, bar):
self.Bars.Add(bar)
@property
def IsReady(self):
return self.Bars.IsReady
Adam W
Don't forget the `self` in front of `self.Portfolio[symbol].Invested`, since it is method inherited from the base algorithm class. Also the whole algorithm is wrapped in a class like this right?
Justin E
Yes totally didn't see I omitted ‘self.’, it works now! And I do have it wrapped in a class I just didn't copy it over. So that solves the portfolio invested check.
I know for checking order status for a symbol I'll have to probably save the order to a variable and check if it contains the ticker as I loop through each symbol, I just don't know how to do that.
Louis Szeto
Hi Justin
You could fetch all open orders, or open orders of a symbol by self.Transactions.GetOpenOrders.
Best
Louis
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.
Justin E
Good tip, would I use it like this? Checking to see if it contains an order for the symbol?
Justin E
This didn't work, I remembered Lists return False when empty, not None, but this didn't work either.
What did seem to work is checking the list length.
Louis Szeto
Hi Justin
Transactions.GetOpenOrders(symbol) returns a list, using both
should be working, and it did in our trial:
It seems like your other conditions were not met in the if clause.
Best
Louis
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.
Justin E
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!