Ejemplo n.º 1
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(((TimeZone?.GetHashCode() ?? 0) * 397) ^ UtcTime.GetHashCode());
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// 将linux时间戳转为DateTime
        /// </summary>
        /// <param name="time">时间戳</param>
        /// <returns>DateTime</returns>
        public static DateTime ToDateTime(int time)
        {
            var datetStart = UtcTime.ToLocalTime();
            var toNow      = new TimeSpan(long.Parse(time + "0000000"));

            return(datetStart.Add(toNow));
        }
Ejemplo n.º 3
0
        private Insight SetGeneratedAndClosedTimes(Insight insight)
        {
            insight.GeneratedTimeUtc = UtcTime;
            insight.ReferenceValue   = _securityValuesProvider.GetValues(insight.Symbol).Get(insight.Type);
            if (string.IsNullOrEmpty(insight.SourceModel))
            {
                // set the source model name if not already set
                insight.SourceModel = Alpha.GetModelName();
            }

            TimeSpan barSize;
            Security security;
            SecurityExchangeHours exchangeHours;

            if (Securities.TryGetValue(insight.Symbol, out security))
            {
                exchangeHours = security.Exchange.Hours;
                barSize       = security.Resolution.ToTimeSpan();
            }
            else
            {
                barSize       = insight.Period.ToHigherResolutionEquivalent(false).ToTimeSpan();
                exchangeHours = MarketHoursDatabase.GetExchangeHours(insight.Symbol.ID.Market, insight.Symbol, insight.Symbol.SecurityType);
            }

            var localStart = UtcTime.ConvertFromUtc(exchangeHours.TimeZone);

            barSize = QuantConnect.Time.Max(barSize, QuantConnect.Time.OneMinute);
            var barCount = (int)(insight.Period.Ticks / barSize.Ticks);

            insight.CloseTimeUtc = QuantConnect.Time.GetEndTimeForTradeBars(exchangeHours, localStart, barSize, barCount, false).ConvertToUtc(exchangeHours.TimeZone);

            return(insight);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets the historical data for the specified symbols. The exact number of bars will be returned for
        /// each symbol. This may result in some data start earlier/later than others due to when various
        /// exchanges are open. The symbols must exist in the Securities collection.
        /// </summary>
        /// <param name="type">The data type of the symbols</param>
        /// <param name="tickers">The symbols to retrieve historical data for</param>
        /// <param name="periods">The number of bars to request</param>
        /// <param name="resolution">The resolution to request</param>
        /// <returns>pandas.DataFrame containing the requested historical data</returns>
        public PyObject History(PyObject type, PyObject tickers, int periods, Resolution?resolution = null)
        {
            var symbols = GetSymbolsFromPyObject(tickers);

            if (symbols == null)
            {
                return(null);
            }

            var requests = symbols.Select(x =>
            {
                var security = Securities[x];
                var config   = security.Subscriptions.OrderByDescending(s => s.Resolution)
                               .FirstOrDefault(s => s.Type.BaseType == CreateType(type).BaseType);
                if (config == null)
                {
                    return(null);
                }

                Resolution?res = resolution ?? security.Resolution;
                var start      = GetStartTimeAlgoTz(x, periods, resolution).ConvertToUtc(TimeZone);
                return(CreateHistoryRequest(config, start, UtcTime.RoundDown(res.Value.ToTimeSpan()), resolution));
            });

            return(PandasConverter.GetDataFrame(History(requests.Where(x => x != null)).Memoize()));
        }
Ejemplo n.º 5
0
        private Alpha SetGeneratedAndClosedTimes(Alpha alpha)
        {
            alpha.GeneratedTimeUtc = UtcTime;

            TimeSpan barSize;
            Security security;
            SecurityExchangeHours exchangeHours;

            if (Securities.TryGetValue(alpha.Symbol, out security))
            {
                exchangeHours = security.Exchange.Hours;
                barSize       = security.Resolution.ToTimeSpan();
            }
            else
            {
                barSize       = alpha.Period.ToHigherResolutionEquivalent(false).ToTimeSpan();
                exchangeHours = MarketHoursDatabase.GetExchangeHours(alpha.Symbol.ID.Market, alpha.Symbol, alpha.Symbol.SecurityType);
            }

            var localStart = UtcTime.ConvertFromUtc(exchangeHours.TimeZone);

            barSize = QuantConnect.Time.Max(barSize, QuantConnect.Time.OneMinute);
            var barCount = (int)(alpha.Period.Ticks / barSize.Ticks);

            alpha.CloseTimeUtc = QuantConnect.Time.GetEndTimeForTradeBars(exchangeHours, localStart, barSize, barCount, false).ConvertToUtc(exchangeHours.TimeZone);

            return(alpha);
        }
        public void CorrectTimeToSecond_RightSecondsExpected(UtcTime utcTime, string expectedSeconds)
        {
            _mockDateTimeParser.Setup(p => p.ParseDateTime(It.IsAny <string>())).Returns(utcTime);
            var converter = GetDateTimeConverter();

            Assert.AreEqual(expectedSeconds, converter.ConvertToSeconds("stub_dateTime"));
        }
Ejemplo n.º 7
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(((TimeZone != null ? TimeZone.GetHashCode() : 0) * 397) ^ UtcTime.GetHashCode());
     }
 }
Ejemplo n.º 8
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(UtcTime.GetHashCode() * 397 + TimeZoneOffset.GetHashCode());
     }
 }
Ejemplo n.º 9
0
 public int CompareTo(ApiDateTime other)
 {
     if (other == null)
     {
         return(1);
     }
     return(UtcTime.CompareTo(other.UtcTime));
 }
Ejemplo n.º 10
0
        public override string ToString()
        {
            DateTime localUtcTime = UtcTime;

            if (!UtcTime.Equals(DateTime.MinValue))
                localUtcTime = UtcTime.Add(TimeZoneOffset);

            return ToRoundTripString(localUtcTime, TimeZoneOffset);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Helper methods to create a history request for the specified symbols and bar count
 /// </summary>
 private IEnumerable <HistoryRequest> CreateBarCountHistoryRequests(IEnumerable <Symbol> symbols, int periods, Resolution?resolution = null)
 {
     return(symbols.Select(x =>
     {
         var security = Securities[x];
         Resolution?res = resolution ?? security.Resolution;
         var start = GetStartTimeAlgoTz(x, periods, res).ConvertToUtc(security.Exchange.TimeZone);
         return CreateHistoryRequest(security, start, UtcTime.RoundDown(res.Value.ToTimeSpan()), resolution);
     }));
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Determines if the exchange for the specified symbol is open at the current time.
        /// </summary>
        /// <param name="symbol">The symbol</param>
        /// <returns>True if the exchange is considered open at the current time, false otherwise</returns>
        public bool IsMarketOpen(Symbol symbol)
        {
            var exchangeHours = MarketHoursDatabase
                .FromDataFolder()
                .GetExchangeHours(symbol.ID.Market, symbol, symbol.SecurityType);

            var time = UtcTime.ConvertFromUtc(exchangeHours.TimeZone);

            return exchangeHours.IsOpen(time, false);
        }
Ejemplo n.º 13
0
        public IEnumerable <DateTime> GetMatches(DateTime?lastMachingTime)
        {
            if (lastMachingTime.HasValue && lastMachingTime.Value.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", "lastMachingTime");
            }

            var baseTime = lastMachingTime ?? UtcTime.AddSeconds(-1);
            var endTime  = UtcTime.AddSeconds(1);

            return(_schedule.GetNextOccurrences(baseTime, endTime));
        }
Ejemplo n.º 14
0
 public bool Equals(ApiDateTime other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(UtcTime.Equals(other.UtcTime) && TimeZoneOffset.Equals(other.TimeZoneOffset));
 }
Ejemplo n.º 15
0
        private void Convert(object obj)
        {
            double numValue;

            if (!double.TryParse(obj.ToString(), out numValue))
            {
                MessageBox.Show("Invalid number!");
            }

            UtcTime    = UnixTimeStampToDateTime(numValue);
            LocalTime  = UtcTime.ToLocalTime();
            TimePassed = (DateTime.UtcNow - UtcTime).Humanize(4);
        }
        /// <summary>
        /// 创建数据库元数据信息
        /// </summary>
        /// <param name="dataSourceMap"></param>
        /// <param name="databaseType"></param>
        /// <returns></returns>
        private ShardingConnectorMetaData CreateMetaData(IDictionary <string, IDataSource> dataSourceMap,
                                                         IDatabaseType databaseType)
        {
            long            start           = UtcTime.CurrentTimeMillis();
            DataSourceMetas dataSourceMetas =
                new DataSourceMetas(databaseType, GetDatabaseAccessConfigurationMap(dataSourceMap));
            SchemaMetaData            schemaMetaData = LoadSchemaMetaData(dataSourceMap);
            ShardingConnectorMetaData result         = new ShardingConnectorMetaData(dataSourceMetas, schemaMetaData);
            var costMillis = UtcTime.CurrentTimeMillis() - start;

            _logger.LogInformation($"Meta data load finished, cost {costMillis} milliseconds.");
            return(result);
        }
Ejemplo n.º 17
0
        public override int GetHashCode()
        {
            var hashCode = 2007374510;

            hashCode = hashCode * -1521134295 + UtcTime.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Room);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Name);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Content);

            return(hashCode);
        }
Ejemplo n.º 18
0
        public override async Task Execute(Message message, ITelegramBotClient botClient, BotContext context)
        {
            db = context;
            var chatId = message.Chat.Id;

            if (db.UtcTimes.FirstOrDefault(x => x.ChatId == chatId) == null)
            {
                State NewState = new State();
                NewState.ChatId = Convert.ToInt32(chatId);
                NewState.States = "Utc";
                db.States.Add(NewState);
                UtcTime NewUser = new UtcTime();
                NewUser.ChatId  = Convert.ToInt32(chatId);
                NewUser.UtcZone = null;
                db.UtcTimes.Add(NewUser);
                db.SaveChanges();
                await botClient.SendTextMessageAsync(chatId,
                                                     "Привет! Вижу ты новый пользователь. Для дальнейшей работы тебе нужно ввести UTC(Всемирное " +
                                                     "координированное время) твоего региона. " +
                                                     "\n\nСейчас в UTC 0 = " +
                                                     DateTime.UtcNow.Hour + ":" + DateTime.UtcNow.Minute +
                                                     "!!!! \n\nПример если UTC 0 = 12:41, а твое время составляет " +
                                                     "14:41 введи '+2', а если 7:41 введи '-3'",
                                                     parseMode : ParseMode.Html, false, false, 0);
            }
            else
            {
                var keyBoard = new ReplyKeyboardMarkup
                {
                    Keyboard = new[]
                    {
                        new[]
                        {
                            new KeyboardButton("\U0001F50D Открыть лист напоминаний")
                        }
                    }
                };
                keyBoard.ResizeKeyboard = true;

                db.States.FirstOrDefault(x => x.ChatId == chatId).States = "Add";
                db.SaveChanges();

                await botClient.SendTextMessageAsync(chatId, "\U0001F64CСейчас вы можете добавлять напоминания.\U0001F64C\n" +
                                                     "Примеры добавления:\n" +
                                                     "\U00002705'Набрать маме через 10 минут'\U00002705\n" +
                                                     "\U00002705'Поздравить Анатолия с Днём рождения 26 января'\U00002705\n" +
                                                     "\U00002705'Успеть купить продукты завтра вечером'\U00002705",
                                                     parseMode : ParseMode.Html, false, false, 0, keyBoard);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Gets the history requests required for provide warm up data for the algorithm
        /// </summary>
        /// <returns></returns>
        public IEnumerable <HistoryRequest> GetWarmupHistoryRequests()
        {
            if (_warmupBarCount.HasValue)
            {
                return(CreateBarCountHistoryRequests(Securities.Keys, _warmupBarCount.Value, _warmupResolution));
            }
            if (_warmupTimeSpan.HasValue)
            {
                var end = UtcTime.ConvertFromUtc(TimeZone);
                return(CreateDateRangeHistoryRequests(Securities.Keys, end - _warmupTimeSpan.Value, end, _warmupResolution));
            }

            // if not warmup requested return nothing
            return(Enumerable.Empty <HistoryRequest>());
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Compares the CalendarTime.
        /// </summary>
        /// <since_tizen> 4 </since_tizen>
        /// <param name="other">The CalendarTime to be compared.</param>
        /// <returns>
        /// A 32-bit signed integer that indicates the relative order of the objects being compared.
        /// </returns>
        public int CompareTo(CalendarTime other)
        {
            if (_type != other._type)
            {
                Log.Error(Globals.LogTag, "Not to compare with different type");
                throw CalendarErrorFactory.GetException((int)CalendarError.InvalidParameter);
            }

            if (_type == (int)Type.Utc)
            {
                return(UtcTime.CompareTo(other.UtcTime));
            }
            else
            {
                return(LocalTime.CompareTo(other.LocalTime));
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Gets the historical data for the specified symbols. The exact number of bars will be returned for
        /// each symbol. This may result in some data start earlier/later than others due to when various
        /// exchanges are open. The symbols must exist in the Securities collection.
        /// </summary>
        /// <typeparam name="T">The data type of the symbols</typeparam>
        /// <param name="symbols">The symbols to retrieve historical data for</param>
        /// <param name="periods">The number of bars to request</param>
        /// <param name="resolution">The resolution to request</param>
        /// <returns>An enumerable of slice containing the requested historical data</returns>
        public IEnumerable <DataDictionary <T> > History <T>(IEnumerable <Symbol> symbols, int periods, Resolution?resolution = null)
            where T : IBaseData
        {
            var requests = symbols.Select(x =>
            {
                var config = GetMatchingSubscription(x, typeof(T));
                if (config == null)
                {
                    return(null);
                }

                var res   = GetResolution(x, resolution);
                var start = GetStartTimeAlgoTz(x, periods, res).ConvertToUtc(TimeZone);
                return(CreateHistoryRequest(config, start, UtcTime.RoundDown(res.Value.ToTimeSpan()), res));
            });

            return(History(requests.Where(x => x != null)).Get <T>().Memoize());
        }
        public static bool TryParse(Queue <Token> unProcessedTokens, out AbstractTime time)
        {
            string timeExpressionRegex = String.Format(@"^(({0})|({1})|({1}:{2})|({1}:{2}:{3})){4}?$", zeroRegex,
                                                       hoursRegex, minutesRegex, secondsRegex, timeTypeRegex);

            if (Regex.IsMatch(unProcessedTokens.Peek().Value, timeExpressionRegex))
            {
                string timeString = unProcessedTokens.Dequeue().Value;
                try
                {
                    if (timeString.EndsWith("w"))
                    {
                        timeString = timeString.TrimEnd('w');
                        time       = new LocalTime(ParseTimeString(timeString));
                        return(true);
                    }
                    if (timeString.EndsWith("s"))
                    {
                        timeString = timeString.TrimEnd('s');
                        time       = new StandardTime(ParseTimeString(timeString));
                        return(true);
                    }
                    if (timeString.EndsWith("u") || timeString.EndsWith("g") ||
                        timeString.EndsWith("z"))
                    {
                        timeString = timeString.TrimEnd('u', 'g', 'z');
                        time       = new UtcTime(ParseTimeString(timeString));
                        return(true);
                    }

                    // default is local time
                    time = new LocalTime(ParseTimeString(timeString));
                    return(true);
                }

                catch (Exception e)
                {
                    string msg = String.Format("Unable to parse {0}: {1}", typeof(TzDbTimeExpression).Name, timeString);
                    throw new Exception(msg, e);
                }
            }
            time = null;
            return(false);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Equals the CalendarTime.
        /// </summary>
        /// <since_tizen> 4 </since_tizen>
        /// <param name="obj">The CalendarTime to be compared.</param>
        /// <returns>
        /// A 32-bit signed integer that indicates the relative order of the objects being compared.
        /// </returns>
        public override bool Equals(object obj)
        {
            var other = obj as CalendarTime;

            if (_type != other._type)
            {
                Log.Error(Globals.LogTag, "Not to compare with different type");
                return(false);
            }

            if (_type == (int)Type.Utc)
            {
                return(UtcTime.Equals(other.UtcTime));
            }
            else
            {
                return(LocalTime.Equals(other.LocalTime));
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets the historical data for the specified symbols. The exact number of bars will be returned for
        /// each symbol. This may result in some data start earlier/later than others due to when various
        /// exchanges are open. The symbols must exist in the Securities collection.
        /// </summary>
        /// <typeparam name="T">The data type of the symbols</typeparam>
        /// <param name="symbols">The symbols to retrieve historical data for</param>
        /// <param name="periods">The number of bars to request</param>
        /// <param name="resolution">The resolution to request</param>
        /// <returns>An enumerable of slice containing the requested historical data</returns>
        public IEnumerable <DataDictionary <T> > History <T>(IEnumerable <Symbol> symbols, int periods, Resolution?resolution = null)
            where T : BaseData
        {
            var requests = symbols.Select(x =>
            {
                var security = Securities[x];
                // don't make requests for symbols of the wrong type
                if (!typeof(T).IsAssignableFrom(security.SubscriptionDataConfig.Type))
                {
                    return(null);
                }

                Resolution?res = resolution ?? security.Resolution;
                var start      = GetStartTimeAlgoTz(x, periods, resolution).ConvertToUtc(TimeZone);
                return(CreateHistoryRequest(security, start, UtcTime.RoundDown(res.Value.ToTimeSpan()), resolution));
            });

            return(History(requests.Where(x => x != null)).Get <T>());
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets the start time required for the specified bar count for a security in terms of the algorithm's time zone
        /// Used when the security has not yet been subscribed to
        /// </summary>
        private DateTime GetStartTimeAlgoTzForSecurity(SecurityExchange securityExchange,
                                                       int periods,
                                                       Resolution resolution,
                                                       bool isExtendedMarketHours)
        {
            var timeSpan = resolution.ToTimeSpan();

            // make this a minimum of one second
            timeSpan = timeSpan < QuantConnect.Time.OneSecond ? QuantConnect.Time.OneSecond : timeSpan;

            var localStartTime = QuantConnect.Time.GetStartTimeForTradeBars(
                securityExchange.Hours,
                UtcTime.ConvertFromUtc(securityExchange.TimeZone),
                timeSpan,
                periods,
                isExtendedMarketHours);

            return(localStartTime.ConvertTo(securityExchange.TimeZone, TimeZone));
        }
Ejemplo n.º 26
0
        public SnowflakeIdState(long id, ISnowflakeId idGen)
        {
            Id              = id;
            _idGen          = idGen;
            MachineIdLength = _idGen.MaxMachineMask.ToString().Length;
            SequenceLength  = _idGen.SequenceMask.ToString().Length;

            Sequence = Id & _idGen.SequenceMask;

            MachineId = (Id >> _idGen.SequenceBits) & _idGen.MaxMachineMask;
            if (MachineId != _idGen.MachineId)
            {
                throw new ArgumentException($"MachineId:[{MachineId}] not Equal IdGen.MachineId:[{_idGen.MachineId}]",
                                            nameof(MachineId));
            }

            UtcTime = _idGen.EpochTime.AddMilliseconds((Id >> _idGen.TimestampShift) & _idGen.TimestampMask);
            var machineIdFormat = $"D{MachineIdLength}";
            var sequenceFormat  = $"D{SequenceLength}";

            IdString =
                $"{UtcTime.ToString(TIME_FORMAT)}{MachineId.ToString(machineIdFormat)}{Sequence.ToString(sequenceFormat)}";
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets the start time required for the specified bar count in terms of the algorithm's time zone
        /// </summary>
        private DateTime GetStartTimeAlgoTz(Symbol symbol, int periods, Resolution?resolution = null)
        {
            var security = Securities[symbol];
            var timeSpan = (resolution ?? security.Resolution).ToTimeSpan();

            // make this a minimum of one second
            timeSpan = timeSpan < QuantConnect.Time.OneSecond ? QuantConnect.Time.OneSecond : timeSpan;
            var localStartTime = QuantConnect.Time.GetStartTimeForTradeBars(security.Exchange.Hours, UtcTime.ConvertFromUtc(security.Exchange.TimeZone), timeSpan, periods, security.IsExtendedMarketHours);

            return(localStartTime.ConvertTo(security.Exchange.TimeZone, TimeZone));
        }
Ejemplo n.º 28
0
 public int CompareTo(ApiDateTime other)
 {
     if (other == null) return 1;
     return UtcTime.CompareTo(other.UtcTime);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// 转为Linux时间戳
        /// </summary>
        /// <param name="time">DateTime(本地时间)</param>
        /// <returns>linux时间戳</returns>
        public static int Timestamp(this DateTime time)
        {
            var startTime = UtcTime.ToLocalTime();

            return((int)(time - startTime).TotalSeconds);
        }
Ejemplo n.º 30
0
 public bool Equals(ApiDateTime other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return UtcTime.Equals(other.UtcTime)&& TimeZoneOffset.Equals(other.TimeZoneOffset);
 }