Example #1
0
 /// <summary>
 /// Adds the specified time zone to this time keeper
 /// </summary>
 /// <param name="timeZone"></param>
 public void AddTimeZone(DateTimeZone timeZone)
 {
     if (!_localTimeKeepers.ContainsKey(timeZone))
     {
         _localTimeKeepers[timeZone] = new LocalTimeKeeper(_utcDateTime, timeZone);
     }
 }
Example #2
0
 /// <summary>
 /// Gets a <see cref="SecurityExchangeHours"/> instance that is always open
 /// </summary>
 public static SecurityExchangeHours AlwaysOpen(DateTimeZone timeZone)
 {
     var dayOfWeeks = Enum.GetValues(typeof (DayOfWeek)).OfType<DayOfWeek>();
     return new SecurityExchangeHours(timeZone,
         Enumerable.Empty<DateTime>(),
         dayOfWeeks.Select(LocalMarketHours.OpenAllDay).ToDictionary(x => x.DayOfWeek)
         );
 }
Example #3
0
 /// <summary>
 /// Gets the <see cref="CoarseFundamental"/> data for the specified market/date
 /// </summary>
 public static IEnumerable<CoarseFundamental> GetCoarseFundamentals(string market, DateTimeZone timeZone, DateTime date, bool isLiveMode)
 {
     var factory = new CoarseFundamental();
     var config = new SubscriptionDataConfig(typeof(CoarseFundamental), SecurityType.Equity, new Symbol(market + "-coarse"), Resolution.Daily, market, timeZone, true, false, true, false);
     var reader = new BaseDataSubscriptionFactory(config, date, isLiveMode);
     var source = factory.GetSource(config, date, isLiveMode);
     return reader.Read(source).OfType<CoarseFundamental>();
 }
Example #4
0
 public TimeZone(string timeZoneId, Offset standardOffset, Offset wallOffset, NodaTime.DateTimeZone dateTimeZone)
 {
     base();
     this.set_TimeZoneId(timeZoneId);
     this.set_StandardOffset(standardOffset);
     this.set_WallOffset(wallOffset);
     this.set_DateTimeZone(dateTimeZone);
     return;
 }
Example #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ScheduleManager"/> class
        /// </summary>
        /// <param name="securities">Securities manager containing the algorithm's securities</param>
        /// <param name="timeZone">The algorithm's time zone</param>
        public ScheduleManager(SecurityManager securities, DateTimeZone timeZone)
        {
            _securities = securities;
            DateRules = new DateRules(securities);
            TimeRules = new TimeRules(securities, timeZone);

            // used for storing any events before the event schedule is set
            _preInitializedEvents = new List<ScheduledEvent>();
        }
 /// <summary>
 /// Constructs an instance from the given information.
 /// </summary>
 /// <remarks>
 /// User code is unlikely to need to deliberately call this constructor except
 /// possibly for testing.
 /// </remarks>
 /// <param name="localDateTime">The local date and time that was ambiguous</param>
 /// <param name="zone">The time zone in which the mapping is ambiguous</param>
 /// <param name="earlierMapping">The earlier possible mapping</param>
 /// <param name="laterMapping">The later possible mapping</param>
 public AmbiguousTimeException(LocalDateTime localDateTime, DateTimeZone zone,
     ZonedDateTime earlierMapping,
     ZonedDateTime laterMapping)
     : base("Local time " + localDateTime + " is ambiguous in time zone " + zone.Id)
 {
     this.localDateTime = localDateTime;
     this.zone = zone;
     this.earlierMapping = earlierMapping;
     this.laterMapping = laterMapping;
 }
Example #7
0
 /// <summary>
 /// Add Market Data Required (Overloaded method for backwards compatibility).
 /// </summary>
 /// <param name="symbol">Symbol of the asset we're like</param>
 /// <param name="resolution">Resolution of Asset Required</param>
 /// <param name="timeZone">The time zone the subscription's data is time stamped in</param>
 /// <param name="exchangeTimeZone">Specifies the time zone of the exchange for the security this subscription is for. This
 /// is this output time zone, that is, the time zone that will be used on BaseData instances</param>
 /// <param name="isCustomData">True if this is custom user supplied data, false for normal QC data</param>
 /// <param name="fillDataForward">when there is no data pass the last tradebar forward</param>
 /// <param name="extendedMarketHours">Request premarket data as well when true </param>
 /// <returns>The newly created <see cref="SubscriptionDataConfig"/></returns>
 public SubscriptionDataConfig Add(Symbol symbol, Resolution resolution, DateTimeZone timeZone, DateTimeZone exchangeTimeZone, bool isCustomData = false, bool fillDataForward = true, bool extendedMarketHours = false)
 {
     //Set the type: market data only comes in two forms -- ticks(trade by trade) or tradebar(time summaries)
     var dataType = typeof(TradeBar);
     if (resolution == Resolution.Tick) 
     {
         dataType = typeof(Tick);
     }
     return Add(dataType, symbol, resolution, timeZone, exchangeTimeZone, isCustomData, fillDataForward, extendedMarketHours, false);
 }
Example #8
0
 public RestApiBaseData ToBaseData(DateTimeZone timeZone, TimeSpan period)
 {
     var dateTime = QuantConnect.Time.UnixTimeStampToDateTime(time).ConvertFromUtc(timeZone).Subtract(period);
     return new RestApiBaseData
     {
         Symbol = symbol,
         Time = dateTime,
         EndTime = dateTime.Add(period),
         Value = (decimal) alpha
     };
 }
Example #9
0
        public PullTests()
        {
            timeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();

            store = new FakeStore();
            storeFactory = new TestStoreFactory(store);

            Emit(NewId<LocalCalendar>(),
                 new RemoteCalendarAdded(
                     new FakeRemote
                     {
                         Id = NewId<RemoteCalendar>()
                     }));
        }
        /// <summary>
        /// Gets the history for the requested securities
        /// </summary>
        /// <param name="requests">The historical data requests</param>
        /// <param name="sliceTimeZone">The time zone used when time stamping the slice instances</param>
        /// <returns>An enumerable of the slices of data covering the span specified in each request</returns>
        public IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone)
        {
            foreach (var request in requests)
            {
                var granularity = ToGranularity(request.Resolution);

                // Oanda only has 5-second bars, we return these for Resolution.Second
                var period = request.Resolution == Resolution.Second ?
                    TimeSpan.FromSeconds(5) : request.Resolution.ToTimeSpan();

                // set the starting date/time
                var startDateTime = request.StartTimeUtc;

                // loop until last date
                while (startDateTime <= request.EndTimeUtc)
                {
                    var start = startDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ");

                    // request blocks of bars at the requested resolution with a starting date/time
                    var oandaSymbol = _symbolMapper.GetBrokerageSymbol(request.Symbol);
                    var candles = DownloadBars(oandaSymbol, start, MaxBarsPerRequest, granularity);
                    if (candles.Count == 0)
                        break;

                    foreach (var candle in candles)
                    {
                        var time = GetDateTimeFromString(candle.time);
                        if (time > request.EndTimeUtc)
                            break;

                        var tradeBar = new TradeBar(
                            time, 
                            request.Symbol,
                            Convert.ToDecimal(candle.openMid),
                            Convert.ToDecimal(candle.highMid),
                            Convert.ToDecimal(candle.lowMid),
                            Convert.ToDecimal(candle.closeMid),
                            0,
                            period);

                        DataPointCount++;

                        yield return new Slice(tradeBar.EndTime, new[] { tradeBar });
                    }

                    // calculate the next request datetime
                    startDateTime = GetDateTimeFromString(candles[candles.Count - 1].time).Add(period);
                }
            }
        }
Example #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SecurityExchangeHours"/> class
        /// </summary>
        /// <param name="timeZone">The time zone the dates and hours are represented in</param>
        /// <param name="holidayDates">The dates this exchange is closed for holiday</param>
        /// <param name="marketHoursForEachDayOfWeek">The exchange's schedule for each day of the week</param>
        public SecurityExchangeHours(DateTimeZone timeZone, IEnumerable<DateTime> holidayDates, IReadOnlyDictionary<DayOfWeek, LocalMarketHours> marketHoursForEachDayOfWeek)
        {
            _timeZone = timeZone;
            _holidays = holidayDates.Select(x => x.Date.Ticks).ToHashSet();
            // make a copy of the dictionary for internal use
            _openHoursByDay = new Dictionary<DayOfWeek, LocalMarketHours>(marketHoursForEachDayOfWeek.ToDictionary());

            SetMarketHoursForDay(DayOfWeek.Sunday, out _sunday);
            SetMarketHoursForDay(DayOfWeek.Monday, out _monday);
            SetMarketHoursForDay(DayOfWeek.Tuesday, out _tuesday);
            SetMarketHoursForDay(DayOfWeek.Wednesday, out _wednesday);
            SetMarketHoursForDay(DayOfWeek.Thursday, out _thursday);
            SetMarketHoursForDay(DayOfWeek.Friday, out _friday);
            SetMarketHoursForDay(DayOfWeek.Saturday, out _saturday);
        }
Example #12
0
 private static void DumpZone(DateTimeZone zone, Options options)
 {
     Console.Write("{0}\r\n", zone.Id);
     var initial = zone.GetZoneInterval(Instant.MinValue);
     Console.Write("Initially: {0} {1} {2}\r\n",
         OffsetPattern.Format(initial.WallOffset),
         initial.Savings != Offset.Zero ? "daylight" : "standard",
         initial.Name);
     foreach (var zoneInterval in zone.GetZoneIntervals(options.Start, options.End)
         .Where(zi => zi.HasStart && zi.Start >= options.Start))
     {
         Console.Write("{0} {1} {2} {3}\r\n",
             InstantPattern.Format(zoneInterval.Start),
             OffsetPattern.Format(zoneInterval.WallOffset),
             zoneInterval.Savings != Offset.Zero ? "daylight" : "standard",
             zoneInterval.Name);
     }
 }
Example #13
0
 /// <summary>
 /// Gets the <see cref="LocalTimeKeeper"/> instance for the specified time zone
 /// </summary>
 /// <param name="timeZone">The time zone whose <see cref="LocalTimeKeeper"/> we seek</param>
 /// <returns>The <see cref="LocalTimeKeeper"/> instance for the specified time zone</returns>
 public LocalTimeKeeper GetLocalTimeKeeper(DateTimeZone timeZone)
 {
     LocalTimeKeeper localTimeKeeper;
     if (!_localTimeKeepers.TryGetValue(timeZone, out localTimeKeeper))
     {
         localTimeKeeper = new LocalTimeKeeper(UtcTime, timeZone);
         _localTimeKeepers[timeZone] = localTimeKeeper;
     }
     return localTimeKeeper;
 }
 IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay, DateTimeZone timeZone)
 {
     return SetTimeRule(_schedule.TimeRules.At(timeOfDay, timeZone));
 }
 /// <summary>
 /// Gets the history for the requested securities
 /// </summary>
 /// <param name="requests">The historical data requests</param>
 /// <param name="sliceTimeZone">The time zone used when time stamping the slice instances</param>
 /// <returns>An enumerable of the slices of data covering the span specified in each request</returns>
 public IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone)
 {
     foreach (var request in requests)
     {
         foreach (var slice in _historyPort.ProcessHistoryRequests(request))
         {
             yield return slice;
         }
     }
 }
Example #16
0
 /// <summary>
 /// Specifies an event should fire at the specified time of day in the specified time zone
 /// </summary>
 /// <param name="hour">The hour</param>
 /// <param name="minute">The minute</param>
 /// <param name="second">The second</param>
 /// <param name="timeZone">The time zone the event time is represented in</param>
 /// <returns>A time rule that fires at the specified time in the algorithm's time zone</returns>
 public ITimeRule At(int hour, int minute, int second, DateTimeZone timeZone)
 {
     return At(new TimeSpan(hour, minute, second), timeZone);
 }
Example #17
0
        /// <summary>
        /// Constructor for Data Subscriptions
        /// </summary>
        /// <param name="objectType">Type of the data objects.</param>
        /// <param name="symbol">Symbol of the asset we're requesting</param>
        /// <param name="resolution">Resolution of the asset we're requesting</param>
        /// <param name="timeZone">The time zone the raw data is time stamped in</param>
        /// <param name="fillForward">Fill in gaps with historical data</param>
        /// <param name="extendedHours">Equities only - send in data from 4am - 8pm</param>
        /// <param name="isInternalFeed">Set to true if this subscription is added for the sole purpose of providing currency conversion rates,
        /// setting this flag to true will prevent the data from being sent into the algorithm's OnData methods</param>
        /// <param name="isCustom">True if this is user supplied custom data, false for normal QC data</param>
        public SubscriptionDataConfig(Type objectType, 
            Symbol symbol, 
            Resolution resolution, 
            DateTimeZone timeZone,
            bool fillForward, 
            bool extendedHours,
            bool isInternalFeed,
            bool isCustom = false)
        {
            Type = objectType;
            SecurityType = symbol.ID.SecurityType;
            Resolution = resolution;
            _sid = symbol.ID;
            FillDataForward = fillForward;
            ExtendedMarketHours = extendedHours;
            PriceScaleFactor = 1;
            MappedSymbol = symbol.Value;
            IsInternalFeed = isInternalFeed;
            IsCustomData = isCustom;
            Market = symbol.ID.Market;
            TimeZone = timeZone;
            Consolidators = new HashSet<IDataConsolidator>();

            switch (resolution)
            {
                case Resolution.Tick:
                    //Ticks are individual sales and fillforward doesn't apply.
                    Increment = TimeSpan.FromSeconds(0);
                    FillDataForward = false;
                    break;
                case Resolution.Second:
                    Increment = TimeSpan.FromSeconds(1);
                    break;
                case Resolution.Minute:
                    Increment = TimeSpan.FromMinutes(1);
                    break;
                case Resolution.Hour:
                    Increment = TimeSpan.FromHours(1);
                    break;
                case Resolution.Daily:
                    Increment = TimeSpan.FromDays(1);
                    break;
                default:
                    throw new InvalidEnumArgumentException("Unexpected Resolution: " + resolution);
            }
        }
 protected override void OnNavigatedFrom(NavigationEventArgs e)
 {
     this.navigationHelper.OnNavigatedFrom(e);
     DateTimeZone = null;
     Reminder = null;
 }
Example #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ZonedDateTime"/> struct.
 /// </summary>
 /// <param name="instant">The instant.</param>
 /// <param name="zone">The time zone.</param>
 /// <param name="calendar">The calendar system.</param>
 public ZonedDateTime(Instant instant, DateTimeZone zone, CalendarSystem calendar)
 {
     this.zone      = Preconditions.CheckNotNull(zone, nameof(zone));
     offsetDateTime = new OffsetDateTime(instant, zone.GetUtcOffset(instant), Preconditions.CheckNotNull(calendar, nameof(calendar)));
 }
Example #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ZonedDateTime" /> struct in the specified time zone
 /// and the ISO calendar.
 /// </summary>
 /// <param name="instant">The instant.</param>
 /// <param name="zone">The time zone.</param>
 public ZonedDateTime(Instant instant, DateTimeZone zone)
 {
     this.zone      = Preconditions.CheckNotNull(zone, nameof(zone));
     offsetDateTime = new OffsetDateTime(instant, zone.GetUtcOffset(instant));
 }
Example #21
0
 public ZonedDateTime InZone([NotNull] DateTimeZone zone) =>
 // zone is checked for nullity by the constructor.
 new ZonedDateTime(this, zone);
Example #22
0
 public ZonedDateTime InZone(DateTimeZone zone)
 {
     Preconditions.CheckNotNull(zone, nameof(zone));
     return(ToInstant().InZone(zone));
 }
Example #23
0
 public ZonedDateTime InFixedZone() => new ZonedDateTime(this, DateTimeZone.ForOffset(Offset));
Example #24
0
 /// <summary>
 /// Creates a new <see cref="ZonedClock"/> with the given clock, time zone and calendar system.
 /// </summary>
 /// <param name="clock">Clock to use to obtain instants.</param>
 /// <param name="zone">Time zone to adjust instants into.</param>
 /// <param name="calendar">Calendar system to use.</param>
 public ZonedClock(IClock clock, DateTimeZone zone, CalendarSystem calendar)
 {
     this.clock    = Preconditions.CheckNotNull(clock, nameof(clock));
     this.zone     = Preconditions.CheckNotNull(zone, nameof(zone));
     this.calendar = Preconditions.CheckNotNull(calendar, nameof(calendar));
 }
Example #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocalTimeKeeper"/> class
 /// </summary>
 /// <param name="utcDateTime">The current time in UTC</param>
 /// <param name="timeZone">The time zone</param>
 internal LocalTimeKeeper(DateTime utcDateTime, DateTimeZone timeZone)
 {
     _timeZone = timeZone;
     _localTime = new Lazy<DateTime>(() => utcDateTime.ConvertTo(DateTimeZone.Utc, _timeZone));
 }
Example #26
0
 /// <summary>
 /// Internal constructor from pre-validated values.
 /// </summary>
 internal ZonedDateTime(OffsetDateTime offsetDateTime, DateTimeZone zone)
 {
     this.offsetDateTime = offsetDateTime;
     this.zone           = zone;
 }
Example #27
0
        /// <summary>
        /// Creates a new <see cref="TimeSlice"/> for the specified time using the specified data
        /// </summary>
        /// <param name="utcDateTime">The UTC frontier date time</param>
        /// <param name="algorithmTimeZone">The algorithm's time zone, required for computing algorithm and slice time</param>
        /// <param name="cashBook">The algorithm's cash book, required for generating cash update pairs</param>
        /// <param name="data">The data in this <see cref="TimeSlice"/></param>
        /// <param name="changes">The new changes that are seen in this time slice as a result of universe selection</param>
        /// <returns>A new <see cref="TimeSlice"/> containing the specified data</returns>
        public static TimeSlice Create(DateTime utcDateTime, DateTimeZone algorithmTimeZone, CashBook cashBook, List<KeyValuePair<Security, List<BaseData>>> data, SecurityChanges changes)
        {
            int count = 0;
            var security = new List<KeyValuePair<Security, BaseData>>();
            var custom = new List<KeyValuePair<Security, List<BaseData>>>();
            var consolidator = new List<KeyValuePair<SubscriptionDataConfig, List<BaseData>>>();
            var allDataForAlgorithm = new List<BaseData>(data.Count);
            var cash = new List<KeyValuePair<Cash, BaseData>>(cashBook.Count);

            var cashSecurities = new HashSet<Symbol>();
            foreach (var cashItem in cashBook.Values)
            {
                cashSecurities.Add(cashItem.SecuritySymbol);
            }

            Split split;
            Dividend dividend;
            Delisting delisting;
            SymbolChangedEvent symbolChange;

            var algorithmTime = utcDateTime.ConvertFromUtc(algorithmTimeZone);
            var tradeBars = new TradeBars(algorithmTime);
            var ticks = new Ticks(algorithmTime);
            var splits = new Splits(algorithmTime);
            var dividends = new Dividends(algorithmTime);
            var delistings = new Delistings(algorithmTime);
            var symbolChanges = new SymbolChangedEvents(algorithmTime);

            foreach (var kvp in data)
            {
                var list = kvp.Value;
                var symbol = kvp.Key.Symbol;
                
                // keep count of all data points
                if (list.Count == 1 && list[0] is BaseDataCollection)
                {
                    count += ((BaseDataCollection) list[0]).Data.Count;
                }
                else
                {
                    count += list.Count;
                }

                BaseData update = null;
                var consolidatorUpdate = new List<BaseData>(list.Count);
                for (int i = 0; i < list.Count; i++)
                {
                    var baseData = list[i];
                    if (!kvp.Key.SubscriptionDataConfig.IsInternalFeed)
                    {
                        // this is all the data that goes into the algorithm
                        allDataForAlgorithm.Add(baseData);
                        if (kvp.Key.SubscriptionDataConfig.IsCustomData)
                        {
                            // this is all the custom data
                            custom.Add(kvp);
                        }
                    }
                    // don't add internal feed data to ticks/bars objects
                    if (baseData.DataType != MarketDataType.Auxiliary)
                    {
                        if (!kvp.Key.SubscriptionDataConfig.IsInternalFeed)
                        {
                            // populate ticks and tradebars dictionaries with no aux data
                            if (baseData.DataType == MarketDataType.Tick)
                            {
                                List<Tick> ticksList;
                                if (!ticks.TryGetValue(symbol, out ticksList))
                                {
                                    ticksList = new List<Tick> {(Tick) baseData};
                                    ticks[symbol] = ticksList;
                                }
                                ticksList.Add((Tick) baseData);
                            }
                            else if (baseData.DataType == MarketDataType.TradeBar)
                            {
                                tradeBars[symbol] = (TradeBar) baseData;
                            }

                            // this is data used to update consolidators
                            consolidatorUpdate.Add(baseData);
                        }

                        // this is the data used set market prices
                        update = baseData;
                    }
                    // include checks for various aux types so we don't have to construct the dictionaries in Slice
                    else if ((delisting = baseData as Delisting) != null)
                    {
                        delistings[symbol] = delisting;
                    }
                    else if ((dividend = baseData as Dividend) != null)
                    {
                        dividends[symbol] = dividend;
                    }
                    else if ((split = baseData as Split) != null)
                    {
                        splits[symbol] = split;
                    }
                    else if ((symbolChange = baseData as SymbolChangedEvent) != null)
                    {
                        // symbol changes is keyed by the requested symbol
                        symbolChanges[kvp.Key.SubscriptionDataConfig.Symbol] = symbolChange;
                    }
                }

                // check for 'cash securities' if we found valid update data for this symbol
                // and we need this data to update cash conversion rates, long term we should
                // have Cash hold onto it's security, then he can update himself, or rather, just
                // patch through calls to conversion rate to compue it on the fly using Security.Price
                if (update != null && cashSecurities.Contains(kvp.Key.Symbol))
                {
                    foreach (var cashKvp in cashBook)
                    {
                        if (cashKvp.Value.SecuritySymbol == kvp.Key.Symbol)
                        {
                            cash.Add(new KeyValuePair<Cash, BaseData>(cashKvp.Value, update));
                        }
                    }
                }

                security.Add(new KeyValuePair<Security, BaseData>(kvp.Key, update));
                consolidator.Add(new KeyValuePair<SubscriptionDataConfig, List<BaseData>>(kvp.Key.SubscriptionDataConfig, consolidatorUpdate));
            }

            var slice = new Slice(utcDateTime.ConvertFromUtc(algorithmTimeZone), allDataForAlgorithm, tradeBars, ticks, splits, dividends, delistings, symbolChanges, allDataForAlgorithm.Count > 0);

            return new TimeSlice(utcDateTime, count, slice, data, cash, security, consolidator, custom, changes);
        }
Example #28
0
 private static TimeRules GetTimeRules(DateTimeZone dateTimeZone)
 {
     var timeKeeper = new TimeKeeper(DateTime.Today, new List<DateTimeZone>());
     var manager = new SecurityManager(timeKeeper);
     var securityExchangeHours = SecurityExchangeHoursProvider.FromDataFolder().GetExchangeHours("usa", null, SecurityType.Equity);
     var config = new SubscriptionDataConfig(typeof(TradeBar), SecurityType.Equity, "SPY", Resolution.Daily, "usa", securityExchangeHours.TimeZone, true, false, false);
     manager.Add("SPY", new Security(securityExchangeHours, config, 1));
     var rules = new TimeRules(manager, dateTimeZone);
     return rules;
 }
Example #29
0
 public ZonedDateTime WithZone(DateTimeZone targetZone)
 {
     Preconditions.CheckNotNull(targetZone, nameof(targetZone));
     return(new ZonedDateTime(ToInstant(), targetZone, Calendar));
 }
Example #30
0
 /// <summary>
 /// Copy constructor with overrides
 /// </summary>
 /// <param name="config">The config to copy, then overrides are applied and all option</param>
 /// <param name="objectType">Type of the data objects.</param>
 /// <param name="securityType">SecurityType Enum Set Equity/FOREX/Futures etc.</param>
 /// <param name="symbol">Symbol of the asset we're requesting</param>
 /// <param name="resolution">Resolution of the asset we're requesting</param>
 /// <param name="market">The market this subscription comes from</param>
 /// <param name="timeZone">The time zone the raw data is time stamped in</param>
 /// <param name="fillForward">Fill in gaps with historical data</param>
 /// <param name="extendedHours">Equities only - send in data from 4am - 8pm</param>
 /// <param name="isInternalFeed">Set to true if this subscription is added for the sole purpose of providing currency conversion rates,
 /// setting this flag to true will prevent the data from being sent into the algorithm's OnData methods</param>
 /// <param name="isCustom">True if this is user supplied custom data, false for normal QC data</param>
 public SubscriptionDataConfig(SubscriptionDataConfig config,
     Type objectType = null,
     SecurityType? securityType = null,
     Symbol symbol = null,
     Resolution? resolution = null,
     string market = null,
     DateTimeZone timeZone = null,
     bool? fillForward = null,
     bool? extendedHours = null,
     bool? isInternalFeed = null,
     bool? isCustom = null)
     : this(objectType ?? config.Type,
     symbol ?? config.Symbol,
     resolution ?? config.Resolution,
     timeZone ?? config.TimeZone,
     fillForward ?? config.FillDataForward,
     extendedHours ?? config.ExtendedMarketHours,
     isInternalFeed ?? config.IsInternalFeed,
     isCustom ?? config.IsCustomData)
 {
 }
Example #31
0
 public void Deconstruct(out LocalDateTime localDateTime, out DateTimeZone dateTimeZone, out Offset offset)
 {
     localDateTime = LocalDateTime;
     dateTimeZone  = Zone;
     offset        = Offset;
 }
Example #32
0
        /// <summary>
        /// Specifies an event should fire at the specified time of day in the specified time zone
        /// </summary>
        /// <param name="timeOfDay">The time of day in the algorithm's time zone the event should fire</param>
        /// <param name="timeZone">The time zone the date time is expressed in</param>
        /// <returns>A time rule that fires at the specified time in the algorithm's time zone</returns>
        public ITimeRule At(TimeSpan timeOfDay, DateTimeZone timeZone)
        {
            var name = string.Join(",", timeOfDay.TotalHours.ToString("0.##"));
            Func<IEnumerable<DateTime>, IEnumerable<DateTime>> applicator = dates =>
                from date in dates
                let localEventTime = date + timeOfDay
                let utcEventTime = localEventTime.ConvertToUtc(timeZone)
                select utcEventTime;

            return new FuncTimeRule(name, applicator);
        }
Example #33
0
 /// <summary>
 /// Creates a new instance for the given local date/time and time zone.
 /// </summary>
 /// <remarks>
 /// User code is unlikely to need to deliberately call this constructor except
 /// possibly for testing.
 /// </remarks>
 /// <param name="localDateTime">The local date/time which is skipped in the specified time zone.</param>
 /// <param name="zone">The time zone in which the local date/time does not exist.</param>
 public SkippedTimeException(LocalDateTime localDateTime, [NotNull] DateTimeZone zone)
     : base("Local time " + localDateTime + " is invalid in time zone " + Preconditions.CheckNotNull(zone, nameof(zone)).Id)
 {
     this.LocalDateTime = localDateTime;
     this.Zone          = zone;
 }
 IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second, DateTimeZone timeZone)
 {
     return SetTimeRule(_schedule.TimeRules.At(hour, minute, second, timeZone));
 }
Example #35
0
        /// <summary>
        /// Constructor for Data Subscriptions
        /// </summary>
        /// <param name="objectType">Type of the data objects.</param>
        /// <param name="securityType">SecurityType Enum Set Equity/FOREX/Futures etc.</param>
        /// <param name="symbol">Symbol of the asset we're requesting</param>
        /// <param name="resolution">Resolution of the asset we're requesting</param>
        /// <param name="market">The market this subscription comes from</param>
        /// <param name="timeZone">The time zone the raw data is time stamped in</param>
        /// <param name="fillForward">Fill in gaps with historical data</param>
        /// <param name="extendedHours">Equities only - send in data from 4am - 8pm</param>
        /// <param name="isTradeBar">Set to true if the objectType has Open, High, Low, and Close properties defines, does not need to directly derive from the TradeBar class
        /// This is used for the DynamicDataConsolidator</param>
        /// <param name="hasVolume">Set to true if the objectType has a Volume property defined. This is used for the DynamicDataConsolidator</param>
        /// <param name="isInternalFeed">Set to true if this subscription is added for the sole purpose of providing currency conversion rates,
        /// setting this flag to true will prevent the data from being sent into the algorithm's OnData methods</param>
        /// <param name="subscriptionIndex">The subscription index from the SubscriptionManager, this MUST equal the subscription's index or all hell will break loose!</param>
        public SubscriptionDataConfig(Type objectType, 
            SecurityType securityType, 
            string symbol, 
            Resolution resolution, 
            string market, 
            DateTimeZone timeZone,
            bool fillForward, 
            bool extendedHours,
            bool isTradeBar,
            bool hasVolume,
            bool isInternalFeed,
            int subscriptionIndex)
        {
            Type = objectType;
            SecurityType = securityType;
            Resolution = resolution;
            Symbol = symbol.ToUpper();
            FillDataForward = fillForward;
            ExtendedMarketHours = extendedHours;
            IsTradeBar = isTradeBar;
            HasVolume = hasVolume;
            PriceScaleFactor = 1;
            MappedSymbol = symbol;
            IsInternalFeed = isInternalFeed;
            SubscriptionIndex = subscriptionIndex;
            Market = market;
            TimeZone = timeZone;
            Consolidators = new HashSet<IDataConsolidator>();

            // verify the market string contains letters a-Z
            if (string.IsNullOrWhiteSpace(market))
            {
                throw new ArgumentException("The market cannot be an empty string.");
            }
            if (!Regex.IsMatch(market, @"^[a-zA-Z]+$"))
            {
                throw new ArgumentException("The market must only contain letters A-Z.");
            }

            switch (resolution)
            {
                case Resolution.Tick:
                    //Ticks are individual sales and fillforward doesn't apply.
                    Increment = TimeSpan.FromSeconds(0);
                    FillDataForward = false;
                    break;
                case Resolution.Second:
                    Increment = TimeSpan.FromSeconds(1);
                    break;
                case Resolution.Minute:
                    Increment = TimeSpan.FromMinutes(1);
                    break;
                case Resolution.Hour:
                    Increment = TimeSpan.FromHours(1);
                    break;
                case Resolution.Daily:
                    Increment = TimeSpan.FromDays(1);
                    break;
                default:
                    throw new InvalidEnumArgumentException("Unexpected Resolution: " + resolution);
            }
        }
Example #36
0
        public static int DaysOff(string date, string time, string rpfTimeZone, string ingestTimeZone)
        {
            int           tensPlace     = 0;
            DateTime      localDt       = DateTime.Parse(string.Format("{0} {1}", date, time));
            LocalTime     localTime     = new LocalTime(localDt.Hour, localDt.Minute, localDt.Second);
            int           hour          = localDt.Hour;
            LocalDateTime localDateTime = LocalDateTime.FromDateTime(localDt);

            DateTimeZoneProviders dtzp = new DateTimeZoneProviders();

            DateTimeZone rpfZone    = dtzp.Tzdb[rpfTimeZone];
            DateTimeZone ingestZone = dtzp.Tzdb[ingestTimeZone];

            ZonedDateTime zonedDateTime = localDateTime.InZoneLeniently(rpfZone);
            Offset        rpfOffset     = rpfZone.GetUtcOffset(zonedDateTime.ToInstant());
            Offset        ingestOffset  = ingestZone.GetUtcOffset(zonedDateTime.ToInstant());


            ZonedDateTime zeroTime   = new LocalDateTime(LocalDate.FromDateTime(localDt), new LocalTime(0, 15)).InZoneLeniently(ingestZone);
            ZonedDateTime elevenTime = new LocalDateTime(LocalDate.FromDateTime(localDt), new LocalTime(11, 15)).InZoneLeniently(ingestZone);

            ZonedDateTime zeroTimeRpf   = new LocalDateTime(LocalDate.FromDateTime(localDt), new LocalTime(0, 15)).InZoneLeniently(rpfZone);
            ZonedDateTime elevenTimeRpf = new LocalDateTime(LocalDate.FromDateTime(localDt), new LocalTime(11, 15)).InZoneLeniently(rpfZone);

            Offset zeroOffset   = zeroTimeRpf.Offset - zeroTime.Offset;
            Offset elevenOffset = elevenTimeRpf.Offset - elevenTime.Offset;

            if (Math.Abs(zeroOffset.Milliseconds) < Math.Abs(elevenOffset.Milliseconds))
            {
                var zeroClock = new LocalTime(0, 0);
                var lowTime   = zeroClock.PlusMilliseconds(-zeroOffset.Milliseconds);
                var highTime  = zeroClock.PlusMilliseconds(-elevenOffset.Milliseconds);

                if (localTime >= lowTime && localTime < highTime)
                {
                    tensPlace = 10;
                }
            }

            /*
             *
             * at0 get offsets and subtract rpfoffat0 - ingestOffsetat0  (-4)
             * at11 get offsets and subtract rpfoffat11 - ingestoffat11 (-5)
             *
             * if these are different
             *  range is (0 in time) - at0 or (0 - -4) = 4
             *   to (0 in time) -at11 or (0 - -5) = 5
             *
             *
             */

            var offsetDelta = rpfOffset - ingestOffset;
            var hrsToAdd    = offsetDelta.Milliseconds / NodaConstants.MillisecondsPerHour;

            var newHour = (hour + hrsToAdd);

            if (newHour < 0)
            {
                return(-1 - tensPlace);
            }
            else if (newHour > 24)
            {
                return(1 + tensPlace);
            }
            else
            {
                return(0 + tensPlace);
            }
        }
Example #37
0
 public ZonedDateTime InZone([NotNull] DateTimeZone zone, [NotNull] CalendarSystem calendar)
 {
     Preconditions.CheckNotNull(zone, nameof(zone));
     Preconditions.CheckNotNull(calendar, nameof(calendar));
     return(new ZonedDateTime(this, zone, calendar));
 }
Example #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TimeRules"/> helper class
 /// </summary>
 /// <param name="securities">The security manager</param>
 /// <param name="timeZone">The algorithm's default time zone</param>
 public TimeRules(SecurityManager securities, DateTimeZone timeZone)
 {
     _securities = securities;
     _timeZone = timeZone;
 }
 /// <summary>
 /// Creates a new instance for the given local date/time and time zone.
 /// </summary>
 /// <remarks>
 /// User code is unlikely to need to deliberately call this constructor except
 /// possibly for testing.
 /// </remarks>
 /// <param name="localDateTime">The local date/time which is skipped in the specified time zone.</param>
 /// <param name="zone">The time zone in which the local date/time does not exist.</param>
 public SkippedTimeException(LocalDateTime localDateTime, DateTimeZone zone)
     : base("Local time " + localDateTime + " is invalid in time zone " + zone.Id)
 {
     this.localDateTime = localDateTime;
     this.zone          = zone;
 }
Example #40
0
 /// <summary>
 /// Sets the default time zone
 /// </summary>
 /// <param name="timeZone">The time zone to use for helper methods that can't resolve a time zone</param>
 public void SetDefaultTimeZone(DateTimeZone timeZone)
 {
     _timeZone = timeZone;
 }
Example #41
0
 public Diary(IClock clock, CalendarSystem calendar, DateTimeZone timeZone)
 {
     _clock = clock;
     _calendar = calendar;
     _timeZone = timeZone;
 }
Example #42
0
 /// <summary>
 /// Gets the local time in the specified time zone. If the specified <see cref="DateTimeZone"/>
 /// has not already been added, this will throw a <see cref="KeyNotFoundException"/>.
 /// </summary>
 /// <param name="timeZone">The time zone to get local time for</param>
 /// <returns>The local time in the specifed time zone</returns>
 public DateTime GetTimeIn(DateTimeZone timeZone)
 {
     return GetLocalTimeKeeper(timeZone).LocalTime;
 }
Example #43
0
 /// <summary>
 /// Gets the <see cref="LocalTimeKeeper"/> instance for the specified time zone
 /// </summary>
 /// <param name="timeZone">The time zone whose <see cref="LocalTimeKeeper"/> we seek</param>
 /// <returns>The <see cref="LocalTimeKeeper"/> instance for the specified time zone</returns>
 public LocalTimeKeeper GetLocalTimeKeeper(DateTimeZone timeZone)
 {
     return _localTimeKeepers[timeZone];
 }
Example #44
-1
        /// <summary>
        /// Initializes a new instance of the <see cref="TimeZoneOffsetProvider"/> class
        /// </summary>
        /// <param name="timeZone">The time zone to provide offsets for</param>
        /// <param name="utcStartTime">The start of the range of offsets</param>
        /// <param name="utcEndTime">The en of the range of offsets</param>
        public TimeZoneOffsetProvider(DateTimeZone timeZone, DateTime utcStartTime, DateTime utcEndTime)
        {
            _timeZone = timeZone;

            // pad the end so we get the correct zone interval
            utcEndTime += TimeSpan.FromDays(2*365);

            var start = DateTimeZone.Utc.AtLeniently(LocalDateTime.FromDateTime(utcStartTime));
            var end = DateTimeZone.Utc.AtLeniently(LocalDateTime.FromDateTime(utcEndTime));
            var zoneIntervals = _timeZone.GetZoneIntervals(start.ToInstant(), end.ToInstant());
            _discontinuities = new Queue<long>(zoneIntervals.Select(x => x.Start.ToDateTimeUtc().Ticks));

            if (_discontinuities.Count == 0)
            {
                // end of discontinuities
                _nextDiscontinuity = DateTime.MaxValue.Ticks;
                _currentOffsetTicks = _timeZone.GetUtcOffset(Instant.FromDateTimeUtc(DateTime.UtcNow)).Ticks;
            }
            else
            {
                // get the offset just before the next discontinuity to initialize
                _nextDiscontinuity = _discontinuities.Dequeue();
                _currentOffsetTicks = _timeZone.GetUtcOffset(Instant.FromDateTimeUtc(new DateTime(_nextDiscontinuity - 1, DateTimeKind.Utc))).Ticks;
            }
        }