Representation of time zone.
 public void AllZonesStartAndEndOfTime(DateTimeZone zone)
 {
     var firstInterval = zone.GetZoneInterval(Instant.MinValue);
     Assert.IsFalse(firstInterval.HasStart);
     var lastInterval = zone.GetZoneInterval(Instant.MaxValue);
     Assert.IsFalse(lastInterval.HasEnd);
 }
 protected override bool EqualsImpl(DateTimeZone other)
 {
     DaylightSavingsDateTimeZone otherZone = (DaylightSavingsDateTimeZone)other;
     return Id == otherZone.Id && 
         standardOffset == otherZone.standardOffset && 
         dstRecurrence.Equals(otherZone.dstRecurrence) &&
         standardRecurrence.Equals(otherZone.standardRecurrence);
 }
 /// <summary>
 /// Validates that all the periods before the tail zone make sense. We have to start at the beginning of time,
 /// and then have adjoining periods. This is only called in the constructors.
 /// </summary>
 /// <remarks>This is only called from the constructors, but is internal to make it easier to test.</remarks>
 /// <exception cref="ArgumentException">The periods specified are invalid.</exception>
 internal static void ValidatePeriods(ZoneInterval[] periods, DateTimeZone tailZone)
 {
     Preconditions.CheckArgument(periods.Length > 0, nameof(periods), "No periods specified in precalculated time zone");
     Preconditions.CheckArgument(!periods[0].HasStart, nameof(periods), "Periods in precalculated time zone must start with the beginning of time");
     for (int i = 0; i < periods.Length - 1; i++)
     {
         // Safe to use End here: there can't be a period *after* an endless one. Likewise it's safe to use Start on the next 
         // period, as there can't be a period *before* one which goes back to the start of time.
         Preconditions.CheckArgument(periods[i].End == periods[i + 1].Start, nameof(periods), "Non-adjoining ZoneIntervals for precalculated time zone");
     }
     Preconditions.CheckArgument(tailZone != null || periods[periods.Length - 1].RawEnd == Instant.AfterMaxValue, nameof(tailZone), "Null tail zone given but periods don't cover all of time");
 }
 static DaylightSavingsDateTimeZoneBenchmarks()
 {
     // Build a daylight savings zone which basically models modern America/Los_Angeles.
     SampleZone = new DaylightSavingsDateTimeZone("America/Los_Angeles", Offset.FromHours(-8),
         new ZoneRecurrence("PDT", Offset.FromHours(1),
             new ZoneYearOffset(TransitionMode.Wall, monthOfYear: 3, dayOfMonth: 8, dayOfWeek: 7,
                                advance: true, timeOfDay: new LocalTime(2, 0)),
             int.MinValue, int.MaxValue),
         new ZoneRecurrence("PST", Offset.FromHours(0),
             new ZoneYearOffset(TransitionMode.Standard, monthOfYear: 11, dayOfMonth: 1, dayOfWeek: 7,
                                advance: true, timeOfDay: new LocalTime(2, 0)),
             int.MinValue, int.MaxValue));
 }
Esempio n. 5
0
 private static void AssertImpossible(LocalDateTime localTime, DateTimeZone zone)
 {
     try
     {
         zone.AtExactly(localTime);
         Assert.Fail("Expected exception");
     }
     catch (SkippedTimeException e)
     {
         Assert.AreEqual(localTime, e.LocalDateTime);
         Assert.AreEqual(zone, e.Zone);
     }
 }
 internal PrecalculatedDateTimeZone([NotNull] string id, [NotNull] ZoneInterval[] intervals, DateTimeZone tailZone)
     : base(id, false,
            ComputeOffset(intervals, tailZone, Offset.Min),
            ComputeOffset(intervals, tailZone, Offset.Max))
 {
     this.tailZone = tailZone;
     this.periods = intervals;
     this.tailZone = tailZone;
     this.tailZoneStart = intervals[intervals.Length - 1].RawEnd; // We want this to be AfterMaxValue for tail-less zones.
     if (tailZone != null)
     {
         // Cache a "clamped" zone interval for use at the start of the tail zone.
         firstTailZoneInterval = tailZone.GetZoneInterval(tailZoneStart).WithStart(tailZoneStart);
     }
     ValidatePeriods(intervals, tailZone);
 }
Esempio n. 7
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);
     }
 }
Esempio n. 8
0
        private static void AssertAmbiguous(LocalDateTime localTime, DateTimeZone zone)
        {
            ZonedDateTime earlier = zone.AtEarlier(localTime);
            ZonedDateTime later = zone.AtLater(localTime);
            Assert.AreEqual(localTime, earlier.LocalDateTime);
            Assert.AreEqual(localTime, later.LocalDateTime);
            Assert.That(earlier.ToInstant(), Is.LessThan(later.ToInstant()));

            try
            {
                zone.AtExactly(localTime);
                Assert.Fail("Expected exception");
            }
            catch (AmbiguousTimeException e)
            {
                Assert.AreEqual(localTime, e.LocalDateTime);
                Assert.AreEqual(zone, e.Zone);
                Assert.AreEqual(earlier, e.EarlierMapping);
                Assert.AreEqual(later, e.LaterMapping);
            }
        }
Esempio n. 9
0
 private static void DumpZone(DateTimeZone zone)
 {
     Console.Write("{0}\r\n", zone.Id);
     var zoneInterval = zone.GetZoneInterval(Start);
     if (!zoneInterval.HasEnd || zoneInterval.End >= End)
     {
         Console.Write("Fixed: {0} {1}\r\n",
             OffsetPattern.Format(zoneInterval.WallOffset),
             zoneInterval.Name);
         return;
     }
     while (zoneInterval.HasEnd && zoneInterval.End < End)
     {
         zoneInterval = zone.GetZoneInterval(zoneInterval.End);
         Console.Write("{0} {1} {2} {3}\r\n",
             InstantPattern.Format(zoneInterval.Start),
             OffsetPattern.Format(zoneInterval.WallOffset),
             zoneInterval.Savings == Offset.Zero ? "standard" : "daylight",
             zoneInterval.Name);
     }
 }
Esempio n. 10
0
 private void DumpZone(DateTimeZone zone, TextWriter writer)
 {
     string lineFormat = options.DisableAbbreviations ? LineFormatWithoutAbbreviations : LineFormatWithAbbreviations;
     writer.Write($"{zone.Id}\n");
     var initial = zone.GetZoneInterval(options.Start);
     writer.Write(lineFormat,
         "Initially:          ",
         OffsetPattern.Format(initial.WallOffset),
         initial.Savings != Offset.Zero ? "daylight" : "standard",
         initial.Name);
     var equalityOptions = options.WallChangeOnly ?
         ZoneEqualityComparer.Options.OnlyMatchWallOffset : ZoneEqualityComparer.Options.StrictestMatch;
     foreach (var zoneInterval in zone.GetZoneIntervals(new Interval(options.Start, options.End), equalityOptions)
         .Where(zi => zi.HasStart && zi.Start >= options.Start))
     {
         writer.Write(lineFormat,
             InstantPattern.Format(zoneInterval.Start),
             OffsetPattern.Format(zoneInterval.WallOffset),
             zoneInterval.Savings != Offset.Zero ? "daylight" : "standard",
             zoneInterval.Name);
     }
     writer.Write("\n");
 }
Esempio n. 11
0
    public DateTime(Context ctx, string time, DateTimeZone timezone)
    {
        Debug.Assert(ctx != null);

        _ctx = ctx;

        if (timezone == null)
        {
            TimeZone = PhpTimeZone.GetCurrentTimeZone(ctx);
        }
        else
        {
            //var datetimezone = timezone as DateTimeZone;
            //if (datetimezone == null)
            //{
            //    PhpException.InvalidArgumentType("timezone", "DateTimeZone");
            //    TimeZone = PhpTimeZone.CurrentTimeZone;
            //}
            //else
            {
                TimeZone = timezone.timezone;
            }
        }

        if (TimeZone == null)
        {
            //PhpException.InvalidArgument("timezone");
            //return null;
            throw new ArgumentException();
        }

        this.Time = StrToTime(time, System_DateTime.UtcNow);

        //this.date.Value = this.Time.ToString("yyyy-mm-dd HH:mm:ss");
        //this.timezone_type.Value = 3;
        //this.timezone.Value = TimeZone.Id;
    }
 private static void AssertOffset(int expectedHours, LocalDateTime localTime, DateTimeZone zone)
 {
     var zoned = zone.MapLocal(localTime).Single();
     int actualHours = zoned.Offset.Milliseconds / NodaConstants.MillisecondsPerHour;
     Assert.AreEqual(expectedHours, actualHours);
 }
Esempio n. 13
0
        public static ZonedDateTime?ParseDateTime(string str, bool nudgeToPast = false, DateTimeZone zone = null)
        {
            if (zone == null)
            {
                zone = DateTimeZone.Utc;
            }

            // Find the current timestamp in the given zone, find the (naive) midnight timestamp, then put that into the same zone (and make it naive again)
            // Should yield a <current *local @ zone* date> 12:00:00 AM.
            var now      = SystemClock.Instance.GetCurrentInstant().InZone(zone).LocalDateTime;
            var midnight = now.Date.AtMidnight();

            // First we try to parse the string as a relative time using the period parser
            var relResult = ParsePeriod(str);

            if (relResult != null)
            {
                // if we can, we just subtract that amount from the
                return(now.InZoneLeniently(zone).Minus(relResult.Value));
            }

            var timePatterns = new[]
            {
                "H:mm",        // 4:30
                "HH:mm",       // 23:30
                "H:mm:ss",     // 4:30:29
                "HH:mm:ss",    // 23:30:29
                "h tt",        // 2 PM
                "htt",         // 2PM
                "h:mm tt",     // 4:30 PM
                "h:mmtt",      // 4:30PM
                "h:mm:ss tt",  // 4:30:29 PM
                "h:mm:sstt",   // 4:30:29PM
                "hh:mm tt",    // 11:30 PM
                "hh:mmtt",     // 11:30PM
                "hh:mm:ss tt", // 11:30:29 PM
                "hh:mm:sstt"   // 11:30:29PM
            };

            var datePatterns = new[]
            {
                "MMM d yyyy",   // Jan 1 2019
                "MMM d, yyyy",  // Jan 1, 2019
                "MMMM d yyyy",  // January 1 2019
                "MMMM d, yyyy", // January 1, 2019
                "yyyy-MM-dd",   // 2019-01-01
                "yyyy MM dd",   // 2019 01 01
                "yyyy/MM/dd",   // 2019/01/01
                "MMM d",        // Jan 1
                "MMMM d",       // January 1
                "MM-dd",        // 01-01
                "MM dd",        // 01 01
                "MM/dd"         // 01-01
            };

            // First, we try all the timestamps that only have a time
            foreach (var timePattern in timePatterns)
            {
                var pat    = LocalDateTimePattern.CreateWithInvariantCulture(timePattern).WithTemplateValue(midnight);
                var result = pat.Parse(str);
                if (result.Success)
                {
                    // If we have a successful match and we need a time in the past, we try to shove a future-time a date before
                    // Example: "4:30 pm" at 3:30 pm likely refers to 4:30 pm the previous day
                    var val = result.Value;

                    // If we need to nudge, we just subtract a day. This only occurs when we're parsing specifically *just time*, so
                    // we know we won't nudge it by more than a day since we use today's midnight timestamp as a date template.

                    // Since this is a naive datetime, this ensures we're actually moving by one calendar day even if
                    // DST changes occur, since they'll be resolved later wrt. the right side of the boundary
                    if (val > now && nudgeToPast)
                    {
                        val = val.PlusDays(-1);
                    }
                    return(val.InZoneLeniently(zone));
                }
            }

            // Then we try specific date+time combinations, both date first and time first, with and without commas
            foreach (var timePattern in timePatterns)
            {
                foreach (var datePattern in datePatterns)
                {
                    foreach (var patternStr in new[]
                    {
                        $"{timePattern}, {datePattern}", $"{datePattern}, {timePattern}",
                        $"{timePattern} {datePattern}", $"{datePattern} {timePattern}"
                    })
                    {
                        var pattern = LocalDateTimePattern.CreateWithInvariantCulture(patternStr).WithTemplateValue(midnight);
                        var res     = pattern.Parse(str);
                        if (res.Success)
                        {
                            return(res.Value.InZoneLeniently(zone));
                        }
                    }
                }
            }

            // Finally, just date patterns, still using midnight as the template
            foreach (var datePattern in datePatterns)
            {
                var pat = LocalDateTimePattern.CreateWithInvariantCulture(datePattern).WithTemplateValue(midnight);
                var res = pat.Parse(str);
                if (res.Success)
                {
                    return(res.Value.InZoneLeniently(zone));
                }
            }

            // Still haven't parsed something, we just give up lmao
            return(null);
        }
Esempio n. 14
0
 /// <summary>
 /// Constructs a <see cref="ZonedClock"/> from a clock (the target of the method),
 /// and a time zone.
 /// </summary>
 /// <param name="clock">Clock to use in the returned object.</param>
 /// <param name="zone">Time zone to use in the returned object.</param>
 /// <returns>A <see cref="ZonedClock"/> with the given clock and time zone, in the ISO calendar system.</returns>
 public static ZonedClock InZone(this IClock clock, DateTimeZone zone) =>
     InZone(clock, zone, CalendarSystem.Iso);
Esempio n. 15
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);
        }
 /// <inheritdoc />
 /// <remarks>
 /// This implementation simply compares the underlying `TimeZoneInfo` values for
 /// reference equality.
 /// </remarks>
 protected override bool EqualsImpl(DateTimeZone zone)
 {
     return ReferenceEquals(OriginalZone, ((BclDateTimeZone) zone).OriginalZone);
 }
Esempio n. 17
0
 public override IEnumerable <Slice> GetHistory(IEnumerable <HistoryRequest> requests, DateTimeZone sliceTimeZone)
 {
     requests = requests.ToList();
     if (requests.Any(r => RegressionSetupHandlerWrapper.Algorithm.UniverseManager.ContainsKey(r.Symbol)))
     {
         throw new Exception("History requests should not be submitted for universe symbols");
     }
     return(base.GetHistory(requests, sliceTimeZone));
 }
Esempio n. 18
0
            public override IEnumerable <Slice> GetHistory(IEnumerable <HistoryRequest> requests, DateTimeZone sliceTimeZone)
            {
                var now = DateTime.UtcNow;

                LastResolutionRequest = requests.First().Resolution;
                var tradeBar1 = new TradeBar(now, underlyingSymbol, 1, 1, 1, 1, 1, TimeSpan.FromDays(1));
                var tradeBar2 = new TradeBar(now, underlyingSymbol2, 3, 3, 3, 3, 3, TimeSpan.FromDays(1));
                var slice1    = new Slice(now, new List <BaseData> {
                    tradeBar1, tradeBar2
                },
                                          new TradeBars(now), new QuoteBars(),
                                          new Ticks(), new OptionChains(),
                                          new FuturesChains(), new Splits(),
                                          new Dividends(now), new Delistings(),
                                          new SymbolChangedEvents());
                var tradeBar1_2 = new TradeBar(now, underlyingSymbol, 2, 2, 2, 2, 2, TimeSpan.FromDays(1));
                var slice2      = new Slice(now, new List <BaseData> {
                    tradeBar1_2
                },
                                            new TradeBars(now), new QuoteBars(),
                                            new Ticks(), new OptionChains(),
                                            new FuturesChains(), new Splits(),
                                            new Dividends(now), new Delistings(),
                                            new SymbolChangedEvents());

                return(new[] { slice1, slice2 });
            }
Esempio n. 19
0
        /// <summary>
        /// Enumerates the subscriptions into slices
        /// </summary>
        protected IEnumerable <Slice> CreateSliceEnumerableFromSubscriptions(List <Subscription> subscriptions, DateTimeZone sliceTimeZone)
        {
            // required by TimeSlice.Create, but we don't need it's behavior
            var cashBook = new CashBook();

            cashBook.Clear();
            var frontier = DateTime.MinValue;

            while (true)
            {
                var earlyBirdTicks = long.MaxValue;
                var data           = new List <DataFeedPacket>();
                foreach (var subscription in subscriptions)
                {
                    if (subscription.EndOfStream)
                    {
                        continue;
                    }

                    var packet = new DataFeedPacket(subscription.Security, subscription.Configuration);

                    while (subscription.Current.EmitTimeUtc <= frontier)
                    {
                        packet.Add(subscription.Current.Data);
                        Interlocked.Increment(ref _dataPointCount);
                        if (!subscription.MoveNext())
                        {
                            break;
                        }
                    }
                    // only add if we have data
                    if (packet.Count != 0)
                    {
                        data.Add(packet);
                    }
                    // udate our early bird ticks (next frontier time)
                    if (subscription.Current != null)
                    {
                        // take the earliest between the next piece of data or the next tz discontinuity
                        earlyBirdTicks = Math.Min(earlyBirdTicks, subscription.Current.EmitTimeUtc.Ticks);
                    }
                }

                // end of subscriptions
                if (earlyBirdTicks == long.MaxValue)
                {
                    break;
                }

                if (data.Count != 0)
                {
                    // reuse the slice construction code from TimeSlice.Create
                    yield return(TimeSlice.Create(frontier, sliceTimeZone, cashBook, data, SecurityChanges.None, new Dictionary <Universe, BaseDataCollection>()).Slice);
                }

                frontier = new DateTime(Math.Max(earlyBirdTicks, frontier.Ticks), DateTimeKind.Utc);
            }

            // make sure we clean up after ourselves
            foreach (var subscription in subscriptions)
            {
                subscription.Dispose();
            }
        }
Esempio n. 20
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);
        }
Esempio n. 21
0
        public IEnumerable <TradeBar> DownloadTradeBars(Symbol symbol, DateTime startTimeUtc, DateTime endTimeUtc, Resolution resolution, DateTimeZone requestedTimeZone)
        {
            string krakenSymbol = SymbolMapper.GetBrokerageSymbol(symbol);

            int interval = ResolutionToInterval(resolution);

            GetOHLCResult result = _restApi.GetOHLC(krakenSymbol, interval, (int)ToUnix(startTimeUtc));

            Dictionary <string, List <OHLC> > dict = result.Pairs;

            List <OHLC> list = dict[krakenSymbol];

            foreach (OHLC candle in list)
            {
                yield return(new TradeBar(DateTimeOffset.FromUnixTimeSeconds(candle.Time).DateTime, symbol, candle.Open, candle.High, candle.Low, candle.Close, candle.Volume, TimeSpan.FromMinutes(interval)));
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Performs a lookup using the specified information and returns the exchange hours if found,
        /// if exchange hours are not found, an exception is thrown
        /// </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="overrideTimeZone">Specify this time zone to override the resolved time zone from the market hours database.
        /// This value will also be used as the time zone for SecurityType.Base with no market hours database entry.
        /// If null is specified, no override will be performed. If null is specified, and it's SecurityType.Base, then Utc will be used.</param>
        /// <returns>The exchange hours for the specified security</returns>
        public SecurityExchangeHours GetExchangeHours(string market, Symbol symbol, SecurityType securityType, DateTimeZone overrideTimeZone = null)
        {
            var stringSymbol = symbol == null ? string.Empty : symbol.Value;

            return(GetEntry(market, stringSymbol, securityType, overrideTimeZone).ExchangeHours);
        }
Esempio n. 23
0
 /// <summary>
 /// Performs a lookup using the specified information and returns the exchange hours if found,
 /// if exchange hours are not found, an exception is thrown
 /// </summary>
 /// <param name="configuration">The subscription data config to get exchange hours for</param>
 /// <param name="overrideTimeZone">Specify this time zone to override the resolved time zone from the market hours database.
 /// This value will also be used as the time zone for SecurityType.Base with no market hours database entry.
 /// If null is specified, no override will be performed. If null is specified, and it's SecurityType.Base, then Utc will be used.</param>
 public SecurityExchangeHours GetExchangeHours(SubscriptionDataConfig configuration, DateTimeZone overrideTimeZone = null)
 {
     // we don't expect base security types to be in the market-hours-database, so set overrideTimeZone
     if (configuration.SecurityType == SecurityType.Base && overrideTimeZone == null)
     {
         overrideTimeZone = configuration.ExchangeTimeZone;
     }
     return(GetExchangeHours(configuration.Market, configuration.Symbol, configuration.SecurityType, overrideTimeZone));
 }
Esempio n. 24
0
            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)));
            }
 private void AssertEqual(DateTimeZone first, DateTimeZone second, 
     Instant start, Instant end, ZoneEqualityComparer.Options options)
 {
     var comparer = ZoneEqualityComparer.ForInterval(new Interval(start, end)).WithOptions(options);
     Assert.IsTrue(comparer.Equals(first, second));
     Assert.AreEqual(comparer.GetHashCode(first), comparer.GetHashCode(second));
 }
Esempio n. 26
0
 public RunningWorkoutBuilder(IEnumerable <Workout> workouts, DateTimeZone zone, Settings.Settings settings)
     : base(workouts, HKConstants.Workouts.Running, ColumnNames.Workout.Running(), zone, settings)
 {
 }
Esempio n. 27
0
    public virtual object setTimeZone(DateTimeZone timezone)
    {
        if (timezone == null)
        {
            //PhpException.ArgumentNull("timezone");
            //return false;
            throw new ArgumentNullException();
        }

        this.TimeZone = timezone.timezone;

        return this;
    }
Esempio n. 28
0
        /// <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 override IEnumerable <Slice> GetHistory(IEnumerable <Data.HistoryRequest> requests, DateTimeZone sliceTimeZone)
        {
            if (string.IsNullOrWhiteSpace(_apiKey))
            {
                Log.Error("IEXDataQueueHandler.GetHistory(): History calls for IEX require an API key.");
                yield break;
            }

            foreach (var request in requests)
            {
                foreach (var slice in ProcessHistoryRequests(request))
                {
                    yield return(slice);
                }
            }
        }
Esempio n. 29
0
 protected override bool EqualsImpl(DateTimeZone zone)
 {
     return TimeZone.Equals(((CachedDateTimeZone) zone).TimeZone);
 }
Esempio n. 30
0
        /// <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 override IEnumerable <Slice> GetHistory(IEnumerable <HistoryRequest> requests, DateTimeZone sliceTimeZone)
        {
            // create subscription objects from the configs
            var subscriptions = new List <Subscription>();

            foreach (var request in requests)
            {
                var subscription = CreateSubscription(request, request.StartTimeUtc, request.EndTimeUtc);
                subscriptions.Add(subscription);
            }

            return(CreateSliceEnumerableFromSubscriptions(subscriptions, sliceTimeZone));
        }
Esempio n. 31
0
 private static void WriteZone(DateTimeZone zone, IDateTimeZoneWriter writer)
 {
     writer.WriteString(zone.Id);
     // For cached zones, simply uncache first.
     var cachedZone = zone as CachedDateTimeZone;
     if (cachedZone != null)
     {
         zone = cachedZone.TimeZone;
     }
     var fixedZone = zone as FixedDateTimeZone;
     if (fixedZone != null)
     {
         writer.WriteByte((byte) DateTimeZoneWriter.DateTimeZoneType.Fixed);
         fixedZone.Write(writer);
     }
     else
     {
         var precalculatedZone = zone as PrecalculatedDateTimeZone;
         if (precalculatedZone != null)
         {
             writer.WriteByte((byte) DateTimeZoneWriter.DateTimeZoneType.Precalculated);
             precalculatedZone.Write(writer);
         }
         else
         {
             throw new ArgumentException("Unserializable DateTimeZone type " + zone.GetType());
         }
     }
 }
        public TaskItemWrapper Map2To1(ITodo source, TaskItemWrapper target, IEntityMappingLogger logger)
        {
            target.Inner.Subject = source.Summary;

            target.Inner.Body = _configuration.MapBody ? source.Description : string.Empty;

            DateTimeZone localZone = DateTimeZoneProviders.Bcl.GetSystemDefault();

            if (source.Start != null)
            {
                if (source.Start.IsUniversalTime)
                {
                    target.Inner.StartDate = Instant.FromDateTimeUtc(source.Start.Value).InZone(localZone).ToDateTimeUnspecified().Date;
                }
                else
                {
                    target.Inner.StartDate = source.Start.Date;
                }
            }

            if (source.Due != null)
            {
                if (source.Start == null || source.Start.Value <= source.Due.Value)
                {
                    if (source.Due.IsUniversalTime)
                    {
                        target.Inner.DueDate = Instant.FromDateTimeUtc(source.Due.Value).InZone(localZone).ToDateTimeUnspecified().Date;
                    }
                    else
                    {
                        target.Inner.DueDate = source.Due.Date;
                    }
                }
            }
            if (source.Completed != null)
            {
                if (source.Completed.IsUniversalTime)
                {
                    target.Inner.DateCompleted = Instant.FromDateTimeUtc(source.Completed.Value).InZone(localZone).ToDateTimeUnspecified().Date;
                }
                else
                {
                    target.Inner.DateCompleted = source.Completed.Date;
                }
                target.Inner.Complete = true;
            }
            else
            {
                target.Inner.Complete = false;
            }

            target.Inner.PercentComplete = source.PercentComplete;

            target.Inner.Status = (target.Inner.Complete && target.Inner.PercentComplete == 100) ? OlTaskStatus.olTaskComplete : MapStatus2To1(source.Status);

            if (_configuration.MapPriority)
            {
                target.Inner.Importance = CommonEntityMapper.MapPriority2To1(source.Priority);
            }

            target.Inner.Sensitivity = CommonEntityMapper.MapPrivacy2To1(source.Class, false, false);

            MapCategories2To1(source, target);

            MapReminder2To1(source, target, logger);

            if (_configuration.MapCustomProperties || _configuration.UserDefinedCustomPropertyMappings.Length > 0)
            {
                using (var userPropertiesWrapper = GenericComObjectWrapper.Create(target.Inner.UserProperties))
                {
                    CommonEntityMapper.MapCustomProperties2To1(source.Properties, userPropertiesWrapper, _configuration.MapCustomProperties, _configuration.UserDefinedCustomPropertyMappings, logger, s_logger);
                }
            }

            if (_configuration.MapRecurringTasks)
            {
                MapRecurrance2To1(source, target, logger);
            }

            return(target);
        }
Esempio n. 33
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;
 }
        /// <summary>
        /// Enumerates the subscriptions into slices
        /// </summary>
        private IEnumerable <Slice> CreateSliceEnumerableFromSubscriptions(List <Subscription> subscriptions, DateTimeZone sliceTimeZone)
        {
            // required by TimeSlice.Create, but we don't need it's behavior
            var cashBook = new CashBook();

            cashBook.Clear();
            var frontier = DateTime.MinValue;

            while (true)
            {
                var earlyBirdTicks = long.MaxValue;
                var data           = new List <DataFeedPacket>();
                foreach (var subscription in subscriptions)
                {
                    if (subscription.EndOfStream)
                    {
                        continue;
                    }

                    var packet = new DataFeedPacket(subscription.Security, subscription.Configuration);

                    var offsetProvider     = subscription.OffsetProvider;
                    var currentOffsetTicks = offsetProvider.GetOffsetTicks(frontier);
                    while (subscription.Current.EndTime.Ticks - currentOffsetTicks <= frontier.Ticks)
                    {
                        // we want bars rounded using their subscription times, we make a clone
                        // so we don't interfere with the enumerator's internal logic
                        var clone = subscription.Current.Clone(subscription.Current.IsFillForward);
                        clone.Time = clone.Time.RoundDown(subscription.Configuration.Increment);
                        packet.Add(clone);
                        Interlocked.Increment(ref _dataPointCount);
                        if (!subscription.MoveNext())
                        {
                            break;
                        }
                    }
                    // only add if we have data
                    if (packet.Count != 0)
                    {
                        data.Add(packet);
                    }
                    // udate our early bird ticks (next frontier time)
                    if (subscription.Current != null)
                    {
                        // take the earliest between the next piece of data or the next tz discontinuity
                        var nextDataOrDiscontinuity = Math.Min(subscription.Current.EndTime.Ticks - currentOffsetTicks, offsetProvider.GetNextDiscontinuity());
                        earlyBirdTicks = Math.Min(earlyBirdTicks, nextDataOrDiscontinuity);
                    }
                }

                // end of subscriptions
                if (earlyBirdTicks == long.MaxValue)
                {
                    break;
                }

                if (data.Count != 0)
                {
                    // reuse the slice construction code from TimeSlice.Create
                    yield return(TimeSlice.Create(frontier, sliceTimeZone, cashBook, data, SecurityChanges.None).Slice);
                }

                frontier = new DateTime(Math.Max(earlyBirdTicks, frontier.Ticks), DateTimeKind.Utc);
            }

            // make sure we clean up after ourselves
            foreach (var subscription in subscriptions)
            {
                subscription.Dispose();
            }
        }
Esempio n. 35
0
 /// <summary>
 /// Constructs a <see cref="ZonedClock"/> from a clock (the target of the method),
 /// a time zone, and a calendar system.
 /// </summary>
 /// <param name="clock">Clock to use in the returned object.</param>
 /// <param name="zone">Time zone to use in the returned object.</param>
 /// <param name="calendar">Calendar to use in the returned object.</param>
 /// <returns>A <see cref="ZonedClock"/> with the given clock, time zone and calendar system.</returns>
 public static ZonedClock InZone(this IClock clock, DateTimeZone zone, CalendarSystem calendar) =>
     new ZonedClock(clock, zone, calendar);
 public TimeZoneNotifyService(RaidBattlesContext db, IDateTimeZoneProvider dateTimeZoneProvider, DateTimeZone dateTimeZone, IClock clock, ITelegramBotClient bot)
 {
     myDB = db;
     myDateTimeZoneProvider = dateTimeZoneProvider;
     myDateTimeZone         = dateTimeZone;
     myClock = clock;
     myBot   = bot;
 }
Esempio n. 37
0
		public DateEdit (System.DateTime time, DateEditFlags flags)
		{
			datetime = new DateTimeZone (time);
			datetime.Changed += HandleDateTimeZoneChanged;
			this.flags = flags;

			date_entry = new Gtk.Entry ();
			date_entry.WidthChars = 10;
			date_entry.Changed += HandleDateEntryChanged;
			PackStart (date_entry, true, true, 0);
		
			Gtk.HBox b_box = new Gtk.HBox ();
			b_box.PackStart (new Gtk.Label (Catalog.GetString ("Calendar")), true, true, 0);
			b_box.PackStart (new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out), true, false, 0);
			date_button = new Gtk.Button (b_box);
			date_button.Clicked += HandleCalendarButtonClicked;
			PackStart (date_button, false, false, 0);

			calendar = new Gtk.Calendar ();
			calendar.DaySelected += HandleCalendarDaySelected;
			Gtk.Frame frame = new Gtk.Frame ();
			frame.Add (calendar);
			cal_popup = new Gtk.Window (Gtk.WindowType.Popup);
			cal_popup.DestroyWithParent = true;
			cal_popup.Add (frame);
			cal_popup.Shown += HandleCalendarPopupShown;
			cal_popup.GrabNotify += HandlePopupGrabNotify;
			frame.Show ();
			calendar.Show ();

			time_entry = new Gtk.Entry ();
			time_entry.WidthChars = 8;
			time_entry.Changed += HandleTimeEntryChanged;
			PackStart (time_entry, true, true, 0);

			Gtk.CellRendererText timecell = new Gtk.CellRendererText ();
			time_combo = new Gtk.ComboBox ();
			time_store = new Gtk.TreeStore (typeof (string), typeof (int), typeof (int)); 
			time_combo.Model = time_store;
			time_combo.PackStart (timecell, true);
			time_combo.SetCellDataFunc (timecell, new CellLayoutDataFunc (TimeCellFunc));
			time_combo.Realized += FillTimeCombo;
			time_combo.Changed += HandleTimeComboChanged;
			PackStart (time_combo, false, false, 0);

			zone_entry = new Gtk.Entry ();
			zone_entry.IsEditable = false;
			zone_entry.MaxLength = 6;
			zone_entry.WidthChars = 6;
			PackStart (zone_entry, true, true, 0);

			Gtk.CellRendererText offsetcell = new Gtk.CellRendererText ();
			offset_combo = new Gtk.ComboBox ();
			offset_combo.Model = new Gtk.TreeStore (typeof (string), typeof (int));
			offset_combo.PackStart (offsetcell, true);
			offset_combo.SetCellDataFunc (offsetcell, new CellLayoutDataFunc (OffsetCellFunc));
			FillOffsetCombo ();
			offset_combo.Changed += HandleOffsetComboChanged;
			PackStart (offset_combo, false, false, 0);

			Update ();
			ShowAll ();
		}
Esempio n. 38
0
            public override IEnumerable <Slice> GetHistory(IEnumerable <HistoryRequest> requests, DateTimeZone sliceTimeZone)
            {
                foreach (var request in requests)
                {
                    HistryRequests.Add(request);
                }

                var startTime = requests.Min(x => x.StartTimeUtc.ConvertFromUtc(x.DataTimeZone));
                var endTime   = requests.Max(x => x.EndTimeUtc.ConvertFromUtc(x.DataTimeZone));

                return(Slices.Where(x => x.Time >= startTime && x.Time <= endTime).ToList());
            }
Esempio n. 39
0
 public void TestTimeZone(DateTimeZone expected)
 {
     Reset();
     Writer.WriteTimeZone(expected);
     var actual = Reader.ReadTimeZone(expected.Id);
     Assert.AreEqual(expected, actual, name + " IDateTimeZone ");
 }
Esempio n. 40
0
 public static string FormatZoned(this Instant i, DateTimeZone zone) => i.InZone(zone).FormatZoned();
 /// <inheritdoc />
 protected override bool EqualsImpl(DateTimeZone zone)
 {
     SingleTransitionDateTimeZone otherZone = (SingleTransitionDateTimeZone)zone;
     return Id == otherZone.Id && EarlyInterval.Equals(otherZone.EarlyInterval) && LateInterval.Equals(otherZone.LateInterval);
 }
Esempio n. 42
0
 /// <summary>
 /// Downloads a list of QuoteBars at the requested resolution
 /// </summary>
 /// <param name="symbol">The symbol</param>
 /// <param name="startTimeUtc">The starting time (UTC)</param>
 /// <param name="endTimeUtc">The ending time (UTC)</param>
 /// <param name="resolution">The requested resolution</param>
 /// <param name="requestedTimeZone">The requested timezone for the data</param>
 /// <returns>The list of bars</returns>
 public abstract IEnumerable <QuoteBar> DownloadQuoteBars(Symbol symbol, DateTime startTimeUtc, DateTime endTimeUtc, Resolution resolution, DateTimeZone requestedTimeZone);
 private void AssertNotEqual(DateTimeZone first, DateTimeZone second, 
     Instant start, Instant end, ZoneEqualityComparer.Options options)
 {
     var comparer = ZoneEqualityComparer.ForInterval(new Interval(start, end)).WithOptions(options);
     Assert.IsFalse(comparer.Equals(first, second));
     // If this fails, the code *could* still be correct - but it's unlikely...
     Assert.AreNotEqual(comparer.GetHashCode(first), comparer.GetHashCode(second));
 }
Esempio n. 44
0
 [return: CastToFalse]
 public static object DateCreate(ScriptContext/*!*/context, string time, DateTimeZone timezone)
 {
     var dt = new __PHP__DateTime(context, true);
     dt.__construct(context, time, timezone);
     return dt;
Esempio n. 45
0
    public static object createFromFormat(Context ctx, string format, string time, DateTimeZone timezone = null)
    {
        // arguments
        var tz = (timezone != null) ? timezone.timezone : PhpTimeZone.GetCurrentTimeZone(ctx);

        if (format == null)
        {
            //PhpException.InvalidArgument("format");
            //return false;
            throw new ArgumentNullException();
        }

        if (time == null)
        {
            //PhpException.InvalidArgument("time");
            //return false;
            throw new ArgumentNullException();
        }

        // create DateTime from format+time
        int i = 0;  // position in <timestr>
        foreach (var c in format)
        {
            switch (c)
            {
                //case 'd':
                //case 'j':
                //    var day = PHP.Library.StrToTime.DateInfo.ParseUnsignedInt(timestr, ref i, 2);
                //    // ... use day
                //    break;
                //case 'F':
                //case 'M':
                //    // parse  ...
                //    break;
                default:
                    if (i < time.Length && time[i] == c)
                    {
                        // match
                        i++;
                    }
                    else
                    {
                        // not match
                        //PhpException.InvalidArgument("time");   // time not matching format
                        //return false;
                        throw new ArgumentException();
                    }
                    break;
            }
        }

        if (i < time.Length)
        {
            //PhpException.InvalidArgument("time");   // time not matching format
            //return false;
            throw new ArgumentException();
        }

        ////
        //return new __PHP__DateTime(context, true)
        //{
        //     //Time = new DateTime(year, month, day, hour, minute, second, millisecond),
        //     TimeZone = tz,
        //};

        throw new NotImplementedException();
    }
Esempio n. 46
0
 private static PrecalculatedDateTimeZone CreatePrecalculatedDateTimeZone(string id, IList<ZoneTransition> transitions,
     Instant tailZoneStart, DateTimeZone tailZone)
 {
     // Convert the transitions to intervals
     int size = transitions.Count;
     var intervals = new ZoneInterval[size];
     for (int i = 0; i < size; i++)
     {
         var transition = transitions[i];
         var endInstant = i == size - 1 ? tailZoneStart : transitions[i + 1].Instant;
         intervals[i] = new ZoneInterval(transition.Name, transition.Instant, endInstant, transition.WallOffset, transition.Savings);
     }
     return new PrecalculatedDateTimeZone(id, intervals, tailZone);
 }
Esempio n. 47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedDateTimeZone"/> class.
 /// </summary>
 /// <param name="timeZone">The time zone to cache.</param>
 /// <param name="map">The caching map</param>
 private CachedDateTimeZone(DateTimeZone timeZone, IZoneIntervalMap map) : base(timeZone.Id, false, timeZone.MinOffset, timeZone.MaxOffset)
 {
     this.TimeZone = timeZone;
     this.map = map;
 }
Esempio n. 48
0
 public static LocalDate ToLocalDate(this Instant instant, DateTimeZone zone)
 {
     return(instant.InZone(zone).Date);
 }
Esempio n. 49
0
        private void ValidateZoneEquality(Instant instant, DateTimeZone nodaZone, TimeZoneInfo windowsZone)
        {
            // The BCL is basically broken (up to and including .NET 4.5.1 at least) around its interpretation
            // of its own data around the new year. See http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/
            // for details. We're not trying to emulate this behaviour.
            // It's a lot *better* for .NET 4.6, 
            var utc = instant.InUtc();
            if ((utc.Month == 12 && utc.Day == 31) || (utc.Month == 1 && utc.Day == 1))
            {
                return;
            }

            var interval = nodaZone.GetZoneInterval(instant);

            // Check that the zone interval really represents a transition. It could be a change in
            // wall offset, name, or the split between standard time and daylight savings for the interval.
            if (interval.RawStart != Instant.BeforeMinValue)
            {
                var previousInterval = nodaZone.GetZoneInterval(interval.Start - Duration.Epsilon);
                Assert.AreNotEqual(new {interval.WallOffset, interval.Name, interval.StandardOffset},
                    new {previousInterval.WallOffset, previousInterval.Name, previousInterval.StandardOffset},
                    "Non-transition from {0} to {1}", previousInterval, interval);
            }
            var nodaOffset = interval.WallOffset;
            var windowsOffset = windowsZone.GetUtcOffset(instant.ToDateTimeUtc());
            Assert.AreEqual(windowsOffset, nodaOffset.ToTimeSpan(), $"Incorrect offset at {instant} in interval {interval}");
            var bclDaylight = windowsZone.IsDaylightSavingTime(instant.ToDateTimeUtc());
            Assert.AreEqual(bclDaylight, interval.Savings != Offset.Zero,
                $"At {instant}, BCL IsDaylightSavingTime={bclDaylight}; Noda savings={interval.Savings}");
        }
Esempio n. 50
0
 public CalendarService(ISessionRepository sessionRepository, string timezone)
 {
     _sessionRepository = sessionRepository;
     _timezone          = DateTimeZoneProviders.Tzdb[timezone];
 }
Esempio n. 51
0
 protected override bool EqualsImpl(DateTimeZone other) =>
     Offset == ((FixedDateTimeZone)other).Offset &&
     Id == other.Id && 
     ((FixedDateTimeZone)other).Name == Name;
Esempio n. 52
0
 public PlayWorkoutBuilder(IEnumerable <Workout> workouts, DateTimeZone zone, Settings.Settings settings)
     : base(workouts, HKConstants.Workouts.Play, ColumnNames.Workout.Play(), zone, settings)
 {
 }
Esempio n. 53
0
 public static Instant GetMonthStartInstant(this LocalDate localDate, DateTimeZone timeZone)
 {
     return(timeZone.AtStartOfDay(new LocalDate(localDate.Year, localDate.Month, 1)).ToInstant());
 }
 // Reasonably simple way of computing the maximum/minimum offset
 // from either periods or transitions, with or without a tail zone.
 private static Offset ComputeOffset([NotNull] ZoneInterval[] intervals,
     DateTimeZone tailZone,
     OffsetAggregator aggregator)
 {
     Preconditions.CheckNotNull(intervals, nameof(intervals));
     Preconditions.CheckArgument(intervals.Length > 0, nameof(intervals), "No intervals specified");
     Offset ret = intervals[0].WallOffset;
     for (int i = 1; i < intervals.Length; i++)
     {
         ret = aggregator(ret, intervals[i].WallOffset);
     }
     if (tailZone != null)
     {
         // Effectively a shortcut for picking either tailZone.MinOffset or
         // tailZone.MaxOffset
         Offset bestFromZone = aggregator(tailZone.MinOffset, tailZone.MaxOffset);
         ret = aggregator(ret, bestFromZone);
     }
     return ret;
 }
        public virtual IEnumerable <LocalInterval> GetIntervals(LocalInterval interval, DateTimeZone destinationTimezone)
        {
            var maskIntervals    = mask.GetIntervals(interval, destinationTimezone);
            var contentIntervals = payload.GetIntervals(interval, destinationTimezone);

            return(TimeMathOld.Intersection(contentIntervals, maskIntervals).OrderBy(i => i.Start));
        }
Esempio n. 56
0
        /// <summary>
        /// Gets the entry for the specified market/symbol/security-type
        /// </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="overrideTimeZone">Specify this time zone to override the resolved time zone from the market hours database.
        /// This value will also be used as the time zone for SecurityType.Base with no market hours database entry.
        /// If null is specified, no override will be performed. If null is specified, and it's SecurityType.Base, then Utc will be used.</param>
        /// <returns>The entry matching the specified market/symbol/security-type</returns>
        public virtual Entry GetEntry(string market, string symbol, SecurityType securityType, DateTimeZone overrideTimeZone = null)
        {
            Entry entry;
            var   key = new SecurityDatabaseKey(market, symbol, securityType);

            if (!_entries.TryGetValue(key, out entry))
            {
                // now check with null symbol key
                if (!_entries.TryGetValue(new SecurityDatabaseKey(market, null, securityType), out entry))
                {
                    if (securityType == SecurityType.Base)
                    {
                        if (overrideTimeZone == null)
                        {
                            overrideTimeZone = TimeZones.Utc;
                            Log.Error("MarketHoursDatabase.GetExchangeHours(): Custom data no time zone specified, default to UTC. " + key);
                        }
                        // base securities are always open by default and have equal data time zone and exchange time zones
                        return(new Entry(overrideTimeZone, SecurityExchangeHours.AlwaysOpen(overrideTimeZone)));
                    }

                    Log.Error(string.Format("MarketHoursDatabase.GetExchangeHours(): Unable to locate exchange hours for {0}." + "Available keys: {1}", key, string.Join(", ", _entries.Keys)));

                    // there was nothing that really matched exactly... what should we do here?
                    throw new ArgumentException("Unable to locate exchange hours for " + key);
                }

                // perform time zone override if requested, we'll use the same exact local hours
                // and holidays, but we'll express them in a different time zone
                if (overrideTimeZone != null && !entry.ExchangeHours.TimeZone.Equals(overrideTimeZone))
                {
                    return(new Entry(overrideTimeZone, new SecurityExchangeHours(overrideTimeZone, entry.ExchangeHours.Holidays, entry.ExchangeHours.MarketHours)));
                }
            }

            return(entry);
        }
Esempio n. 57
0
 [return:CastToFalse]
 public static __PHP__DateTime DateCreateFromFormat(ScriptContext/*!*/context, string format, string time, DateTimeZone timezone)
 {
     return __PHP__DateTime.createFromFormat(context, format, time, timezone) as __PHP__DateTime;
Esempio n. 58
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);

                var currentExchangeTimeEod = currentInTimeZoneEod.ConvertTo(timeZone, exchange.TimeZone);

                // don't pass the end
                if (currentExchangeTimeEod > thru)
                {
                    currentExchangeTimeEod = thru;
                }

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

                currentExchangeTime = currentExchangeTimeEod;
            }
        }
        protected override bool EqualsImpl(DateTimeZone zone)
        {
            PrecalculatedDateTimeZone otherZone = (PrecalculatedDateTimeZone)zone;

            // Check the individual fields first...
            if (Id != otherZone.Id ||
                !Equals(tailZone, otherZone.tailZone) ||
                tailZoneStart != otherZone.tailZoneStart ||
                !Equals(firstTailZoneInterval, otherZone.firstTailZoneInterval))
            {
                return false;
            }

            // Now all the intervals
            if (periods.Length != otherZone.periods.Length)
            {
                return false;
            }
            for (int i = 0; i < periods.Length; i++)
            {
                if (!periods[i].Equals(otherZone.periods[i]))
                {
                    return false;
                }
            }
            return true;                        
        }
Esempio n. 60
0
        /// <summary>
        /// Determines the start time required to produce the requested number of bars and the given size
        /// </summary>
        /// <param name="exchangeHours">The exchange hours 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>
        /// <param name="dataTimeZone">Timezone for this data</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 exchangeHours, DateTime end, TimeSpan barSize, int barCount, bool extendedMarketHours, DateTimeZone dataTimeZone)
        {
            if (barSize <= TimeSpan.Zero)
            {
                throw new ArgumentException("barSize must be greater than TimeSpan.Zero", nameof(barSize));
            }

            // need to round down in data timezone because data is stored in this time zone
            var current = end.RoundDownInTimeZone(barSize, exchangeHours.TimeZone, dataTimeZone);

            for (int i = 0; i < barCount;)
            {
                var previous = current;
                current = current - barSize;
                if (exchangeHours.IsOpen(current, previous, extendedMarketHours))
                {
                    i++;
                }
            }
            return(current);
        }