Ejemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HistoryRequest"/> class from the specified parameters
 /// </summary>
 /// <param name="startTimeUtc">The start time for this request,</param>
 /// <param name="endTimeUtc">The start time for this request</param>
 /// <param name="dataType">The data type of the output data</param>
 /// <param name="symbol">The symbol to request data for</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <param name="resolution">The requested data resolution</param>
 /// <param name="market">The market this data belongs to</param>
 /// <param name="exchangeHours">The exchange hours used in fill forward processing</param>
 /// <param name="fillForwardResolution">The requested fill forward resolution for this request</param>
 /// <param name="includeExtendedMarketHours">True to include data from pre/post market hours</param>
 /// <param name="isCustomData">True for custom user data, false for normal QC data</param>
 public HistoryRequest(DateTime startTimeUtc, 
     DateTime endTimeUtc,
     Type dataType,
     Symbol symbol,
     SecurityType securityType,
     Resolution resolution,
     string market,
     SecurityExchangeHours exchangeHours,
     Resolution? fillForwardResolution,
     bool includeExtendedMarketHours,
     bool isCustomData
     )
 {
     StartTimeUtc = startTimeUtc;
     EndTimeUtc = endTimeUtc;
     Symbol = symbol;
     ExchangeHours = exchangeHours;
     Resolution = resolution;
     FillForwardResolution = fillForwardResolution;
     IncludeExtendedMarketHours = includeExtendedMarketHours;
     DataType = dataType;
     SecurityType = securityType;
     Market = market;
     IsCustomData = isCustomData;
     TimeZone = exchangeHours.TimeZone;
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Construct a new security vehicle based on the user options.
        /// </summary>
        public Security(SecurityExchangeHours exchangeHours, SubscriptionDataConfig config, decimal leverage)
        {
            _config = config;

            Cache = new SecurityCache();
            Exchange = new SecurityExchange(exchangeHours);
            DataFilter = new SecurityDataFilter();
            PortfolioModel = new SecurityPortfolioModel();
            TransactionModel = new SecurityTransactionModel();
            MarginModel = new SecurityMarginModel(leverage);
            Holdings = new SecurityHolding(this);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Construct a new security vehicle based on the user options.
        /// </summary>
        public Security(SecurityExchangeHours exchangeHours, SubscriptionDataConfig config, decimal leverage, bool isDynamicallyLoadedData = false)
        {
            _config = config;
            _symbol = config.Symbol;
            _isDynamicallyLoadedData = isDynamicallyLoadedData;

            Cache = new SecurityCache();
            Exchange = new SecurityExchange(exchangeHours);
            DataFilter = new SecurityDataFilter();
            PortfolioModel = new SecurityPortfolioModel();
            TransactionModel = new SecurityTransactionModel();
            MarginModel = new SecurityMarginModel(leverage);
            Holdings = new SecurityHolding(this);
        }
        /// <summary>
        /// Creates a new instance of <see cref="SecurityExchangeHours"/> from the specified csv line and holiday set
        /// </summary>
        /// <param name="line">The csv line to be parsed</param>
        /// <param name="holidaysByMarket">The holidays this exchange isn't open for trading by market</param>
        /// <param name="key">The key used to uniquely identify these market hours</param>
        /// <returns>A new <see cref="SecurityExchangeHours"/> for the specified csv line and holidays</returns>
        private static MarketHoursDatabase.Entry FromCsvLine(string line,
            IReadOnlyDictionary<string, IEnumerable<DateTime>> holidaysByMarket,
            out SecurityDatabaseKey key)
        {
            var csv = line.Split(',');
            var marketHours = new List<LocalMarketHours>(7);

            // timezones can be specified using Tzdb names (America/New_York) or they can
            // be specified using offsets, UTC-5

            var dataTimeZone = ParseTimeZone(csv[0]);
            var exchangeTimeZone = ParseTimeZone(csv[1]);

            //var market = csv[2];
            //var symbol = csv[3];
            //var type = csv[4];
            var symbol = string.IsNullOrEmpty(csv[3]) ? null : csv[3];
            key = new SecurityDatabaseKey(csv[2], symbol, (SecurityType)Enum.Parse(typeof(SecurityType), csv[4], true));

            int csvLength = csv.Length;
            for (int i = 1; i < 8; i++) // 7 days, so < 8
            {
                // the 4 here is because 4 times per day, ex_open,open,close,ex_close
                if (4*i + 4 > csvLength - 1)
                {
                    break;
                }
                var hours = ReadCsvHours(csv, 4*i + 1, (DayOfWeek) (i - 1));
                marketHours.Add(hours);
            }

            IEnumerable<DateTime> holidays;
            if (!holidaysByMarket.TryGetValue(key.Market, out holidays))
            {
                holidays = Enumerable.Empty<DateTime>();
            }

            var exchangeHours = new SecurityExchangeHours(exchangeTimeZone, holidays, marketHours.ToDictionary(x => x.DayOfWeek));
            return new MarketHoursDatabase.Entry(dataTimeZone, exchangeHours);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Construct a new security vehicle based on the user options.
 /// </summary>
 public Security(SecurityExchangeHours exchangeHours, SubscriptionDataConfig config)
     : this(config,
         new SecurityExchange(exchangeHours),
         new SecurityCache(),
         new SecurityPortfolioModel(),
         new ImmediateFillModel(),
         new InteractiveBrokersFeeModel(),
         new SpreadSlippageModel(),
         new ImmediateSettlementModel(),
         new SecurityMarginModel(1m),
         new SecurityDataFilter())
 {
 }
Ejemplo n.º 6
0
        public static SecurityExchangeHours CreateUsEquitySecurityExchangeHours()
        {
            var sunday = LocalMarketHours.ClosedAllDay(DayOfWeek.Sunday);
            var monday = new LocalMarketHours(DayOfWeek.Monday, new TimeSpan(9, 30, 0), new TimeSpan(16, 0, 0));
            var tuesday = new LocalMarketHours(DayOfWeek.Tuesday, new TimeSpan(9, 30, 0), new TimeSpan(16, 0, 0));
            var wednesday = new LocalMarketHours(DayOfWeek.Wednesday, new TimeSpan(9, 30, 0), new TimeSpan(16, 0, 0));
            var thursday = new LocalMarketHours(DayOfWeek.Thursday, new TimeSpan(9, 30, 0), new TimeSpan(16, 0, 0));
            var friday = new LocalMarketHours(DayOfWeek.Friday, new TimeSpan(9, 30, 0), new TimeSpan(16, 0, 0));
            var saturday = LocalMarketHours.ClosedAllDay(DayOfWeek.Saturday);

            var exchangeHours = new SecurityExchangeHours(TimeZones.NewYork, USHoliday.Dates.Select(x => x.Date), new[]
            {
                sunday, monday, tuesday, wednesday, thursday, friday, saturday
            }.ToDictionary(x => x.DayOfWeek));
            return exchangeHours;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Sets the regular market hours for the specified days If no days are specified then
        /// all days will be updated.
        /// </summary>
        /// <param name="extendedMarketOpen">The time of day the pre market opens</param>
        /// <param name="marketOpen">The time of day the market opens</param>
        /// <param name="marketClose">The time of day the market closes</param>
        /// <param name="extendedMarketClose">The time of day the post market opens</param>
        /// <param name="days">The days of the week to set these times for</param>
        public void SetMarketHours(TimeSpan extendedMarketOpen, TimeSpan marketOpen, TimeSpan marketClose, TimeSpan extendedMarketClose, params DayOfWeek[] days)
        {
            if (days.IsNullOrEmpty()) days = Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>().ToArray();

            // if we specify close as 1 tick before the day rolls over, the exchange is still
            // considered to be open all day,so set it to one day and this impl will make it OpenAllDay
            if (extendedMarketOpen == marketOpen && marketOpen == TimeSpan.Zero && extendedMarketClose == marketClose && marketClose.Ticks == Time.OneDay.Ticks - 1)
            {
                marketClose = Time.OneDay;
            }
            
            // make sure extended hours are outside of regular hours
            extendedMarketOpen = TimeSpan.FromTicks(Math.Min(extendedMarketOpen.Ticks, marketOpen.Ticks));
            extendedMarketClose = TimeSpan.FromTicks(Math.Max(extendedMarketClose.Ticks, marketClose.Ticks));

            var marketHours = _exchangeHours.MarketHours.ToDictionary();
            foreach (var day in days)
            {
                if (marketOpen == TimeSpan.Zero && marketClose == TimeSpan.Zero)
                {
                    marketHours[day] = LocalMarketHours.ClosedAllDay(day);
                }
                else if (marketOpen == TimeSpan.Zero && marketClose == Time.OneDay)
                {
                    marketHours[day] = LocalMarketHours.OpenAllDay(day);
                }
                else
                {
                    marketHours[day] = new LocalMarketHours(day, extendedMarketOpen, marketOpen, marketClose, extendedMarketClose);
                }
            }

            // create a new exchange hours instance for the new hours
            _exchangeHours = new SecurityExchangeHours(_exchangeHours.TimeZone, _exchangeHours.Holidays, marketHours);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Sets the regular market hours for the specified days If no days are specified then
        /// all days will be updated.
        /// </summary>
        /// <param name="extendedMarketOpen">The time of day the pre market opens</param>
        /// <param name="marketOpen">The time of day the market opens</param>
        /// <param name="marketClose">The time of day the market closes</param>
        /// <param name="extendedMarketClose">The time of day the post market opens</param>
        /// <param name="days">The days of the week to set these times for</param>
        public void SetMarketHours(TimeSpan extendedMarketOpen, TimeSpan marketOpen, TimeSpan marketClose, TimeSpan extendedMarketClose, params DayOfWeek[] days)
        {
            if (days.IsNullOrEmpty()) days = Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>().ToArray();

            // make sure extended hours are outside of regular hours
            extendedMarketOpen = TimeSpan.FromTicks(Math.Min(extendedMarketOpen.Ticks, marketOpen.Ticks));
            extendedMarketClose = TimeSpan.FromTicks(Math.Max(extendedMarketClose.Ticks, marketClose.Ticks));

            var marketHours = _exchangeHours.MarketHours.ToDictionary();
            foreach (var day in days)
            {
                if (marketOpen == TimeSpan.Zero && marketClose == TimeSpan.Zero)
                {
                    marketHours[day] = LocalMarketHours.ClosedAllDay(day);
                }
                else if (marketOpen == TimeSpan.Zero && marketClose == Time.OneDay)
                {
                    marketHours[day] = LocalMarketHours.OpenAllDay(day);
                }
                else
                {
                    marketHours[day] = new LocalMarketHours(day, extendedMarketOpen, marketOpen, marketClose, extendedMarketClose);
                }
            }

            // create a new exchange hours instance for the new hours
            _exchangeHours = new SecurityExchangeHours(_exchangeHours.TimeZone, _exchangeHours.Holidays, marketHours);
        }
Ejemplo n.º 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(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 addToSymbolCache       = true,
                                              bool isFilteredSubscription = 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, isFilteredSubscription);

            Security security;

            switch (config.SecurityType)
            {
            case SecurityType.Equity:
                security = new Equity.Equity(exchangeHours, config, securityPortfolioManager.CashBook[CashBook.AccountCurrency], symbolProperties);
                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, symbolProperties);
            }
            break;

            case SecurityType.Cfd:
            {
                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);
                }
                security = new Cfd.Cfd(exchangeHours, securityPortfolioManager.CashBook[quoteCurrency], config, symbolProperties);
            }
            break;

            default:
            case SecurityType.Base:
                security = new Security(exchangeHours, config, securityPortfolioManager.CashBook[CashBook.AccountCurrency], symbolProperties);
                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);
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Entry"/> class
 /// </summary>
 /// <param name="dataTimeZone">The raw data time zone</param>
 /// <param name="exchangeHours">The security exchange hours for this entry</param>
 public Entry(DateTimeZone dataTimeZone, SecurityExchangeHours exchangeHours)
 {
     DataTimeZone  = dataTimeZone;
     ExchangeHours = exchangeHours;
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Convenience method for the common custom data case.
 /// Sets the entry for the specified symbol using SecurityExchangeHours.AlwaysOpen(timeZone)
 /// This sets the data time zone equal to the exchange time zone as well.
 /// </summary>
 /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
 /// <param name="symbol">The particular symbol being traded</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <param name="timeZone">The time zone of the symbol's exchange and raw data</param>
 /// <returns>The entry matching the specified market/symbol/security-type</returns>
 public virtual Entry SetEntryAlwaysOpen(string market, string symbol, SecurityType securityType, DateTimeZone timeZone)
 {
     return(SetEntry(market, symbol, securityType, SecurityExchangeHours.AlwaysOpen(timeZone)));
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Sets the entry for the specified market/symbol/security-type.
        /// This is intended to be used by custom data and other data sources that don't have explicit
        /// entries in market-hours-database.csv. At run time, the algorithm can update the market hours
        /// database via calls to AddData.
        /// </summary>
        /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
        /// <param name="symbol">The particular symbol being traded</param>
        /// <param name="securityType">The security type of the symbol</param>
        /// <param name="exchangeHours">The exchange hours for the specified symbol</param>
        /// <param name="dataTimeZone">The time zone of the symbol's raw data. Optional, defaults to the exchange time zone</param>
        /// <returns>The entry matching the specified market/symbol/security-type</returns>
        public virtual Entry SetEntry(string market, string symbol, SecurityType securityType, SecurityExchangeHours exchangeHours, DateTimeZone dataTimeZone = null)
        {
            dataTimeZone = dataTimeZone ?? exchangeHours.TimeZone;
            var key   = new SecurityDatabaseKey(market, symbol, securityType);
            var entry = new Entry(dataTimeZone, exchangeHours);

            _entries[key] = entry;
            return(entry);
        }
            public override Entry GetEntry(string market, string symbol, SecurityType securityType, DateTimeZone overrideTimeZone = null)
            {
                var tz = overrideTimeZone ?? TimeZones.Utc;

                return(new Entry(tz, SecurityExchangeHours.AlwaysOpen(tz)));
            }
Ejemplo n.º 14
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,
                                              Symbol symbol,
                                              Resolution resolution,
                                              bool fillDataForward,
                                              decimal leverage,
                                              bool extendedMarketHours,
                                              bool isInternalFeed,
                                              bool isCustomData,
                                              bool addToSymbolCache = true)
        {
            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
            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, 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);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Sets the regular market hours for the specified days If no days are specified then
        /// all days will be updated.
        /// </summary>
        /// <param name="marketHoursSegments">Specifies each segment of the market hours, such as premarket/market/postmark</param>
        /// <param name="days">The days of the week to set these times for</param>
        public void SetMarketHours(IEnumerable<MarketHoursSegment> marketHoursSegments, params DayOfWeek[] days)
        {
            if (days.IsNullOrEmpty()) days = Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>().ToArray();
            
            var marketHours = _exchangeHours.MarketHours.ToDictionary();
            marketHoursSegments = marketHoursSegments as IList<MarketHoursSegment> ?? marketHoursSegments.ToList();
            foreach (var day in days)
            {
                marketHours[day] = new LocalMarketHours(day, marketHoursSegments);
            }

            // create a new exchange hours instance for the new hours
            _exchangeHours = new SecurityExchangeHours(_exchangeHours.TimeZone, _exchangeHours.Holidays, marketHours);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Entry"/> class
 /// </summary>
 /// <param name="dataTimeZone">The raw data time zone</param>
 /// <param name="exchangeHours">The security exchange hours for this entry</param>
 public Entry(DateTimeZone dataTimeZone, SecurityExchangeHours exchangeHours)
 {
     DataTimeZone = dataTimeZone;
     ExchangeHours = exchangeHours;
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Define an enumerable date range of tradeable dates but expressed in a different time zone.
        /// </summary>
        /// <remarks>
        /// This is mainly used to bridge the gap between exchange time zone and data time zone for file written to disk. The returned
        /// enumerable of dates is gauranteed to be the same size or longer than those generated via <see cref="EachTradeableDay(ICollection{Security},DateTime,DateTime)"/>
        /// </remarks>
        /// <param name="exchange">The exchange hours</param>
        /// <param name="from">The start time in the exchange time zone</param>
        /// <param name="thru">The end time in the exchange time zone (inclusive of the final day)</param>
        /// <param name="timeZone">The timezone to project the dates into (inclusive of the final day)</param>
        /// <param name="includeExtendedMarketHours">True to include extended market hours trading in the search, false otherwise</param>
        /// <returns></returns>
        public static IEnumerable<DateTime> EachTradeableDayInTimeZone(SecurityExchangeHours exchange, DateTime from, DateTime thru, DateTimeZone timeZone, bool includeExtendedMarketHours = true)
        {
            var currentExchangeTime = from;
            thru = thru.Date.AddDays(1); // we want to include the full thru date
            while (currentExchangeTime < thru)
            {
                // take steps of max size of one day in the data time zone
                var currentInTimeZone = currentExchangeTime.ConvertTo(exchange.TimeZone, timeZone);
                var currentInTimeZoneEod = currentInTimeZone.Date.AddDays(1);

                // don't pass the end
                if (currentInTimeZoneEod.ConvertTo(timeZone, exchange.TimeZone) > thru)
                {
                    currentInTimeZoneEod = thru.ConvertTo(exchange.TimeZone, timeZone);
                }

                // perform market open checks in the exchange time zone
                var currentExchangeTimeEod = currentInTimeZoneEod.ConvertTo(timeZone, exchange.TimeZone);
                if (exchange.IsOpen(currentExchangeTime, currentExchangeTimeEod, includeExtendedMarketHours))
                {
                    yield return currentInTimeZone.Date;
                }

                currentExchangeTime = currentInTimeZoneEod.ConvertTo(timeZone, exchange.TimeZone);
            }
        } 
Ejemplo n.º 18
0
 /// <summary>
 /// Construct a new security vehicle based on the user options.
 /// </summary>
 public Security(Symbol symbol, SecurityExchangeHours exchangeHours, Cash quoteCurrency, SymbolProperties symbolProperties)
     : this(symbol,
         quoteCurrency,
         symbolProperties,
         new SecurityExchange(exchangeHours),
         new SecurityCache(),
         new SecurityPortfolioModel(),
         new ImmediateFillModel(),
         new InteractiveBrokersFeeModel(),
         new SpreadSlippageModel(),
         new ImmediateSettlementModel(),
         Securities.VolatilityModel.Null,
         new SecurityMarginModel(1m),
         new SecurityDataFilter()
         )
 {
 }
Ejemplo n.º 19
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)
        {
            // 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 configs = subscriptionManager.SubscriptionDataConfigService.Add(symbol, resolution, fillDataForward,
                                                                                extendedMarketHours, isFilteredSubscription, isInternalFeed,
                                                                                isCustomData, subscriptionDataTypes);
            var configList = new SubscriptionDataConfigList(symbol);

            configList.AddRange(configs);

            // 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 (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);
                }
                security = new Option.Option(symbol, exchangeHours, securityPortfolioManager.CashBook[CashBook.AccountCurrency], new Option.OptionSymbolProperties(symbolProperties));
                break;

            case SecurityType.Future:
                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 (!isInternalFeed)
            {
                security.IsTradable = true;
            }

            security.AddData(configList);

            // 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);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SecurityExchange"/> class using the specified
 /// exchange hours to determine open/close times
 /// </summary>
 /// <param name="exchangeHours">Contains the weekly exchange schedule plus holidays</param>
 public SecurityExchange(SecurityExchangeHours exchangeHours)
 {
     _exchangeHours = exchangeHours;
 }
Ejemplo n.º 21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SecurityExchange"/> class using the specified
 /// exchange hours to determine open/close times
 /// </summary>
 /// <param name="exchangeHours">Contains the weekly exchange schedule plus holidays</param>
 public SecurityExchange(SecurityExchangeHours exchangeHours)
 {
     _exchangeHours = exchangeHours;
 }
Ejemplo n.º 22
0
        public static SecurityExchangeHours CreateForexSecurityExchangeHours()
        {
            var sunday = new LocalMarketHours(DayOfWeek.Sunday, new TimeSpan(17, 0, 0), TimeSpan.FromTicks(Time.OneDay.Ticks - 1));
            var monday = LocalMarketHours.OpenAllDay(DayOfWeek.Monday);
            var tuesday = LocalMarketHours.OpenAllDay(DayOfWeek.Tuesday);
            var wednesday = LocalMarketHours.OpenAllDay(DayOfWeek.Wednesday);
            var thursday = LocalMarketHours.OpenAllDay(DayOfWeek.Thursday);
            var friday = new LocalMarketHours(DayOfWeek.Friday, TimeSpan.Zero, new TimeSpan(17, 0, 0));
            var saturday = LocalMarketHours.ClosedAllDay(DayOfWeek.Saturday);

            var exchangeHours = new SecurityExchangeHours(TimeZones.NewYork, USHoliday.Dates.Select(x => x.Date), new[]
            {
                sunday, monday, tuesday, wednesday, thursday, friday//, saturday
            }.ToDictionary(x => x.DayOfWeek));
            return exchangeHours;
        }
Ejemplo n.º 23
0
Archivo: Time.cs Proyecto: skyfyl/Lean
 /// <summary>
 /// Define an enumerable date range of tradeable dates - skip the holidays and weekends when securities in this algorithm don't trade.
 /// </summary>
 /// <param name="exchange">The security to get tradeable dates for</param>
 /// <param name="from">Start date</param>
 /// <param name="thru">End date</param>
 /// <returns>Enumerable date range</returns>
 public static IEnumerable<DateTime> EachTradeableDay(SecurityExchangeHours exchange, DateTime from, DateTime thru)
 {
     for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
     {
         if (exchange.IsDateOpen(day))
         {
             yield return day;
         }
     }
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Construct a new security vehicle based on the user options.
 /// </summary>
 public Security(SecurityExchangeHours exchangeHours, SubscriptionDataConfig config, Cash quoteCurrency, SymbolProperties symbolProperties)
     : this(config,
         quoteCurrency,
         symbolProperties,
         new SecurityExchange(exchangeHours),
         new SecurityCache(),
         new SecurityPortfolioModel(),
         new ImmediateFillModel(),
         new InteractiveBrokersFeeModel(),
         new SpreadSlippageModel(),
         new ImmediateSettlementModel(),
         new SecurityMarginModel(1m),
         new SecurityDataFilter())
 {
 }
Ejemplo n.º 25
0
Archivo: Time.cs Proyecto: skyfyl/Lean
        /// <summary>
        /// Determines the start time required to produce the requested number of bars and the given size
        /// </summary>
        /// <param name="exchange">The exchange used to test for market open hours</param>
        /// <param name="end">The end time of the last bar over the requested period</param>
        /// <param name="barSize">The length of each bar</param>
        /// <param name="barCount">The number of bars requested</param>
        /// <param name="extendedMarketHours">True to allow extended market hours bars, otherwise false for only normal market hours</param>
        /// <returns>The start time that would provide the specified number of bars ending at the specified end time, rounded down by the requested bar size</returns>
        public static DateTime GetStartTimeForTradeBars(SecurityExchangeHours exchange, DateTime end, TimeSpan barSize, int barCount, bool extendedMarketHours)
        {
            if (barSize <= TimeSpan.Zero)
            {
                throw new ArgumentException("barSize must be greater than TimeSpan.Zero", "barSize");
            }

            var current = end.RoundDown(barSize);
            for (int i = 0; i < barCount;)
            {
                var previous = current;
                current = current - barSize;
                if (exchange.IsOpen(current, previous, extendedMarketHours))
                {
                    i++;
                }
            }
            return current;
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HistoryRequest"/> class from the specified config and exchange hours
 /// </summary>
 /// <param name="config">The subscription data config used to initalize this request</param>
 /// <param name="hours">The exchange hours used for fill forward processing</param>
 /// <param name="startTimeUtc">The start time for this request,</param>
 /// <param name="endTimeUtc">The start time for this request</param>
 public HistoryRequest(SubscriptionDataConfig config, SecurityExchangeHours hours, DateTime startTimeUtc, DateTime endTimeUtc)
 {
     StartTimeUtc = startTimeUtc;
     EndTimeUtc = endTimeUtc;
     Symbol = config.Symbol;
     ExchangeHours = hours;
     Resolution = config.Resolution;
     FillForwardResolution = config.FillDataForward ? config.Resolution : (Resolution?) null;
     IncludeExtendedMarketHours = config.ExtendedMarketHours;
     DataType = config.Type;
     SecurityType = config.SecurityType;
     Market = config.Market;
     IsCustomData = config.IsCustomData;
     TimeZone = config.TimeZone;
 }
 public override SecurityExchangeHours GetExchangeHours(string market, Symbol symbol, SecurityType securityType, DateTimeZone overrideTimeZone = null)
 {
     return(SecurityExchangeHours.AlwaysOpen(overrideTimeZone ?? TimeZones.Utc));
 }