Attached is my code that throws an exceptions trying to add multiple indicators for multiple equity and use it in OnData. complains that data is not found. What am i doing wrong?
#region imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Drawing;
using QuantConnect;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Parameters;
using QuantConnect.Benchmarks;
using QuantConnect.Brokerages;
using QuantConnect.Util;
using QuantConnect.Interfaces;
using QuantConnect.Algorithm;
using QuantConnect.Indicators;
using QuantConnect.Data;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Custom;
using QuantConnect.DataSource;
using QuantConnect.Data.Fundamental;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Slippage;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using QuantConnect.Securities.Forex;
using QuantConnect.Securities.Crypto;
using QuantConnect.Securities.Interfaces;
using QuantConnect.Storage;
using QuantConnect.Data.Custom.AlphaStreams;
using QCAlgorithmFramework = QuantConnect.Algorithm.QCAlgorithm;
using QCAlgorithmFrameworkBridge = QuantConnect.Algorithm.QCAlgorithm;
#endregion
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Concurrent;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests a wide variety of liquid and illiquid stocks together, with bins
/// of 20 ranging from micro-cap to mega-cap stocks.
/// </summary>
public class MACDCrossOverAlgorithmMultipleStocks : QCAlgorithm
{
public List<SymbolData> Data;
private const decimal TargetPercent = 0.1m;
public override void Initialize()
{
SetStartDate(2011, 1, 1);
SetWarmup(1000);
SetCash(10000);
Data = new List<SymbolData> {
new SymbolData(this, AddEquity("TQQQ", Resolution.Daily).Symbol),
new SymbolData(this, AddEquity("SQQQ", Resolution.Daily).Symbol),
new SymbolData(this, AddEquity("NUGT", Resolution.Daily).Symbol),
new SymbolData(this, AddEquity("SPY", Resolution.Daily).Symbol)
};
}
public override void OnData(Slice data)
{
foreach (var sd in Data)
{
if (!Portfolio.Invested && sd.IsCrossed && data.Bars[sd.Symbol].Price > sd.EMA200)
{
SetHoldings(sd.Symbol, 0.01);
}
else if (Portfolio.Invested && !sd.IsCrossed)
{
Liquidate(sd.Symbol);
}
}
}
public class SymbolData
{
public Symbol Symbol;
public readonly ExponentialMovingAverage EMA200;
public readonly MovingAverageConvergenceDivergence MACD;
public bool IsCrossed => SignalDeltaPercent > 0;
public SymbolData(QCAlgorithm algorithm, Symbol symbol) {
Symbol = symbol;
MACD = algorithm.MACD(symbol, 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily);
EMA200 = algorithm.EMA(symbol, 200, Resolution.Daily);
}
public decimal SignalDeltaPercent
{
get
{
if (MACD.Fast == 0) return 0;
return (MACD - MACD.Signal) / MACD.Fast;
}
}
}
}
}
System.Exception: 'TQQQ' wasn't found in the TradeBars object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey("TQQQ") in DataDictionary.cs:line 228 ---> System.Collections.Generic.KeyNotFoundException: 'TQQQ' wasn't found in the TradeBars object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey("TQQQ") at QuantConnect.Data.Market.DataDictionary`1.get_Item(Symbol symbol) in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/Lean/Common/Data/Market/DataDictionary.cs:line 228 at QuantConnect.Data.Market.TradeBars.get_Item(Symbol symbol) in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/Lean/Common/Data/Market/TradeBars.cs:line 59 at QuantConnect.Algorithm.CSharp.MACDCrossOverAlgorithmMultipleStocks.OnData(Slice data) in /home/lean-user/workspace/project/Main.cs:line 95 at QuantConnect.Lean.Engine.AlgorithmManager.Run(AlgorithmNodePacket job, IAlgorithm algorithm, ISynchronizer synchronizer, ITransactionHandler transactions, IResultHandler results, IRealTimeHandler realtime, ILeanManager leanManager, IAlphaHandler alphas, CancellationToken token) in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/Lean/Engine/AlgorithmManager.cs:line 533 --- End of inner exception stack trace ---
Nico Xenox
Hey Rulak,
before accessing the price of the symbols you must check if the data contains any bars. The code should look something like this:
Hope it helps ;)
Rulak
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!