I am currently having two problems. The first problem is my algorithm keeps making trades @ 00:00:00. I then changed the order to a MarketOrder, but the same thing happens (It just gets filled at Market Open) I tried writing some code so the Algo can only account for prices during open market and stop pre/post-market trade request.
usa_after_hours = True
#opentime = self.TimeRules.At(9, 30)
#closetime = self.TimeRules.At(15, 59, 45)
#if int(self.time) >= int(opentime) and <= int(closetime):
#usa_after_hours = False
'''I put the int() after i tried it without int()'''
'''I then went on and tried this, which also isnt working'''
if self.IsMarketOpen:
usa_after_hours = False
elif not self.IsMarketOpen:
usa_after_hours = True
if not self.Portfolio.Invested and already_traded and not usa_after_hours:
none of these seem to work and "usa_after_hours" is either stated to be already defined or not defined in the error logs. I saw something about SetMarketHours in an already closed discussion but I couldn't find it the API or documents.
The second problem is I am trying to create a T/F variable that only allows one entry trade in a given period. I named it "already_traded", but that also seems to be not working. So I am assuming that I am not using T/F statements correctly because I have seen QC algorithms use T/F as part of determining to get into a trade or not.
Teddy Brosevelt
I'm not really that good at writing python but I believe this example from Algorithm.Python\BubbleAlgorithm.py answers your question. If not, I do appologize.
"and self.Time.hour > 9 and self.Time.minute > 30:" or "and self.Time.hour < 16 and self.Time.minute < 30:"
# Order stock based on MACD # During market hours, stock is trading, and sufficient cash if self.Securities[stock].Holdings.Quantity == 0 and self._rsiDic[stock].Current.Value < 70 \ and self.Securities[stock].Price != 0 \ and self.Portfolio.Cash > self.Securities[stock].Price * 100 \ and self.Time.hour == 9 and self.Time.minute == 31: self.BuyStock(stock) # Utilize RSI for overbought territories and liquidate that stock if self._rsiDic[stock].Current.Value > 70 and self.Securities[stock].Holdings.Quantity > 0 \ and self.Time.hour == 9 and self.Time.minute == 31: self.SellStock(stock)
Teddy Brosevelt
Actually, you could use it as is and execute your daily buy/sell at 9:31am.
Ez Buckets
Eric Davis, I don't think that fully solves either one of my problems. But I'll keep giving it a look and see what I can do with it. Thank you. But if you have another way that you could code in C# I have no problem looking at it and translating into python.
Teddy Brosevelt
Ah, I see your problem now. I had not really thought about it prior to this but here's how I did it in c#. If you set an hourly schedule, make sure you set the appropriate resolution for the algo.
First I created a counter and a trade hours bool.
private bool _tradingEnabled = true; private int _tradeCounter = 0;
Second I created a schedule to fire every hour resetting the trade counter.
Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromMinutes(60)), () => { _tradeCounter = 0; });
Then I created a method to toggle trading hours on and off.
// Enables and disables trading based on time. private void TradingHoursToggle() { if (Time.Hour == 9 && Time.Minute == 30) { _tradingEnabled = true; } if (Time.Hour == 4 && Time.Minute == 0) { _tradingEnabled = false; } }
Finally I threw everything in OnData and put an increment for the counter in the buy method and a conditional statement saying if more than 1 trade has been made, then another one can't be made till the schedule fires and resets the trade counter.
//Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol. public void OnData(TradeBars data) { // If the deadmans switch is enabled, the algorithm must be restarted before we can trade again. if (_deadmansSwitchTripped == true) return; // Verify we can trade TradingHoursToggle(); // Check to see if we need to enable the deadmans switch to liquidate everything and stop all trading //DeadmansSwitch(); // Check to make sure our stock didn't drop below the drawdown limit. TrailingStop(); // Liquidate the security when it's no longer at the top of the rankings list. if (_changes.RemovedSecurities.Count > 0) { // liquidate removed securities foreach (var security in _changes.RemovedSecurities) { if (security.Invested && _tradingEnabled == true) { Liquidate(security.Symbol); Debug("Liquidated Stock due to security being removed: " + security.Symbol.Value); } } } // liquidate removed securities foreach (var security in Securities) { if (!security.Value.Invested && _tradingEnabled == true && _tradeCounter < 1) { SetHoldings(security.Key, 1m / _numberOfSymbolsFine); Debug("Purchased Stock due to security being added: " + security.Key); _tradeCounter++; } } }
Teddy Brosevelt
You could also create a trade queue (List) and have the schedule fire every minute, trying to sell everything in the trade queue after the market opens.
Ez Buckets
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!