Beispiel #1
0
        /// <summary>
        /// Add specified data to required list. QC will funnel this data to the handle data routine.
        /// </summary>
        /// <param name="securityType">MarketType Type: Equity, Commodity, Future or FOREX</param>
        /// <param name="symbol">Symbol Reference for the MarketType</param>
        /// <param name="resolution">Resolution of the Data Required</param>
        /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param>
        /// <param name="leverage">Custom leverage per security</param>
        /// <param name="extendedMarketHours">Extended market hours</param>
        /// <remarks> AddSecurity(SecurityType securityType, string symbol, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)</remarks>
        public void AddSecurity(SecurityType securityType, string symbol, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)
        {
            try
            {
                if (!_locked)
                {
                    symbol = symbol.ToUpper();
                    //If it hasn't been set, use some defaults based on the portfolio type:
                    if (leverage <= 0)
                    {
                        switch (securityType)
                        {
                        case SecurityType.Equity:
                            leverage = 2;       //Cash Ac. = 1, RegT Std = 2 or PDT = 4.
                            break;

                        case SecurityType.Forex:
                            leverage = 50;
                            break;
                        }
                    }

                    // add currencies for forex types
                    if (securityType == SecurityType.Forex)
                    {
                        if (symbol.Length != 6)
                        {
                            throw new ArgumentException("Unexpected currency pair format: " + symbol + ". Expected symbol of length 6, 3 characters per currency.");
                        }
                        // decompose the symbol into each currency pair
                        string left  = symbol.Substring(0, 3);
                        string right = symbol.Substring(3);
                        if (!Portfolio.CashBook.ContainsKey(left))
                        {
                            // since we have none it's safe to say the conversion is zero
                            Portfolio.CashBook.Add(left, 0, 0);
                        }
                        if (!Portfolio.CashBook.ContainsKey(right))
                        {
                            // since we have none it's safe to say the conversion is zero
                            Portfolio.CashBook.Add(right, 0, 0);
                        }
                    }

                    //Add the symbol to Data Manager -- generate unified data streams for algorithm events
                    var config = SubscriptionManager.Add(securityType, symbol, resolution, fillDataForward, extendedMarketHours);

                    //Add the symbol to Securities Manager -- manage collection of portfolio entities for easy access.
                    Securities.Add(symbol, config, leverage, isDynamicallyLoadedData: false);
                }
                else
                {
                    throw new Exception("Algorithm.AddSecurity(): Cannot add another security after algorithm running.");
                }
            }
            catch (Exception err)
            {
                Error("Algorithm.AddSecurity(): " + err.Message);
            }
        }
Beispiel #2
0
        private async void Market_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Securities.Clear();
            Boards.Clear();

            Info    = "";
            History = new List <HistoryObject>();
            FirePropertyChanged(nameof(Info));
            FirePropertyChanged(nameof(History));

            try
            {
                foreach (var item in
                         await Task <IEnumerable <Item> > .Run(() =>
                {
                    return(new MarketSecuritiesListRequest(Engine.Value, Market.Value).Response.Securities.Data.Select(d =>
                                                                                                                       new Item
                    {
                        Name = $"{d["SECID"]}",
                        Value = d["SECID"],
                        Data = d
                    }).Distinct(new ItemEqvCmp()));
                }))
                {
                    Securities.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
Beispiel #3
0
        public Security AddSecurity(string securitySymbol)
        {
            Security security = new Security(securitySymbol);

            Securities.Add(securitySymbol, security);
            return(security);
        }
Beispiel #4
0
        /// <summary>
        /// Create a new security and add it to the feed so it receives events
        /// </summary>
        /// <param name="securitySymbol">Security symbol</param>
        public Security AddSecurity(string securitySymbol)
        {
            Security result = new Security(securitySymbol);

            Securities.Add(securitySymbol, result);
            return(result);
        }
Beispiel #5
0
        /// <summary>
        /// Called by setup handlers after Initialize and allows the algorithm a chance to organize
        /// the data gather in the Initialize method
        /// </summary>
        public void PostInitialize()
        {
            // if the benchmark hasn't been set yet, set it
            if (Benchmark == null)
            {
                // apply the default benchmark if it hasn't been set
                if (_benchmarkSymbol == Symbol.Empty)
                {
                    _benchmarkSymbol       = new Symbol("SPY");
                    _benchmarkSecurityType = SecurityType.Equity;
                }

                // if the requested benchmark system wasn't already added, then add it now
                Security security;
                if (!Securities.TryGetValue(_benchmarkSymbol, out security))
                {
                    // add the security as an internal feed so the algorithm doesn't receive the data
                    var resolution = _liveMode ? Resolution.Second : Resolution.Daily;
                    var market     = _benchmarkSecurityType == SecurityType.Forex ? "fxcm" : "usa";
                    security = SecurityManager.CreateSecurity(Portfolio, SubscriptionManager, _exchangeHoursProvider, _benchmarkSecurityType, _benchmarkSymbol, resolution, market, true, 1m, false, true, false);
                    Securities.Add(_benchmarkSymbol, security);
                }

                // just return the current price
                Benchmark = dateTime => security.Price;
            }
        }
        /// <summary>
        /// Adds the security to the user defined universe for the specified
        /// </summary>
        private void AddToUserDefinedUniverse(Security security)
        {
            Securities.Add(security);

            // add this security to the user defined universe
            UserDefinedUniverse universe;
            var key = new SecurityTypeMarket(security.Type, security.SubscriptionDataConfig.Market);

            if (_userDefinedUniverses.TryGetValue(key, out universe))
            {
                universe.Add(security.Symbol);
            }
            else
            {
                // create a new universe, these subscription settings don't currently get used
                // since universe selection proper is never invoked on this type of universe
                var securityConfig = security.SubscriptionDataConfig;
                var universeSymbol = UserDefinedUniverse.CreateSymbol(securityConfig.SecurityType, securityConfig.Market);
                var uconfig        = new SubscriptionDataConfig(securityConfig, symbol: universeSymbol, isInternalFeed: true, fillForward: false);
                universe = new UserDefinedUniverse(uconfig,
                                                   new UniverseSettings(security.Resolution, security.Leverage, security.IsFillDataForward, security.IsExtendedMarketHours, TimeSpan.Zero),
                                                   QuantConnect.Time.OneDay,
                                                   new List <Symbol> {
                    security.Symbol
                }
                                                   );
                _userDefinedUniverses[key] = universe;

                UniverseManager.Add(universe.Configuration.Symbol, universe);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Adds the security to the user defined universe for the specified
        /// </summary>
        private void AddToUserDefinedUniverse(Security security)
        {
            // if we are adding a non-internal security which already has an internal feed, we remove it first
            Security existingSecurity;

            if (Securities.TryGetValue(security.Symbol, out existingSecurity))
            {
                if (!security.IsInternalFeed() && existingSecurity.IsInternalFeed())
                {
                    var securityUniverse = UniverseManager.Select(x => x.Value).OfType <UserDefinedUniverse>().FirstOrDefault(x => x.Members.ContainsKey(security.Symbol));
                    securityUniverse?.Remove(security.Symbol);

                    Securities.Remove(security.Symbol);
                }
            }

            Securities.Add(security);

            // add this security to the user defined universe
            Universe universe;
            var      subscription   = security.Subscriptions.First();
            var      universeSymbol = UserDefinedUniverse.CreateSymbol(subscription.SecurityType, subscription.Market);

            if (!UniverseManager.TryGetValue(universeSymbol, out universe))
            {
                // create a new universe, these subscription settings don't currently get used
                // since universe selection proper is never invoked on this type of universe
                var uconfig = new SubscriptionDataConfig(subscription, symbol: universeSymbol, isInternalFeed: true, fillForward: false);

                if (security.Type == SecurityType.Base)
                {
                    // set entry in market hours database for the universe subscription to match the custom data
                    var symbolString = MarketHoursDatabase.GetDatabaseSymbolKey(uconfig.Symbol);
                    MarketHoursDatabase.SetEntry(uconfig.Market, symbolString, uconfig.SecurityType, security.Exchange.Hours, uconfig.DataTimeZone);
                }

                universe = new UserDefinedUniverse(uconfig,
                                                   new UniverseSettings(security.Resolution, security.Leverage, security.IsFillDataForward, security.IsExtendedMarketHours, TimeSpan.Zero),
                                                   SecurityInitializer,
                                                   QuantConnect.Time.MaxTimeSpan,
                                                   new List <Symbol> {
                    security.Symbol
                }
                                                   );
                UniverseManager.Add(universeSymbol, universe);
            }

            var userDefinedUniverse = universe as UserDefinedUniverse;

            if (userDefinedUniverse != null)
            {
                userDefinedUniverse.Add(security.Symbol);
            }
            else
            {
                // should never happen, someone would need to add a non-user defined universe with this symbol
                throw new Exception("Expected universe with symbol '" + universeSymbol.Value + "' to be of type UserDefinedUniverse.");
            }
        }
        private void GetAllSecurities(DBContext dbContext)
        {
            List <TradableSecurity> securities = dbContext.Security.AsNoTracking().ToList();

            foreach (var security in securities)
            {
                Securities.Add(security.Ticker, security);
            }
        }
Beispiel #9
0
        /// <summary>
        /// AddData<typeparam name="T"/> a new user defined data source, requiring only the minimum config options.
        /// </summary>
        /// <param name="symbol">Key/Symbol for data</param>
        /// <param name="resolution">Resolution of the Data Required</param>
        /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param>
        /// <param name="leverage">Custom leverage per security</param>
        /// <remarks>Generic type T must implement base data</remarks>
        public void AddData <T>(string symbol, Resolution resolution, bool fillDataForward, decimal leverage = 1.0m)
        {
            if (_locked)
            {
                return;
            }

            //Add this to the data-feed subscriptions
            SubscriptionManager.Add(typeof(T), SecurityType.Base, symbol, resolution, fillDataForward, extendedMarketHours: true);

            //Add this new generic data as a tradeable security:
            Securities.Add(symbol, SecurityType.Base, resolution, fillDataForward, leverage, extendedMarketHours: true, isDynamicallyLoadedData: true);
        }
Beispiel #10
0
        /// <summary>
        /// Add a new user defined data source, requiring only the minimum config options:
        /// </summary>
        /// <param name="type">typeof(Type) data</param>
        /// <param name="symbol">Key/Symbol for data</param>
        public void AddData <T>(string symbol, Resolution resolution = Resolution.Second)
        {
            if (!_locked)
            {
                //Add this to the data-feed subscriptions
                SubscriptionManager.Add(typeof(T), SecurityType.Base, symbol, resolution, fillDataForward: false, extendedMarketHours: true);

                //Add this new generic data as a tradeable security:
                // Defaults:extended market hours"      = true because we want events 24 hours,
                //          fillforward                 = false because only want to trigger when there's new custom data.
                //          leverage                    = 1 because no leverage on nonmarket data?
                Securities.Add(symbol, SecurityType.Base, resolution, fillDataForward: false, leverage: 1, extendedMarketHours: true, useQuantConnectData: false);
            }
        }
Beispiel #11
0
        private void SearchCallback(List <Instrument> instruments, bool hasMoreResults)
        {
            var lastAddedInstrumentId = 0;

            lock (Securities)
            {
                foreach (var instrument in instruments)
                {
                    if (_securities.ContainsKey((int)instrument.Id) || instrument.Name.Contains("weekend"))
                    {
                        continue;
                    }

                    var security = new Security
                    {
                        DataFeed       = Name,
                        Symbol         = instrument.Underlying.Symbol,
                        Name           = instrument.Name,
                        SecurityId     = (int)instrument.Id,
                        AssetClass     = instrument.Underlying.AssetClass,
                        BaseCurrency   = instrument.Contract.Currency,
                        UnitOfMeasure  = instrument.Contract.UnitOfMeasure,
                        ContractSize   = instrument.Contract.ContractSize,
                        Digit          = Math.Max(instrument.OrderBook.PriceIncrement.ToString().Length - 2, 1),
                        PriceIncrement = instrument.OrderBook.PriceIncrement,
                        MarginRate     = instrument.Risk.MarginRate,
                        MaxPosition    = instrument.Risk.MaximumPosition,
                        UnitPrice      = instrument.Contract.UnitPrice,
                        QtyIncrement   = instrument.OrderBook.QuantityIncrement,
                        MarketOpen     = instrument.Calendar.Open,
                        MarketClose    = instrument.Calendar.Close
                    };

                    Securities.Add(security);
                    NewSecurity?.Invoke(security);
                    _securities[security.SecurityId] = security;
                    Subscribe(security);
                    lastAddedInstrumentId = security.SecurityId;

                    _session.Subscribe(new OrderBookSubscriptionRequest(instrument.Id), () => { }, FailureCallback);
                    _session.Subscribe(new OrderBookStatusSubscriptionRequest(instrument.Id), () => { }, FailureCallback);
                }
            }

            if (hasMoreResults && lastAddedInstrumentId > 0)
            {
                _session.SearchInstruments(new SearchRequest("", lastAddedInstrumentId), SearchCallback, FailureCallback);
            }
        }
Beispiel #12
0
        /// <summary>
        /// AddData<typeparam name="T"/> a new user defined data source, requiring only the minimum config options.
        /// </summary>
        /// <param name="symbol">Key/Symbol for data</param>
        /// <param name="resolution">Resolution of the Data Required</param>
        /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param>
        /// <param name="leverage">Custom leverage per security</param>
        /// <param name="isTradeBar">Set to true if this data has Open, High, Low, and Close properties</param>
        /// <param name="hasVolume">Set to true if this data has a Volume property</param>
        /// <remarks>Generic type T must implement base data</remarks>
        public void AddData <T>(string symbol, Resolution resolution, bool fillDataForward, decimal leverage = 1.0m, bool isTradeBar = false, bool hasVolume = false)
        {
            if (_locked)
            {
                return;
            }

            symbol = symbol.ToUpper();

            //Add this to the data-feed subscriptions
            var config = SubscriptionManager.Add(typeof(T), SecurityType.Base, symbol, resolution, fillDataForward, extendedMarketHours: true, isTradeBar: isTradeBar, hasVolume: hasVolume);

            //Add this new generic data as a tradeable security:
            Securities.Add(symbol, config, leverage, isDynamicallyLoadedData: true);
        }
Beispiel #13
0
        /// <summary>
        /// Add specified data to required list. QC will funnel this data to the handle data routine.
        /// </summary>
        /// <param name="securityType">MarketType Type: Equity, Commodity, Future or FOREX</param>
        /// <param name="symbol">Symbol Reference for the MarketType</param>
        /// <param name="resolution">Resolution of the Data Required</param>
        /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param>
        /// <param name="leverage">Custom leverage per security</param>
        public void AddSecurity(SecurityType securityType, string symbol, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)
        {
            try
            {
                if (!_locked)
                {
                    symbol = symbol.ToUpper();

                    if (securityType != SecurityType.Equity && securityType != SecurityType.Forex)
                    {
                        throw new Exception("We only support Equities or FOREX at this time.");
                    }

                    if (_resolution != "" && _resolution != resolution.ToString())
                    {
                        throw new Exception("We can only accept one resolution at this time. Make all your datafeeds the lowest resolution you require.");
                    }

                    //If it hasn't been set, use some defaults based on the portfolio type:
                    if (leverage <= 0)
                    {
                        switch (securityType)
                        {
                        case SecurityType.Equity:
                            leverage = 1;       //RegT = 2 or 4.
                            break;

                        case SecurityType.Forex:
                            leverage = 50;
                            break;
                        }
                    }

                    //Add the symbol to Data Manager -- generate unified data streams for algorithm events
                    DataManager.Add(securityType, symbol, resolution, fillDataForward, extendedMarketHours);

                    //Add the symbol to Securities Manager -- manage collection of portfolio entities for easy access.
                    Securities.Add(symbol, securityType, resolution, fillDataForward, leverage, extendedMarketHours);
                }
                else
                {
                    throw new Exception("Algorithm.AddSecurity(): Cannot add another security after algorithm running.");
                }
            } catch (Exception err) {
                Error("Algorithm.AddMarketData(): " + err.Message);
            }
        }
Beispiel #14
0
        private void CancelSellOrder(SellOrder order)
        {
            Security security;

            if (!Securities.TryGetValue(order.SecurityName, out security))
            {
                Securities.Add(order.SecurityName, order.ForSale);
            }
            else
            {
                Securities[order.SecurityName].Merge(order.ForSale);
            }
            lock (SellOrders)
            {
                SellOrders.Remove(order);
            }
            Updated?.Invoke(this, this);
        }
Beispiel #15
0
        /// <summary>
        /// AddData<typeparam name="T"/> a new user defined data source, requiring only the minimum config options.
        /// </summary>
        /// <param name="symbol">Key/Symbol for data</param>
        /// <param name="resolution">Resolution of the Data Required</param>
        /// <param name="timeZone">Specifies the time zone of the raw data</param>
        /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param>
        /// <param name="leverage">Custom leverage per security</param>
        /// <remarks>Generic type T must implement base data</remarks>
        public void AddData <T>(Symbol symbol, Resolution resolution, DateTimeZone timeZone, bool fillDataForward = false, decimal leverage = 1.0m)
            where T : BaseData, new()
        {
            if (_locked)
            {
                return;
            }

            //Add this to the data-feed subscriptions
            var config = SubscriptionManager.Add(typeof(T), SecurityType.Base, symbol, resolution, "usa", timeZone, true, fillDataForward, true, false);

            var exchangeHours = _exchangeHoursProvider.GetExchangeHours(config);

            //Add this new generic data as a tradeable security:
            var security = new Security(exchangeHours, config, leverage);

            Securities.Add(symbol, security);
        }
Beispiel #16
0
        private void ExecuteBuyOrder(BuyOrder order)
        {
            Security security;

            if (!Securities.TryGetValue(order.SecurityName, out security))
            {
                Securities.Add(order.SecurityName, order.Security);
            }
            else
            {
                Securities[order.SecurityName].Merge(order.Security);
            }
            lock (BuyOrders)
            {
                BuyOrders.Remove(order);
            }
            Updated?.Invoke(this, this);
        }
        public Option AddChineseOption(string underlying, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = 0m)
        {
            if (market == null)
            {
                if (!BrokerageModel.DefaultMarkets.TryGetValue(SecurityType.Option, out market))
                {
                    throw new Exception("No default market set for security type: " + SecurityType.Option);
                }
            }

            Symbol canonicalSymbol;
            var    alias = "?" + underlying;

            if (!SymbolCache.TryGetSymbol(alias, out canonicalSymbol))
            {
                //canonicalSymbol = QuantConnect.Symbol.Create(underlying, SecurityType.Option, market, alias);
                canonicalSymbol = QuantConnect.Symbol.CreateOption(underlying, market, OptionStyle.European, default(OptionRight), 0, SecurityIdentifier.DefaultDate, alias);
            }

            var marketHoursEntry  = MarketHoursDatabase.FromDataFolder().GetEntry(market, underlying, SecurityType.Option);
            var symbolProperties  = SymbolPropertiesDatabase.FromDataFolder().GetSymbolProperties(market, underlying, SecurityType.Option, CashBook.AccountCurrency);
            var canonicalSecurity = (Option)SecurityManager.CreateSecurity(new List <Type>()
            {
                typeof(ZipEntryName)
            }, Portfolio, SubscriptionManager,
                                                                           marketHoursEntry.ExchangeHours, marketHoursEntry.DataTimeZone, symbolProperties, SecurityInitializer, canonicalSymbol, resolution,
                                                                           fillDataForward, leverage, false, false, false, LiveMode, true, false);

            canonicalSecurity.IsTradable = false;

            Securities.Add(canonicalSecurity);

            // add this security to the user defined universe
            Universe universe;

            if (!UniverseManager.TryGetValue(canonicalSymbol, out universe))
            {
                var settings = new UniverseSettings(resolution, leverage, true, false, TimeSpan.Zero);
                universe = new OptionChainUniverse(canonicalSecurity, settings, SubscriptionManager, SecurityInitializer);
                UniverseManager.Add(canonicalSymbol, universe);
            }

            return(canonicalSecurity);
        }
Beispiel #18
0
        /// <summary>
        /// AddData<typeparam name="T"/> a new user defined data source, requiring only the minimum config options.
        /// </summary>
        /// <param name="symbol">Key/Symbol for data</param>
        /// <param name="resolution">Resolution of the Data Required</param>
        /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param>
        /// <param name="leverage">Custom leverage per security</param>
        /// <param name="isTradeBar">Set to true if this data has Open, High, Low, and Close properties</param>
        /// <param name="hasVolume">Set to true if this data has a Volume property</param>
        /// <remarks>Generic type T must implement base data</remarks>
        public void AddData <T>(string symbol, Resolution resolution, bool fillDataForward, decimal leverage = 1.0m, bool isTradeBar = false, bool hasVolume = false)
        {
            if (_locked)
            {
                return;
            }

            symbol = symbol.ToUpper();

            //Add this to the data-feed subscriptions
            var config = SubscriptionManager.Add(typeof(T), SecurityType.Base, symbol, resolution, "usa", TimeZones.NewYork, fillDataForward, true, isTradeBar, hasVolume, false);

            var exchangeHours = _exchangeHoursProvider.GetExchangeHours(config);

            //Add this new generic data as a tradeable security:
            var security = new Security(exchangeHours, config, leverage, true);

            Securities.Add(symbol, security);
        }
Beispiel #19
0
        private void CreateCommonData()
        {
            var securityIds = Securities.GetSecurityIds().ToHashSet();

            var securities = new List <Security>();

            securities.AddRange(CreateSecurities("RI", securityIds));
            securities.AddRange(CreateSecurities("SR", securityIds));

            if (!securityIds.Contains("SBER@TQBR"))
            {
                securities.Add(new Security
                {
                    Id            = "SBER@TQBR",
                    Code          = "SBER",
                    Board         = ExchangeBoard.MicexTqbr,
                    Type          = SecurityTypes.Stock,
                    ExtensionInfo = new Dictionary <object, object>()
                });
            }

            if (securities.Count > 0)
            {
                securities.ForEach(s => Securities.Add(s));
                Securities.DelayAction.WaitFlush();
            }

            const string pfName = "Simulator";

            if (Portfolios.ReadById(pfName) == null)
            {
                Portfolios.Save(new Portfolio
                {
                    Name          = pfName,
                    BeginValue    = 1000000,
                    Board         = ExchangeBoard.Test,
                    ExtensionInfo = new Dictionary <object, object>()
                });
                Portfolios.DelayAction.WaitFlush();
            }
        }
Beispiel #20
0
        /// <summary>
        /// Set a required SecurityType-symbol and resolution for algorithm
        /// </summary>
        /// <param name="securityType">SecurityType Enum: Equity, Commodity, FOREX or Future</param>
        /// <param name="symbol">Symbol Representation of the MarketType, e.g. AAPL</param>
        /// <param name="resolution">Resolution of the MarketType required: MarketData, Second or Minute</param>
        /// <param name="market">The market the requested security belongs to, such as 'usa' or 'fxcm'</param>
        /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice.</param>
        /// <param name="leverage">leverage for this security</param>
        /// <param name="extendedMarketHours">ExtendedMarketHours send in data from 4am - 8pm, not used for FOREX</param>
        public void AddSecurity(SecurityType securityType, Symbol symbol, Resolution resolution, string market, bool fillDataForward, decimal leverage, bool extendedMarketHours)
        {
            if (_locked)
            {
                throw new Exception("Algorithm.AddSecurity(): Cannot add another security after algorithm running.");
            }

            try
            {
                var security = SecurityManager.CreateSecurity(Portfolio, SubscriptionManager, _exchangeHoursProvider,
                                                              securityType, symbol, resolution, market,
                                                              fillDataForward, leverage, extendedMarketHours, false, false);

                //Add the symbol to Securities Manager -- manage collection of portfolio entities for easy access.
                Securities.Add(security.Symbol, security);
            }
            catch (Exception err)
            {
                Error("Algorithm.AddSecurity(): " + err.Message);
            }
        }
Beispiel #21
0
        /// <summary>
        /// Add specified data to required list. QC will funnel this data to the handle data routine.
        /// </summary>
        /// <param name="securityType">MarketType Type: Equity, Commodity, Future or FOREX</param>
        /// <param name="symbol">Symbol Reference for the MarketType</param>
        /// <param name="resolution">Resolution of the Data Required</param>
        /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param>
        /// <param name="leverage">Custom leverage per security</param>
        /// <param name="extendedMarketHours">Extended market hours</param>
        /// <remarks> AddSecurity(SecurityType securityType, string symbol, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)</remarks>
        public void AddSecurity(SecurityType securityType, string symbol, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)
        {
            try
            {
                if (!_locked)
                {
                    symbol = symbol.ToUpper();
                    //If it hasn't been set, use some defaults based on the portfolio type:
                    if (leverage <= 0)
                    {
                        switch (securityType)
                        {
                        case SecurityType.Equity:
                            leverage = 2;       //Cash Ac. = 1, RegT Std = 2 or PDT = 4.
                            break;

                        case SecurityType.Forex:
                            leverage = 50;
                            break;
                        }
                    }

                    //Add the symbol to Securities Manager -- manage collection of portfolio entities for easy access.
                    Securities.Add(symbol, securityType, resolution, fillDataForward, leverage, extendedMarketHours, isDynamicallyLoadedData: false);

                    //Add the symbol to Data Manager -- generate unified data streams for algorithm events
                    SubscriptionManager.Add(securityType, symbol, resolution, fillDataForward, extendedMarketHours);
                }
                else
                {
                    throw new Exception("Algorithm.AddSecurity(): Cannot add another security after algorithm running.");
                }
            }
            catch (Exception err)
            {
                Error("Algorithm.AddSecurity(): " + err.Message);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Adds the security to the user defined universe for the specified
        /// </summary>
        private void AddToUserDefinedUniverse(Security security)
        {
            Securities.Add(security);

            // add this security to the user defined universe
            Universe universe;
            var      securityConfig = security.SubscriptionDataConfig;
            var      universeSymbol = UserDefinedUniverse.CreateSymbol(securityConfig.SecurityType, securityConfig.Market);

            if (!UniverseManager.TryGetValue(universeSymbol, out universe))
            {
                // create a new universe, these subscription settings don't currently get used
                // since universe selection proper is never invoked on this type of universe
                var uconfig = new SubscriptionDataConfig(securityConfig, symbol: universeSymbol, isInternalFeed: true, fillForward: false);
                universe = new UserDefinedUniverse(uconfig,
                                                   new UniverseSettings(security.Resolution, security.Leverage, security.IsFillDataForward, security.IsExtendedMarketHours, TimeSpan.Zero),
                                                   SecurityInitializer,
                                                   QuantConnect.Time.OneDay,
                                                   new List <Symbol> {
                    security.Symbol
                }
                                                   );
                UniverseManager.Add(universeSymbol, universe);
            }

            var userDefinedUniverse = universe as UserDefinedUniverse;

            if (userDefinedUniverse != null)
            {
                userDefinedUniverse.Add(security.Symbol);
            }
            else
            {
                // should never happen, someone would need to add a non-user defined universe with this symbol
                throw new Exception("Expected universe with symbol '" + universeSymbol.Value + "' to be of type UserDefinedUniverse.");
            }
        }
Beispiel #23
0
        /// <summary>
        /// Adds the security to the user defined universe
        /// </summary>
        /// <param name="security">The security to add</param>
        /// <param name="configurations">The <see cref="SubscriptionDataConfig"/> instances we want to add</param>
        private Security AddToUserDefinedUniverse(
            Security security,
            List <SubscriptionDataConfig> configurations)
        {
            var subscription = configurations.First();

            // if we are adding a non-internal security which already has an internal feed, we remove it first
            if (Securities.TryGetValue(security.Symbol, out var existingSecurity))
            {
                if (!subscription.IsInternalFeed && existingSecurity.IsInternalFeed())
                {
                    var securityUniverse = UniverseManager.Select(x => x.Value).OfType <UserDefinedUniverse>().FirstOrDefault(x => x.Members.ContainsKey(security.Symbol));
                    securityUniverse?.Remove(security.Symbol);

                    Securities.Remove(security.Symbol);
                    Securities.Add(security);
                }
                else
                {
                    var isTradable = security.IsTradable;
                    // We will reuse existing so we return it to the user.
                    // We will use the IsTradable flag of the new security, since existing could of been set to false when removed
                    security            = existingSecurity;
                    security.IsTradable = isTradable;
                }
            }
            else
            {
                Securities.Add(security);
            }

            // add this security to the user defined universe
            Universe universe;
            var      universeSymbol = UserDefinedUniverse.CreateSymbol(security.Type, security.Symbol.ID.Market);

            lock (_pendingUniverseAdditionsLock)
            {
                if (!UniverseManager.TryGetValue(universeSymbol, out universe))
                {
                    universe = _pendingUniverseAdditions.FirstOrDefault(x => x.Configuration.Symbol == universeSymbol);
                    if (universe == null)
                    {
                        // create a new universe, these subscription settings don't currently get used
                        // since universe selection proper is never invoked on this type of universe
                        var uconfig = new SubscriptionDataConfig(subscription, symbol: universeSymbol, isInternalFeed: true, fillForward: false,
                                                                 exchangeTimeZone: DateTimeZone.Utc,
                                                                 dataTimeZone: DateTimeZone.Utc);

                        // this is the universe symbol, has no real entry in the mhdb, will default to market and security type
                        // set entry in market hours database for the universe subscription to match the config
                        var symbolString = MarketHoursDatabase.GetDatabaseSymbolKey(uconfig.Symbol);
                        MarketHoursDatabase.SetEntry(uconfig.Market, symbolString, uconfig.SecurityType,
                                                     SecurityExchangeHours.AlwaysOpen(uconfig.ExchangeTimeZone), uconfig.DataTimeZone);

                        universe = new UserDefinedUniverse(uconfig,
                                                           new UniverseSettings(
                                                               subscription.Resolution,
                                                               security.Leverage,
                                                               subscription.FillDataForward,
                                                               subscription.ExtendedMarketHours,
                                                               TimeSpan.Zero),
                                                           QuantConnect.Time.MaxTimeSpan,
                                                           new List <Symbol>());

                        AddUniverse(universe);
                    }
                }
            }

            var userDefinedUniverse = universe as UserDefinedUniverse;

            if (userDefinedUniverse != null)
            {
                lock (_pendingUniverseAdditionsLock)
                {
                    _pendingUserDefinedUniverseSecurityAdditions.Add(
                        new UserDefinedUniverseAddition(userDefinedUniverse, configurations, security));
                }
            }
            else
            {
                // should never happen, someone would need to add a non-user defined universe with this symbol
                throw new Exception($"Expected universe with symbol '{universeSymbol.Value}' to be of type {nameof(UserDefinedUniverse)} but was {universe.GetType().Name}.");
            }

            return(security);
        }
Beispiel #24
0
        /// <summary>
        /// Add specified data to required list. QC will funnel this data to the handle data routine.
        /// </summary>
        /// <param name="securityType">MarketType Type: Equity, Commodity, Future or FOREX</param>
        /// <param name="symbol">Symbol Reference for the MarketType</param>
        /// <param name="resolution">Resolution of the Data Required</param>
        /// <param name="fillDataForward">When no data available on a tradebar, return the last data that was generated</param>
        /// <param name="leverage">Custom leverage per security</param>
        /// <param name="extendedMarketHours">Extended market hours</param>
        /// <remarks> AddSecurity(SecurityType securityType, string symbol, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)</remarks>
        public void AddSecurity(SecurityType securityType, string symbol, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)
        {
            try
            {
                if (_locked)
                {
                    throw new Exception("Algorithm.AddSecurity(): Cannot add another security after algorithm running.");
                }

                symbol = symbol.ToUpper();
                //If it hasn't been set, use some defaults based on the portfolio type:
                if (leverage <= 0)
                {
                    switch (securityType)
                    {
                    case SecurityType.Equity:
                        leverage = 2;     //Cash Ac. = 1, RegT Std = 2 or PDT = 4.
                        break;

                    case SecurityType.Forex:
                        leverage = 50;
                        break;
                    }
                }

                //Add the symbol to Data Manager -- generate unified data streams for algorithm events
                var config = SubscriptionManager.Add(securityType, symbol, resolution, fillDataForward, extendedMarketHours);

                Security security;
                switch (config.SecurityType)
                {
                case SecurityType.Equity:
                    security = new Equity(config, leverage, false);
                    break;

                case SecurityType.Forex:
                    // decompose the symbol into each currency pair
                    string baseCurrency, quoteCurrency;
                    QuantConnect.Securities.Forex.Forex.DecomposeCurrencyPair(symbol, out baseCurrency, out quoteCurrency);

                    if (!Portfolio.CashBook.ContainsKey(baseCurrency))
                    {
                        // since we have none it's safe to say the conversion is zero
                        Portfolio.CashBook.Add(baseCurrency, 0, 0);
                    }
                    if (!Portfolio.CashBook.ContainsKey(quoteCurrency))
                    {
                        // since we have none it's safe to say the conversion is zero
                        Portfolio.CashBook.Add(quoteCurrency, 0, 0);
                    }
                    security = new Forex(Portfolio.CashBook[quoteCurrency], config, leverage, false);
                    break;

                default:
                case SecurityType.Base:
                    security = new Security(config, leverage, false);
                    break;
                }

                //Add the symbol to Securities Manager -- manage collection of portfolio entities for easy access.
                Securities.Add(config.Symbol, security);
            }
            catch (Exception err)
            {
                Error("Algorithm.AddSecurity(): " + err.Message);
            }
        }
Beispiel #25
0
 public void AddSecurity(Security security)
 {
     Securities.Add(security.Symbol, security);
 }
 public void AddSecurity(string security)
 {
     Securities.Add(security);
 }