Exemple #1
0
        /// <summary>
        /// Add a new security by all of its properties.
        /// </summary>
        /// <param name="symbol">Symbol of the security</param>
        /// <param name="config">The SubscriptionDataConfig for this symbol</param>
        /// <param name="leverage">Leverage for this security, default = 1</param>
        /// <param name="isDynamicallyLoadedData">Use dynamic data</param>
        public void Add(string symbol, SubscriptionDataConfig config, decimal leverage = 1m, bool isDynamicallyLoadedData = false)
        {
            //Upper case sybol:
            symbol = symbol.ToUpper();
            if (symbol != config.Symbol)
            {
                throw new ArgumentException("Expected SubscriptionDataConfig for " + symbol + " but received " + config.Symbol);
            }

            CheckResolutionCounts(config.Resolution);

            //If we don't already have this asset, add it to the securities list.
            if (_securityManager.ContainsKey(symbol))
            {
                //Otherwise, we already have it, just change its resolution:
                Log.Trace("Algorithm.Securities.Add(): Changing security information will overwrite portfolio");
            }

            switch (config.Security)
            {
            case SecurityType.Equity:
                _securityManager[symbol] = new Equity.Equity(symbol, config, leverage, isDynamicallyLoadedData);
                break;

            case SecurityType.Forex:
                _securityManager[symbol] = new Forex.Forex(symbol, config, leverage, isDynamicallyLoadedData);
                break;

            case SecurityType.Base:
                _securityManager[symbol] = new Security(symbol, config, leverage, isDynamicallyLoadedData);
                break;
            }
        }
Exemple #2
0
        /// <summary>
        /// Add a new security by all of its properties.
        /// </summary>
        /// <param name="symbol">Symbol of the security</param>
        /// <param name="type">Type of security: Equity, Forex or Future</param>
        /// <param name="resolution">Resolution of data required: currently only tick, second and minute for QuantConnect sources.</param>
        /// <param name="fillDataForward">Return previous bar's data when there is no trading in this bar</param>
        /// <param name="leverage">Leverage for this security, default = 1</param>
        /// <param name="extendedMarketHours">Request all the data available, including the extended market hours from 4am - 8pm.</param>
        /// <param name="isDynamicallyLoadedData">Use dynamic data</param>
        public void Add(string symbol, SecurityType type = SecurityType.Equity, Resolution resolution = Resolution.Minute, bool fillDataForward = true, decimal leverage = 1, bool extendedMarketHours = false, bool isDynamicallyLoadedData = false)
        {
            //Upper case sybol:
            symbol = symbol.ToUpper();

            //Maximum Data Usage: mainly RAM constraints but this has never been fully tested.
            if (GetResolutionCount(Resolution.Tick) == 30 && resolution == Resolution.Tick)
            {
                throw new Exception("We currently only support 30 tick assets at a time.");
            }
            if (GetResolutionCount(Resolution.Second) == 100 && resolution == Resolution.Second)
            {
                throw new Exception("We currently only support 100 second resolution securities at a time.");
            }
            if (GetResolutionCount(Resolution.Minute) == 1000 && resolution == Resolution.Minute)
            {
                throw new Exception("We currently only support 1000 minute assets at a time.");
            }

            //If we don't already have this asset, add it to the securities list.
            if (!_securityManager.ContainsKey(symbol))
            {
                switch (type)
                {
                case SecurityType.Equity:
                    Add(symbol, new Equity.Equity(symbol, resolution, fillDataForward, leverage, extendedMarketHours, isDynamicallyLoadedData));
                    break;

                case SecurityType.Forex:
                    Add(symbol, new Forex.Forex(symbol, resolution, fillDataForward, leverage, extendedMarketHours, isDynamicallyLoadedData));
                    break;

                case SecurityType.Base:
                    Add(symbol, new Security(symbol, SecurityType.Base, resolution, fillDataForward, leverage, extendedMarketHours));
                    break;
                }
            }
            else
            {
                //Otherwise, we already have it, just change its resolution:
                Log.Trace("Algorithm.Securities.Add(): Changing security information will overwrite portfolio");
                switch (type)
                {
                case SecurityType.Equity:
                    _securityManager[symbol] = new Equity.Equity(symbol, resolution, fillDataForward, leverage, extendedMarketHours);
                    break;

                case SecurityType.Forex:
                    _securityManager[symbol] = new Forex.Forex(symbol, resolution, fillDataForward, leverage, extendedMarketHours);
                    break;

                case SecurityType.Base:
                    _securityManager[symbol] = new Security(symbol, SecurityType.Base, resolution, fillDataForward, leverage, extendedMarketHours);
                    break;
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Creates a security and matching configuration. This applies the default leverage if
        /// leverage is less than or equal to zero.
        /// This method also add the new symbol mapping to the <see cref="SymbolCache"/>
        /// </summary>
        public static Security CreateSecurity(List <Tuple <Type, TickType> > subscriptionDataTypes,
                                              SecurityPortfolioManager securityPortfolioManager,
                                              SubscriptionManager subscriptionManager,
                                              SecurityExchangeHours exchangeHours,
                                              DateTimeZone dataTimeZone,
                                              SymbolProperties symbolProperties,
                                              ISecurityInitializer securityInitializer,
                                              Symbol symbol,
                                              Resolution resolution,
                                              bool fillDataForward,
                                              decimal leverage,
                                              bool extendedMarketHours,
                                              bool isInternalFeed,
                                              bool isCustomData,
                                              bool isLiveMode,
                                              bool addToSymbolCache       = true,
                                              bool isFilteredSubscription = true)
        {
            if (!subscriptionDataTypes.Any())
            {
                throw new ArgumentNullException(nameof(subscriptionDataTypes), "At least one type needed to create security");
            }

            // add the symbol to our cache
            if (addToSymbolCache)
            {
                SymbolCache.Set(symbol.Value, symbol);
            }

            // Add the symbol to Data Manager -- generate unified data streams for algorithm events
            var configList = new SubscriptionDataConfigList(symbol);

            configList.AddRange(from subscriptionDataType
                                in subscriptionDataTypes
                                let dataType = subscriptionDataType.Item1
                                               let tickType = subscriptionDataType.Item2
                                                              select subscriptionManager.Add(dataType, tickType,
                                                                                             symbol, resolution, dataTimeZone,
                                                                                             exchangeHours.TimeZone, isCustomData,
                                                                                             fillDataForward, extendedMarketHours,
                                                                                             isInternalFeed, isFilteredSubscription));

            // verify the cash book is in a ready state
            var quoteCurrency = symbolProperties.QuoteCurrency;

            if (!securityPortfolioManager.CashBook.ContainsKey(quoteCurrency))
            {
                // since we have none it's safe to say the conversion is zero
                securityPortfolioManager.CashBook.Add(quoteCurrency, 0, 0);
            }
            if (symbol.ID.SecurityType == SecurityType.Forex || symbol.ID.SecurityType == SecurityType.Crypto)
            {
                // decompose the symbol into each currency pair
                string baseCurrency;
                Forex.Forex.DecomposeCurrencyPair(symbol.Value, out baseCurrency, out quoteCurrency);

                if (!securityPortfolioManager.CashBook.ContainsKey(baseCurrency))
                {
                    // since we have none it's safe to say the conversion is zero
                    securityPortfolioManager.CashBook.Add(baseCurrency, 0, 0);
                }
                if (!securityPortfolioManager.CashBook.ContainsKey(quoteCurrency))
                {
                    // since we have none it's safe to say the conversion is zero
                    securityPortfolioManager.CashBook.Add(quoteCurrency, 0, 0);
                }
            }

            var quoteCash = securityPortfolioManager.CashBook[symbolProperties.QuoteCurrency];

            Security security;

            switch (configList.Symbol.ID.SecurityType)
            {
            case SecurityType.Equity:
                security = new Equity.Equity(symbol, exchangeHours, quoteCash, symbolProperties);
                break;

            case SecurityType.Option:
                if (addToSymbolCache)
                {
                    SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying);
                }
                configList.SetDataNormalizationMode(DataNormalizationMode.Raw);
                security = new Option.Option(symbol, exchangeHours, securityPortfolioManager.CashBook[CashBook.AccountCurrency], new Option.OptionSymbolProperties(symbolProperties));
                break;

            case SecurityType.Future:
                configList.SetDataNormalizationMode(DataNormalizationMode.Raw);
                security = new Future.Future(symbol, exchangeHours, securityPortfolioManager.CashBook[CashBook.AccountCurrency], symbolProperties);
                break;

            case SecurityType.Forex:
                security = new Forex.Forex(symbol, exchangeHours, quoteCash, symbolProperties);
                break;

            case SecurityType.Cfd:
                security = new Cfd.Cfd(symbol, exchangeHours, quoteCash, symbolProperties);
                break;

            case SecurityType.Crypto:
                security = new Crypto.Crypto(symbol, exchangeHours, quoteCash, symbolProperties);
                break;

            default:
            case SecurityType.Base:
                security = new Security(symbol, exchangeHours, quoteCash, symbolProperties);
                break;
            }

            // if we're just creating this security and it only has an internal
            // feed, mark it as non-tradable since the user didn't request this data
            if (!configList.IsInternalFeed)
            {
                security.IsTradable = true;
            }

            security.AddData(configList);

            // invoke the security initializer
            securityInitializer.Initialize(security, true);

            // if leverage was specified then apply to security after the initializer has run, parameters of this
            // method take precedence over the intializer
            if (leverage > 0)
            {
                security.SetLeverage(leverage);
            }

            // In live mode, equity assumes specific price variation model
            if (isLiveMode && security.Type == SecurityType.Equity)
            {
                security.PriceVariationModel = new EquityPriceVariationModel();
            }

            return(security);
        }
Exemple #4
0
        /// <summary>
        /// Creates a new security
        /// </summary>
        /// <remarks>Following the obsoletion of Security.Subscriptions,
        /// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks>
        public Security CreateSecurity(Symbol symbol,
                                       List <SubscriptionDataConfig> subscriptionDataConfigList,
                                       decimal leverage      = 0,
                                       bool addToSymbolCache = true)
        {
            var configList = new SubscriptionDataConfigList(symbol);

            configList.AddRange(subscriptionDataConfigList);

            var exchangeHours = _marketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType).ExchangeHours;

            var defaultQuoteCurrency = _cashBook.AccountCurrency;

            if (symbol.ID.SecurityType == SecurityType.Forex)
            {
                defaultQuoteCurrency = symbol.Value.Substring(3);
            }

            if (symbol.ID.SecurityType == SecurityType.Crypto && !_symbolPropertiesDatabase.ContainsKey(symbol.ID.Market, symbol, symbol.ID.SecurityType))
            {
                throw new ArgumentException($"Symbol can't be found in the Symbol Properties Database: {symbol.Value}");
            }

            // For Futures Options that don't have a SPDB entry, the futures entry will be used instead.
            var symbolProperties = _symbolPropertiesDatabase.GetSymbolProperties(
                symbol.ID.Market,
                symbol,
                symbol.SecurityType,
                defaultQuoteCurrency);

            // add the symbol to our cache
            if (addToSymbolCache)
            {
                SymbolCache.Set(symbol.Value, symbol);
            }

            // verify the cash book is in a ready state
            var quoteCurrency = symbolProperties.QuoteCurrency;

            if (!_cashBook.ContainsKey(quoteCurrency))
            {
                // since we have none it's safe to say the conversion is zero
                _cashBook.Add(quoteCurrency, 0, 0);
            }
            if (symbol.ID.SecurityType == SecurityType.Forex || symbol.ID.SecurityType == SecurityType.Crypto)
            {
                // decompose the symbol into each currency pair
                string baseCurrency;
                if (symbol.ID.SecurityType == SecurityType.Forex)
                {
                    Forex.Forex.DecomposeCurrencyPair(symbol.Value, out baseCurrency, out quoteCurrency);
                }
                else
                {
                    Crypto.Crypto.DecomposeCurrencyPair(symbol, symbolProperties, out baseCurrency, out quoteCurrency);
                }

                if (!_cashBook.ContainsKey(baseCurrency))
                {
                    // since we have none it's safe to say the conversion is zero
                    _cashBook.Add(baseCurrency, 0, 0);
                }
                if (!_cashBook.ContainsKey(quoteCurrency))
                {
                    // since we have none it's safe to say the conversion is zero
                    _cashBook.Add(quoteCurrency, 0, 0);
                }
            }

            var quoteCash = _cashBook[symbolProperties.QuoteCurrency];
            var cache     = _cacheProvider.GetSecurityCache(symbol);

            Security security;

            switch (symbol.ID.SecurityType)
            {
            case SecurityType.Equity:
                security = new Equity.Equity(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
                break;

            case SecurityType.Option:
                if (addToSymbolCache)
                {
                    SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying);
                }
                security = new Option.Option(symbol, exchangeHours, quoteCash, new Option.OptionSymbolProperties(symbolProperties), _cashBook, _registeredTypes, cache);
                break;

            case SecurityType.FutureOption:
                if (addToSymbolCache)
                {
                    SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying);
                }
                var optionSymbolProperties = new Option.OptionSymbolProperties(symbolProperties);

                // Future options exercised only gives us one contract back, rather than the
                // 100x seen in equities.
                optionSymbolProperties.SetContractUnitOfTrade(1);

                security = new FutureOption.FutureOption(symbol, exchangeHours, quoteCash, optionSymbolProperties, _cashBook, _registeredTypes, cache);
                break;

            case SecurityType.Future:
                security = new Future.Future(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
                break;

            case SecurityType.Forex:
                security = new Forex.Forex(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
                break;

            case SecurityType.Cfd:
                security = new Cfd.Cfd(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
                break;

            case SecurityType.Crypto:
                security = new Crypto.Crypto(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
                break;

            default:
            case SecurityType.Base:
                security = new Security(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
                break;
            }

            // if we're just creating this security and it only has an internal
            // feed, mark it as non-tradable since the user didn't request this data
            if (!configList.IsInternalFeed)
            {
                security.IsTradable = true;
            }

            security.AddData(configList);

            // invoke the security initializer
            _securityInitializerProvider.SecurityInitializer.Initialize(security);

            // if leverage was specified then apply to security after the initializer has run, parameters of this
            // method take precedence over the intializer
            if (leverage != Security.NullLeverage)
            {
                security.SetLeverage(leverage);
            }

            var isNotNormalized = configList.DataNormalizationMode() == DataNormalizationMode.Raw;

            // In live mode and non normalized data, equity assumes specific price variation model
            if ((_isLiveMode || isNotNormalized) && security.Type == SecurityType.Equity)
            {
                security.PriceVariationModel = new EquityPriceVariationModel();
            }

            return(security);
        }
Exemple #5
0
        /// <summary>
        /// Creates a security and matching configuration. This applies the default leverage if
        /// leverage is less than or equal to zero.
        /// This method also add the new symbol mapping to the <see cref="SymbolCache"/>
        /// </summary>
        public static Security CreateSecurity(Type factoryType,
                                              SecurityPortfolioManager securityPortfolioManager,
                                              SubscriptionManager subscriptionManager,
                                              SecurityExchangeHours exchangeHours,
                                              DateTimeZone dataTimeZone,
                                              ISecurityInitializer securityInitializer,
                                              Symbol symbol,
                                              Resolution resolution,
                                              bool fillDataForward,
                                              decimal leverage,
                                              bool extendedMarketHours,
                                              bool isInternalFeed,
                                              bool isCustomData,
                                              bool addToSymbolCache = true)
        {
            var sid = symbol.ID;

            // add the symbol to our cache
            if (addToSymbolCache)
            {
                SymbolCache.Set(symbol.Value, symbol);
            }

            //Add the symbol to Data Manager -- generate unified data streams for algorithm events
            var config = subscriptionManager.Add(factoryType, symbol, resolution, dataTimeZone, exchangeHours.TimeZone, isCustomData, fillDataForward,
                                                 extendedMarketHours, isInternalFeed);

            Security security;

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

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

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

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

            // invoke the security initializer
            securityInitializer.Initialize(security);

            // if leverage was specified then apply to security after the initializer has run, parameters of this
            // method take precedence over the intializer
            if (leverage > 0)
            {
                security.SetLeverage(leverage);
            }

            return(security);
        }
Exemple #6
0
        /// <summary>
        /// Add a new security by all of its properties.
        /// </summary>
        /// <param name="symbol">Symbol of the security</param>
        /// <param name="type">Type of security: Equity, Forex or Future</param>
        /// <param name="resolution">Resolution of data required: currently only tick, second and minute for QuantConnect sources.</param>
        /// <param name="fillDataForward">Return previous bar's data when there is no trading in this bar</param>
        /// <param name="leverage">Leverage for this security, default = 1</param>
        /// <param name="extendedMarketHours">Request all the data available, including the extended market hours from 4am - 8pm.</param>
        /// <param name="isDynamicallyLoadedData">Use dynamic data</param>
        public void Add(string symbol, SecurityType type = SecurityType.Equity, Resolution resolution = Resolution.Minute, bool fillDataForward = true, decimal leverage = 1, bool extendedMarketHours = false, bool isDynamicallyLoadedData = false)
        {
            //Upper case sybol:
            symbol = symbol.ToUpper();

            //Maximum Data Usage: mainly RAM constraints but this has never been fully tested.
            if (GetResolutionCount(Resolution.Tick) >= _tickLimit && resolution == Resolution.Tick)
            {
                throw new Exception("We currently only support " + _tickLimit + " tick assets at a time due to physical memory limitations.");
            }
            if (GetResolutionCount(Resolution.Second) >= _secondLimit && resolution == Resolution.Second)
            {
                throw new Exception("We currently only support  " + _secondLimit + "  second resolution securities at a time due to physical memory limitations.");
            }
            if (GetResolutionCount(Resolution.Minute) >= _minuteLimit && resolution == Resolution.Minute)
            {
                throw new Exception("We currently only support  " + _minuteLimit + "  minute assets at a time due to physical memory limitations.");
            }

            //Current ram usage: this especially applies during live trading where micro servers have limited resources:
            var currentEstimatedRam = GetRamEstimate(GetResolutionCount(Resolution.Minute), GetResolutionCount(Resolution.Second), GetResolutionCount(Resolution.Tick));

            if (currentEstimatedRam > _maxRamEstimate)
            {
                throw new Exception("We estimate you will run out of memory (" + currentEstimatedRam + "mb of " + _maxRamEstimate + "mb physically available). Please reduce the number of symbols you're analysing or if in live trading upgrade your server to allow more memory.");
            }

            //If we don't already have this asset, add it to the securities list.
            if (!_securityManager.ContainsKey(symbol))
            {
                switch (type)
                {
                case SecurityType.Equity:
                    Add(symbol, new Equity.Equity(symbol, resolution, fillDataForward, leverage, extendedMarketHours, isDynamicallyLoadedData));
                    break;

                case SecurityType.Forex:
                    Add(symbol, new Forex.Forex(symbol, resolution, fillDataForward, leverage, extendedMarketHours, isDynamicallyLoadedData));
                    break;

                case SecurityType.Base:
                    Add(symbol, new Security(symbol, SecurityType.Base, resolution, fillDataForward, leverage, extendedMarketHours, isDynamicallyLoadedData));
                    break;
                }
            }
            else
            {
                //Otherwise, we already have it, just change its resolution:
                Log.Trace("Algorithm.Securities.Add(): Changing security information will overwrite portfolio");
                switch (type)
                {
                case SecurityType.Equity:
                    _securityManager[symbol] = new Equity.Equity(symbol, resolution, fillDataForward, leverage, extendedMarketHours);
                    break;

                case SecurityType.Forex:
                    _securityManager[symbol] = new Forex.Forex(symbol, resolution, fillDataForward, leverage, extendedMarketHours);
                    break;

                case SecurityType.Base:
                    _securityManager[symbol] = new Security(symbol, SecurityType.Base, resolution, fillDataForward, leverage, extendedMarketHours, isDynamicallyLoadedData);
                    break;
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Creates a security and matching configuration. This applies the default leverage if
        /// leverage is less than or equal to zero
        /// </summary>
        public static Security CreateSecurity(SecurityPortfolioManager securityPortfolioManager,
                                              SubscriptionManager subscriptionManager,
                                              SecurityExchangeHoursProvider securityExchangeHoursProvider,
                                              SecurityType securityType,
                                              Symbol symbol,
                                              Resolution resolution,
                                              string market,
                                              bool fillDataForward,
                                              decimal leverage,
                                              bool extendedMarketHours,
                                              bool isInternalFeed,
                                              bool isCustomData)
        {
            //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;
                }
            }

            if (market == null)
            {
                // set default values
                if (securityType == SecurityType.Forex)
                {
                    market = "fxcm";
                }
                else if (securityType == SecurityType.Equity)
                {
                    market = "usa";
                }
                else
                {
                    market = "usa";
                }
            }

            //Add the symbol to Data Manager -- generate unified data streams for algorithm events
            var exchangeHours = securityExchangeHoursProvider.GetExchangeHours(market, symbol, securityType);
            var tradeBarType  = typeof(TradeBar);
            var type          = resolution == Resolution.Tick ? typeof(Tick) : tradeBarType;
            var config        = subscriptionManager.Add(type, securityType, symbol, resolution, market, exchangeHours.TimeZone, isCustomData, fillDataForward, extendedMarketHours, isInternalFeed);

            Security security;

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

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

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

            default:
            case SecurityType.Base:
                security = new Security(exchangeHours, config, leverage);
                break;
            }
            return(security);
        }
Exemple #8
0
        /// <summary>
        /// Creates a new security
        /// </summary>
        /// <remarks>Following the obsoletion of Security.Subscriptions,
        /// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks>
        public Security CreateSecurity(Symbol symbol,
                                       List <SubscriptionDataConfig> subscriptionDataConfigList,
                                       decimal leverage      = 0,
                                       bool addToSymbolCache = true)
        {
            var configList = new SubscriptionDataConfigList(symbol);

            configList.AddRange(subscriptionDataConfigList);

            var exchangeHours = _marketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType).ExchangeHours;

            var defaultQuoteCurrency = _cashBook.AccountCurrency;

            if (symbol.ID.SecurityType == SecurityType.Forex || symbol.ID.SecurityType == SecurityType.Crypto)
            {
                defaultQuoteCurrency = symbol.Value.Substring(3);
            }

            var symbolProperties = _symbolPropertiesDatabase.GetSymbolProperties(symbol.ID.Market, symbol, symbol.ID.SecurityType, defaultQuoteCurrency);

            // add the symbol to our cache
            if (addToSymbolCache)
            {
                SymbolCache.Set(symbol.Value, symbol);
            }

            // verify the cash book is in a ready state
            var quoteCurrency = symbolProperties.QuoteCurrency;

            if (!_cashBook.ContainsKey(quoteCurrency))
            {
                // since we have none it's safe to say the conversion is zero
                _cashBook.Add(quoteCurrency, 0, 0);
            }
            if (symbol.ID.SecurityType == SecurityType.Forex || symbol.ID.SecurityType == SecurityType.Crypto)
            {
                // decompose the symbol into each currency pair
                string baseCurrency;
                Forex.Forex.DecomposeCurrencyPair(symbol.Value, out baseCurrency, out quoteCurrency);

                if (!_cashBook.ContainsKey(baseCurrency))
                {
                    // since we have none it's safe to say the conversion is zero
                    _cashBook.Add(baseCurrency, 0, 0);
                }
                if (!_cashBook.ContainsKey(quoteCurrency))
                {
                    // since we have none it's safe to say the conversion is zero
                    _cashBook.Add(quoteCurrency, 0, 0);
                }
            }

            var quoteCash = _cashBook[symbolProperties.QuoteCurrency];

            Security security;

            switch (symbol.ID.SecurityType)
            {
            case SecurityType.Equity:
                security = new Equity.Equity(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook);
                break;

            case SecurityType.Option:
                if (addToSymbolCache)
                {
                    SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying);
                }
                security = new Option.Option(symbol, exchangeHours, _cashBook[_cashBook.AccountCurrency], new Option.OptionSymbolProperties(symbolProperties), _cashBook);
                break;

            case SecurityType.Future:
                security = new Future.Future(symbol, exchangeHours, _cashBook[_cashBook.AccountCurrency], symbolProperties, _cashBook);
                break;

            case SecurityType.Forex:
                security = new Forex.Forex(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook);
                break;

            case SecurityType.Cfd:
                security = new Cfd.Cfd(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook);
                break;

            case SecurityType.Crypto:
                security = new Crypto.Crypto(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook);
                break;

            default:
            case SecurityType.Base:
                security = new Security(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook);
                break;
            }

            // if we're just creating this security and it only has an internal
            // feed, mark it as non-tradable since the user didn't request this data
            if (!configList.IsInternalFeed)
            {
                security.IsTradable = true;
            }

            security.AddData(configList);

            // invoke the security initializer
            _securityInitializerProvider.SecurityInitializer.Initialize(security);

            // if leverage was specified then apply to security after the initializer has run, parameters of this
            // method take precedence over the intializer
            if (leverage > 0)
            {
                security.SetLeverage(leverage);
            }

            // In live mode, equity assumes specific price variation model
            if (_isLiveMode && security.Type == SecurityType.Equity)
            {
                security.PriceVariationModel = new EquityPriceVariationModel();
            }

            return(security);
        }
Exemple #9
0
        /// <summary>
        /// Creates a security and matching configuration. This applies the default leverage if
        /// leverage is less than or equal to zero.
        /// This method also add the new symbol mapping to the <see cref="SymbolCache"/>
        /// </summary>
        public static Security CreateSecurity(SecurityPortfolioManager securityPortfolioManager,
                                              SubscriptionManager subscriptionManager,
                                              MarketHoursDatabase marketHoursDatabase,
                                              Symbol symbol,
                                              Resolution resolution,
                                              bool fillDataForward,
                                              decimal leverage,
                                              bool extendedMarketHours,
                                              bool isInternalFeed,
                                              bool isCustomData)
        {
            var sid = symbol.ID;

            //If it hasn't been set, use some defaults based on the security type
            if (leverage <= 0)
            {
                if (sid.SecurityType == SecurityType.Equity)
                {
                    leverage = 2;
                }
                else if (sid.SecurityType == SecurityType.Forex)
                {
                    leverage = 50;
                }
                // default to 1 for everything else
                else
                {
                    leverage = 1m;
                }
            }

            // add the symbol to our cache
            SymbolCache.Set(symbol.Value, symbol);

            var market       = sid.Market;
            var securityType = sid.SecurityType;

            //Add the symbol to Data Manager -- generate unified data streams for algorithm events
            var marketHoursDbEntry = marketHoursDatabase.GetEntry(market, symbol, securityType);
            var exchangeHours      = marketHoursDbEntry.ExchangeHours;
            var tradeBarType       = typeof(TradeBar);
            var type   = resolution == Resolution.Tick ? typeof(Tick) : tradeBarType;
            var config = subscriptionManager.Add(type, symbol, resolution, marketHoursDbEntry.DataTimeZone, exchangeHours.TimeZone, isCustomData, fillDataForward: fillDataForward, extendedMarketHours: extendedMarketHours, isInternalFeed: isInternalFeed);

            Security security;

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

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

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

            default:
            case SecurityType.Base:
                security = new Security(exchangeHours, config, leverage);
                break;
            }
            return(security);
        }
Exemple #10
0
        /// <summary>
        /// Creates a security and matching configuration. This applies the default leverage if
        /// leverage is less than or equal to zero.
        /// This method also add the new symbol mapping to the <see cref="SymbolCache"/>
        /// </summary>
        public static Security CreateSecurity(Type factoryType,
                                              SecurityPortfolioManager securityPortfolioManager,
                                              SubscriptionManager subscriptionManager,
                                              SecurityExchangeHours exchangeHours,
                                              DateTimeZone dataTimeZone,
                                              SymbolProperties symbolProperties,
                                              ISecurityInitializer securityInitializer,
                                              Symbol symbol,
                                              Resolution resolution,
                                              bool fillDataForward,
                                              decimal leverage,
                                              bool extendedMarketHours,
                                              bool isInternalFeed,
                                              bool isCustomData,
                                              bool isLiveMode,
                                              bool addToSymbolCache       = true,
                                              bool isFilteredSubscription = true)
        {
            // add the symbol to our cache
            if (addToSymbolCache)
            {
                SymbolCache.Set(symbol.Value, symbol);
            }

            //Add the symbol to Data Manager -- generate unified data streams for algorithm events
            var config = subscriptionManager.Add(factoryType, symbol, resolution, dataTimeZone, exchangeHours.TimeZone, isCustomData, fillDataForward,
                                                 extendedMarketHours, isInternalFeed, isFilteredSubscription);

            // verify the cash book is in a ready state
            var quoteCurrency = symbolProperties.QuoteCurrency;

            if (!securityPortfolioManager.CashBook.ContainsKey(quoteCurrency))
            {
                // since we have none it's safe to say the conversion is zero
                securityPortfolioManager.CashBook.Add(quoteCurrency, 0, 0);
            }
            if (symbol.ID.SecurityType == SecurityType.Forex)
            {
                // decompose the symbol into each currency pair
                string baseCurrency;
                Forex.Forex.DecomposeCurrencyPair(symbol.Value, out baseCurrency, out quoteCurrency);

                if (!securityPortfolioManager.CashBook.ContainsKey(baseCurrency))
                {
                    // since we have none it's safe to say the conversion is zero
                    securityPortfolioManager.CashBook.Add(baseCurrency, 0, 0);
                }
                if (!securityPortfolioManager.CashBook.ContainsKey(quoteCurrency))
                {
                    // since we have none it's safe to say the conversion is zero
                    securityPortfolioManager.CashBook.Add(quoteCurrency, 0, 0);
                }
            }

            var quoteCash = securityPortfolioManager.CashBook[symbolProperties.QuoteCurrency];

            Security security;

            switch (config.SecurityType)
            {
            case SecurityType.Equity:
                security = new Equity.Equity(symbol, exchangeHours, quoteCash, symbolProperties);
                break;

            case SecurityType.Option:
                security = new Option.Option(exchangeHours, config, securityPortfolioManager.CashBook[CashBook.AccountCurrency], symbolProperties);
                break;

            case SecurityType.Forex:
                security = new Forex.Forex(symbol, exchangeHours, quoteCash, symbolProperties);
                break;

            case SecurityType.Cfd:
                security = new Cfd.Cfd(symbol, exchangeHours, quoteCash, symbolProperties);
                break;

            default:
            case SecurityType.Base:
                security = new Security(symbol, exchangeHours, quoteCash, symbolProperties);
                break;
            }

            // if we're just creating this security and it only has an internal
            // feed, mark it as non-tradable since the user didn't request this data
            if (!config.IsInternalFeed)
            {
                security.IsTradable = true;
            }

            security.AddData(config);

            // invoke the security initializer
            securityInitializer.Initialize(security);

            // if leverage was specified then apply to security after the initializer has run, parameters of this
            // method take precedence over the intializer
            if (leverage > 0)
            {
                security.SetLeverage(leverage);
            }

            // In live mode, equity assumes specific price variation model
            if (isLiveMode && security.Type == SecurityType.Equity)
            {
                security.PriceVariationModel = new EquityPriceVariationModel();
            }

            return(security);
        }