コード例 #1
0
        private IEnumerable <Slice> History(IEnumerable <HistoryRequest> requests, DateTimeZone timeZone)
        {
            var sentMessage = false;
            // filter out any universe securities that may have made it this far
            var filteredRequests = requests.Where(hr => !UniverseManager.ContainsKey(hr.Symbol)).ToList();

            for (var i = 0; i < filteredRequests.Count; i++)
            {
                var request = filteredRequests[i];
                // prevent future requests
                if (request.EndTimeUtc > UtcTime)
                {
                    var endTimeUtc   = UtcTime;
                    var startTimeUtc = request.StartTimeUtc;
                    if (request.StartTimeUtc > request.EndTimeUtc)
                    {
                        startTimeUtc = request.EndTimeUtc;
                    }

                    filteredRequests[i] = new HistoryRequest(startTimeUtc, endTimeUtc,
                                                             request.DataType, request.Symbol, request.Resolution, request.ExchangeHours,
                                                             request.DataTimeZone, request.FillForwardResolution, request.IncludeExtendedMarketHours,
                                                             request.IsCustomData, request.DataNormalizationMode, request.TickType);

                    if (!sentMessage)
                    {
                        sentMessage = true;
                        Debug("Request for future history modified to end now.");
                    }
                }
            }

            // filter out future data to prevent look ahead bias
            return(((IAlgorithm)this).HistoryProvider.GetHistory(filteredRequests, timeZone));
        }
コード例 #2
0
 Task CallSaveHistory(HistoryRequest data)
 {
     return(Task.Factory.StartNew(() =>
     {
         Save_History(data);
     }));
 }
コード例 #3
0
        static async Task HistorySample(string currency, string method)
        {
            var api = new BitfinexApiV1(Configuration["BitfinexApi_key"], Configuration["BitfinexApi_secret"]);

            var request = new HistoryRequest
            {
                Currency = currency,
                Method   = method,
                Since    = DateTimeOffset.Now.AddDays(-3).ToUnixTimeSeconds().ToString(),
                Until    = DateTimeOffset.Now.AddDays(1).ToUnixTimeSeconds().ToString(),
                Limit    = 100,
            };

            LogRequest(request);

            var response = await api.HistoryAsync(request);

            foreach (var r in response)
            {
                r.Timestamp        = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(Convert.ToDouble(r.Timestamp))).ToString();
                r.TimestampCreated = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(Convert.ToDouble(r.TimestampCreated))).ToString();
            }

            LogResponse(response);
        }
コード例 #4
0
ファイル: QCAlgorithm.History.cs プロジェクト: sena7/Lean
        /// <summary>
        /// Get the last known price using the history provider.
        /// Useful for seeding securities with the correct price
        /// </summary>
        /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param>
        /// <returns>A single <see cref="BaseData"/> object with the last known price</returns>
        public BaseData GetLastKnownPrice(Security security)
        {
            var startTime = GetStartTimeAlgoTzForSecurity(security, 1);
            var endTime   = Time.RoundDown(security.Resolution.ToTimeSpan());

            var request = new HistoryRequest()
            {
                StartTimeUtc          = startTime.ConvertToUtc(_localTimeKeeper.TimeZone),
                EndTimeUtc            = endTime.ConvertToUtc(_localTimeKeeper.TimeZone),
                DataType              = security.Resolution == Resolution.Tick ? typeof(Tick) : typeof(TradeBar),
                Resolution            = security.Resolution,
                FillForwardResolution = security.Resolution,
                Symbol        = security.Symbol,
                Market        = security.Symbol.ID.Market,
                ExchangeHours = security.Exchange.Hours
            };

            var history = History(new List <HistoryRequest> {
                request
            });

            if (history.Any() && history.First().Values.Any())
            {
                return(history.First().Values.First());
            }

            return(null);
        }
コード例 #5
0
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="resolution">Resolution of the data request</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable <BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
        {
            if (resolution == Resolution.Tick || resolution == Resolution.Second)
            {
                throw new ArgumentException($"Resolution not available: {resolution}");
            }

            if (!_symbolMapper.IsKnownLeanSymbol(symbol))
            {
                throw new ArgumentException($"The ticker {symbol.Value} is not available.");
            }

            if (endUtc < startUtc)
            {
                throw new ArgumentException("The end date must be greater or equal than the start date.");
            }

            var historyRequest = new HistoryRequest(
                startUtc,
                endUtc,
                typeof(TradeBar),
                symbol,
                resolution,
                SecurityExchangeHours.AlwaysOpen(TimeZones.EasternStandard),
                DateTimeZone.Utc,
                resolution,
                false,
                false,
                DataNormalizationMode.Adjusted,
                TickType.Quote);

            var data = _brokerage.GetHistory(historyRequest);

            return(data);
        }
コード例 #6
0
        private void GetHistoryHelper(HistoryRequest request, Resolution resolution)
        {
            var brokerage = new TradierBrokerage(null, null, null, null, _useSandbox, _accountId, _accessToken);
            var requests  = new[] { request };
            var history   = brokerage.GetHistory(requests, TimeZones.Utc);

            foreach (var slice in history)
            {
                if (resolution == Resolution.Tick)
                {
                    foreach (var tick in slice.Ticks[request.Symbol])
                    {
                        Log.Trace("{0}: {1} - {2} / {3}", tick.Time, tick.Symbol, tick.BidPrice, tick.AskPrice);
                    }
                }
                else
                {
                    var bar = slice.Bars[request.Symbol];

                    Log.Trace("{0}: {1} - O={2}, H={3}, L={4}, C={5}, V={6}", bar.Time, bar.Symbol, bar.Open, bar.High, bar.Low, bar.Close, bar.Volume);
                }
            }

            Log.Trace("Data points retrieved: " + brokerage.DataPointCount);
        }
コード例 #7
0
        public Request AddRequest(RequestViewModel requestViewModel, int requestorId)
        {
            requestViewModel.Request.Requestor   = requestorId;
            requestViewModel.Request.Status      = StatusConstants.STATUS_UNASSIGNED;
            requestViewModel.Request.RequestDate = DateTime.Now;
            requestViewModel.Request.Assignee    = RoleConstants.ROLE_HEAD_OFFICE;

            var createdRequest = _context.Request.Add(requestViewModel.Request);

            if (createdRequest.Entity != null)
            {
                _context.SaveChanges();
                var historyRequest = new HistoryRequest
                {
                    Id          = createdRequest.Entity.Id,
                    Requestor   = requestorId,
                    Facility    = (int)createdRequest.Entity.Facility,
                    RequestDate = DateTime.Now,
                    Assignee    = (int)createdRequest.Entity.Assignee,
                    Status      = (int)createdRequest.Entity.Status,
                    Severity    = (int)createdRequest.Entity.Severity,
                    Remarks     = createdRequest.Entity.Remarks,
                    Requirement = createdRequest.Entity.Requirement
                };
                _context.HistoryRequest.Add(historyRequest);
                _context.SaveChanges();

                return(requestViewModel.Request);
            }
            else
            {
                return(null);
            }
        }
コード例 #8
0
        public SIMSResponseData SaveHistory(HistoryRequest historydata)
        {
            string result = null;
            HttpResponseMessage responseMessage = null;
            SIMSResponseData    response        = new SIMSResponseData();

            try
            {
                string request = JsonConvert.SerializeObject(historydata);

                responseMessage = RestClient.doPost(Url.SAVE_HISTORY_URL, request);

                if (responseMessage.IsSuccessStatusCode)
                {
                    result = responseMessage.Content.ReadAsStringAsync().Result;
                    SIMSResponseData rst = JsonConvert.DeserializeObject <SIMSResponseData>(result);

                    response = rst;

                    if (null != response)
                    {
                        //Utilities.Utility.ShowAlert("Appraisal App", "Vehicle History saved", "OK");
                    }
                }
                else
                {
                    Utilities.Utility.ShowAlert("Appraisal App", "History save failed!!", "OK");
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine("Exception occured :: " + exc.Message);
            }
            return(response);
        }
コード例 #9
0
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="resolution">Resolution of the data request</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <param name="tickType">The tick type (Trade or Quote)</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable <BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc, TickType tickType)
        {
            if (symbol.SecurityType != SecurityType.Equity &&
                symbol.SecurityType != SecurityType.Forex &&
                symbol.SecurityType != SecurityType.Crypto)
            {
                throw new NotSupportedException($"Security type not supported: {symbol.SecurityType}");
            }

            if (endUtc < startUtc)
            {
                throw new ArgumentException("The end date must be greater or equal than the start date.");
            }

            var dataType = LeanData.GetDataType(resolution, tickType);

            var historyRequest =
                new HistoryRequest(startUtc,
                                   endUtc,
                                   dataType,
                                   symbol,
                                   resolution,
                                   SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                                   TimeZones.NewYork,
                                   resolution,
                                   true,
                                   false,
                                   DataNormalizationMode.Adjusted,
                                   tickType);

            foreach (var baseData in _historyProvider.GetHistory(historyRequest))
            {
                yield return(baseData);
            }
        }
コード例 #10
0
        public static HistoryResponse History(HistoryRequest request)
        {
            var res = new HistoryResponse();

            try
            {
                var ActivityPeriod = string.IsNullOrEmpty(request.ActivityPeriod) ? DateTime.Now.ToString("MMMM yyyy") : Convert.ToDateTime(request.ActivityPeriod).ToString("MMMM yyyy");
                var response       = CardActivity(request);
                res.YearToDateFees = response.yearToDateFees;
                var transactionList = response.pendingActivities.cardTransactionHistory.AsEnumerable();
                var list            = new List <Transaction>();
                if (transactionList.Count() > 0)
                {
                    list = transactionList.Select(t => new Transaction
                    {
                        Merchant    = t.transTypeDesc,
                        Time        = t.transactionDateTime.ToString(),
                        Type        = t.totalAmount < 0 ? "Debit" : "Credit",
                        Amount      = t.totalAmount.ToString(),
                        Fee         = t.totalFees.ToString(),
                        Description = t.reference,
                        TransId     = t.sequence
                    }).ToList();
                }
                res.PendingTransactions = list.ToArray();
                return(res);
            }

            catch (Exception ex)
            {
                throw new Exception("History Error");
            }
        }
コード例 #11
0
        private IEnumerable <BaseData> GetDataFromFile(HistoryRequest request, string ticker, DateTime startDate, DateTime?endDate)
        {
            try
            {
                string filename;

                switch (request.Resolution)
                {
                case Resolution.Tick:
                    filename = _lookupClient.Historical.File.GetHistoryTickTimeframeAsync(ticker, startDate, endDate, dataDirection: DataDirection.Oldest).SynchronouslyAwaitTaskResult();
                    return(GetDataFromTickMessages(filename, request));

                case Resolution.Daily:
                    filename = _lookupClient.Historical.File.GetHistoryDailyTimeframeAsync(ticker, startDate, endDate, dataDirection: DataDirection.Oldest).SynchronouslyAwaitTaskResult();
                    return(GetDataFromDailyMessages(filename, request));

                default:
                    var interval = new Interval(GetPeriodType(request.Resolution), 1);
                    filename = _lookupClient.Historical.File.GetHistoryIntervalTimeframeAsync(ticker, interval.Seconds, startDate, endDate, dataDirection: DataDirection.Oldest).SynchronouslyAwaitTaskResult();
                    return(GetDataFromIntervalMessages(filename, request));
                }
            }
            catch (Exception e)
            {
                Log.Error($"IQFeedHistoryProvider.GetDataFromFile(): {e}");
            }

            return(Enumerable.Empty <BaseData>());
        }
コード例 #12
0
        static async Task FindTransactionByCryptoAddress()
        {
            var api = new BitfinexApiV1(Configuration["BitfinexApi_key"], Configuration["BitfinexApi_secret"]);

            string addressToLookFor = "<address>";

            var request = new HistoryRequest
            {
                Currency = "BTC",
                Method   = "bitcoin",
                Since    = DateTimeOffset.Now.AddDays(-3).ToUnixTimeSeconds().ToString(),
                Until    = DateTimeOffset.Now.AddDays(1).ToUnixTimeSeconds().ToString(),
                Limit    = 100,
            };

            LogRequest(request);

            var response = await api.HistoryAsync(request);

            LogResponse(response);

            var item = response.First(t => t.Address == addressToLookFor);

            double expectedAmount = 0.01851848;

            Console.WriteLine("################## Result ################");
            Console.WriteLine($"Expected: Address: {addressToLookFor}, Amount: {expectedAmount} BTC");
            Console.WriteLine($"Actual: Address: {item.Address}, Amount {item.Amount} {item.Currency}, Fee: {item.Fee}, type: {item.Type}");
        }
コード例 #13
0
        static async Task FindTransactionByTxnId()
        {
            var api = new BitfinexApiV1(Configuration["BitfinexApi_key"], Configuration["BitfinexApi_secret"]);

            string txnId = "<txnId>";

            var request = new HistoryRequest
            {
                Currency = "BTC",
                Method   = "bitcoin",
                Since    = DateTimeOffset.Now.AddDays(-30).ToUnixTimeSeconds().ToString(),
                Until    = DateTimeOffset.Now.AddDays(1).ToUnixTimeSeconds().ToString(),
                Limit    = 100,
            };

            LogRequest(request);

            var response = await api.HistoryAsync(request);

            LogResponse(response);

            var item = response.First(t => t.Txid == txnId);

            double expectedAmount = 0.0;

            Console.WriteLine("################## Result ################");
            Console.WriteLine($"Expected: TxnId: {txnId}, Amount: {expectedAmount} BTC");
            Console.WriteLine($"Actual: TxnId: {item.Txid}, Amount {item.Amount} {item.Currency}, Fee: {item.Fee}, type: {item.Type}");
        }
コード例 #14
0
        public static IRequest CreateApiRequest(ApiRequestType requestType)
        {
            IRequest request = null;

            switch (requestType)
            {
            case ApiRequestType.Evemon:
                request = new EvemonRequest();
                break;

            case ApiRequestType.History:
                request = new HistoryRequest();
                break;

            case ApiRequestType.MarketStat:
                request = new MarketStatRequest();
                break;

            case ApiRequestType.QuickLook:
                request = new QuickLookRequest();
                break;

            case ApiRequestType.QuickLookOnPath:
                request = new QuickLookOnPathRequest();
                break;

            case ApiRequestType.Route:
                request = new RouteRequest();
                break;
            }

            return(request);
        }
コード例 #15
0
        public async Task messagesGetHistory(HistoryRequest request, string token, string apiVersion)
        {
            var urlBuilder = new UriBuilder(_url)
            {
                Path  = "method/messages.getHistory",
                Query = $"access_token={token}&v={apiVersion}"
            };

            _logger.Log(NLog.LogLevel.Info, urlBuilder);

            var values = new Dictionary <string, string>
            {
                { "offset", request.offset.ToString() },
                { "count", request.count.ToString() },
                { "user_id", request.user_id },
                { "peer_id", request.peer_id },
                { "start_message_id", request.start_message_id },
                { "rev", request.rev },
                { "extended", request.extended },
                { "fields", request.fields },
                { "group_id", request.group_id },
            };

            var content = new FormUrlEncodedContent(values);

            var response = await _httpClient.PostAsync(urlBuilder.Uri, content);

            var responseBody = await response.Content.ReadAsStringAsync();

            _logger.Log(NLog.LogLevel.Info, responseBody);

            //return Newtonsoft.Json.JsonConvert.DeserializeObject<PhotoSaveResponse>(responseBody);
        }
コード例 #16
0
ファイル: IBDataDownloader.cs プロジェクト: zdomokos/Lean
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="resolution">Resolution of the data request</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable <BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
        {
            if (resolution == Resolution.Tick)
            {
                throw new NotSupportedException("Resolution not available: " + resolution);
            }

            if (endUtc < startUtc)
            {
                throw new ArgumentException("The end date must be greater or equal than the start date.");
            }

            var historyRequest = new HistoryRequest(
                startUtc,
                endUtc,
                typeof(QuoteBar),
                symbol,
                resolution,
                SecurityExchangeHours.AlwaysOpen(TimeZones.EasternStandard),
                DateTimeZone.Utc,
                resolution,
                false,
                false,
                DataNormalizationMode.Adjusted,
                TickType.Quote);

            var data = _brokerage.GetHistory(historyRequest);

            return(data);
        }
コード例 #17
0
        public IEnumerable<HistoryItem> BuildHistory(HistoryRequest request)
        {
            if (!_historySettings.MergeCaseHistoryChildSubcases)
            {
                return _historyBuilder.Build(request);
            }

            _logger.LogDebug("Build merged history for case {0}", request.WorkflowObject.Id);

            var subcaseIds = GetSubcaseIds(request.WorkflowObject).ToArray();

            var caseHistory = _historyBuilder.Build(request);

            if (!subcaseIds.Any())
            {
                return caseHistory;
            }
            var subcaseWorkflowObject = new WorkflowObject {Type = WorkflowObject.Subcase, Id = subcaseIds.First(), IsChild = true};
            var subcaseHistoryRequest = new HistoryRequest
            {
                HistoryItemLimit = request.HistoryItemLimit,
                WorkflowObject = subcaseWorkflowObject,
                Since = request.Since,
                ShowAllActivities = request.ShowAllActivities
            };

            _logger.LogDebug("Build and merge subcase history for case {0} subcases: {1}", request.WorkflowObject.Id, subcaseIds.Join(","));

            var subcaseHistories = _historyBuilder.Build(subcaseHistoryRequest, subcaseIds);

            var results = subcaseHistories.Concat(caseHistory);

            return results.OrderByDescending(r => r.When);
        }
コード例 #18
0
        /// <summary>
        /// Gets the history for the requested security
        /// </summary>
        /// <param name="request">The historical data request</param>
        /// <returns>An enumerable of bars covering the span specified in the request</returns>
        public override IEnumerable <BaseData> GetHistory(HistoryRequest request)
        {
            // GDAX API only allows us to support history requests for TickType.Trade
            if (request.TickType != TickType.Trade)
            {
                yield break;
            }

            if (request.EndTimeUtc < request.StartTimeUtc)
            {
                OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidDateRange",
                                                    "The history request start date must precede the end date, no history returned"));
                yield break;
            }

            if (request.Resolution == Resolution.Tick || request.Resolution == Resolution.Second)
            {
                OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidResolution",
                                                    $"{request.Resolution} resolution not supported, no history returned"));
                yield break;
            }

            Log.Trace($"GDAXBrokerage.GetHistory(): Submitting request: {request.Symbol.Value}: {request.Resolution} {request.StartTimeUtc} UTC -> {request.EndTimeUtc} UTC");

            foreach (var tradeBar in GetHistoryFromCandles(request))
            {
                yield return(tradeBar);
            }
        }
コード例 #19
0
        public void GetsHistory(Symbol symbol, Resolution resolution, TimeSpan period, bool throwsException)
        {
            TestDelegate test = () =>
            {
                var now     = DateTime.UtcNow;
                var request = new HistoryRequest(now.Add(-period),
                                                 now,
                                                 typeof(TradeBar),
                                                 symbol,
                                                 resolution,
                                                 SecurityExchangeHours.AlwaysOpen(TimeZones.EasternStandard),
                                                 TimeZones.EasternStandard,
                                                 Resolution.Minute,
                                                 false,
                                                 false,
                                                 DataNormalizationMode.Adjusted,
                                                 TickType.Trade);


                GetHistoryHelper(request, resolution);
            };

            if (throwsException)
            {
                Assert.Throws <ArgumentException>(test);
            }
            else
            {
                Assert.DoesNotThrow(test);
            }
        }
コード例 #20
0
ファイル: QCAlgorithm.History.cs プロジェクト: xhxuciedu/Lean
        /// <summary>
        /// Get the last known price using the history provider.
        /// Useful for seeding securities with the correct price
        /// </summary>
        /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param>
        /// <returns>A single <see cref="BaseData"/> object with the last known price</returns>
        public BaseData GetLastKnownPrice(Security security)
        {
            // For speed and memory usage, use Resolution.Minute as the minimum resolution
            var resolution = (Resolution)Math.Max((int)Resolution.Minute, (int)security.Resolution);

            var startTime = GetStartTimeAlgoTzForSecurity(security, 1, resolution);
            var endTime   = Time.RoundDown(resolution.ToTimeSpan());

            var request = new HistoryRequest()
            {
                StartTimeUtc          = startTime.ConvertToUtc(_localTimeKeeper.TimeZone),
                EndTimeUtc            = endTime.ConvertToUtc(_localTimeKeeper.TimeZone),
                DataType              = typeof(TradeBar),
                Resolution            = resolution,
                FillForwardResolution = resolution,
                Symbol        = security.Symbol,
                Market        = security.Symbol.ID.Market,
                ExchangeHours = security.Exchange.Hours
            };

            var history = History(new List <HistoryRequest> {
                request
            });

            if (history.Any() && history.First().Values.Any())
            {
                return(history.First().Values.First());
            }

            return(null);
        }
コード例 #21
0
        public IEnumerable <BaseData> ProcessHistoryRequests(HistoryRequest request)
        {
            // skipping universe and canonical symbols
            if (!CanHandle(request.Symbol) ||
                request.Symbol.ID.SecurityType == SecurityType.Option && request.Symbol.IsCanonical() ||
                request.Symbol.ID.SecurityType == SecurityType.Future && request.Symbol.IsCanonical())
            {
                return(Enumerable.Empty <BaseData>());
            }

            // skipping empty ticker
            var ticker = _symbolMapper.GetBrokerageSymbol(request.Symbol);

            if (string.IsNullOrEmpty(ticker))
            {
                Log.Trace($"IQFeedFileHistoryProvider.ProcessHistoryRequests(): Unable to retrieve ticker from Symbol: ${request.Symbol}");
                return(Enumerable.Empty <BaseData>());
            }

            var      start = request.StartTimeUtc.ConvertFromUtc(TimeZones.NewYork);
            DateTime?end   = request.EndTimeUtc.ConvertFromUtc(TimeZones.NewYork);

            // if we're within a minute of now, don't set the end time
            if (request.EndTimeUtc >= DateTime.UtcNow.AddMinutes(-1))
            {
                end = null;
            }

            Log.Trace(
                $"IQFeedFileHistoryProvider.ProcessHistoryRequests(): Submitting request: {request.Symbol.SecurityType.ToStringInvariant()}-{ticker}: " +
                $"{request.Resolution.ToStringInvariant()} {start.ToStringInvariant()}->{(end ?? DateTime.UtcNow.AddMinutes(-1)).ToStringInvariant()}"
                );

            return(FilterUnorderedData(GetDataFromFile(request, ticker, start, end)));
        }
コード例 #22
0
ファイル: VKBot.cs プロジェクト: SNAKEspb/StirkaBot
        public async Task messagesGetHistory(IOutgoingMessage message)
        {
            try
            {
                var tmessage = (OutgoingMessage)message;

                var request = new HistoryRequest
                {
                    //offset = 0,
                    count = 1,
                    //user_id = "1556462",
                    peer_id = tmessage.peer_id,
                    //start_message_id = "0",
                    //rev = "1",
                    //extended =
                    //fields =
                    group_id = _options.groupId,
                };
                await vkService.sendRequest(request, "messages.getHistory", _options);
            }
            catch (Exception e)
            {
                _logger.Log(NLog.LogLevel.Error, e, "SendMessageAsync error");
            }
        }
コード例 #23
0
        private void Validate(HistoryRequest aRequest)
        {
            SymbolItem aSymbol = aRequest.Selection.Symbol;

            if (aSymbol.Type == Instrument.Unknown)
            {
                throw new ApplicationException("Invalid instrument");
            }
        }
コード例 #24
0
 public HttpResponseMessage Post(HistoryRequest request)
 {
     return(StartJob((session, config, job) => {
         using (var exporter = new Exporter(session, config, job)) {
             exporter.ExportSentOrders(request.OrderIds ?? new ulong[0]);
             exporter.Compress(job.OutputFile(Config));
         }
     }));
 }
コード例 #25
0
ファイル: LocController.cs プロジェクト: seb999/BTrackerR
 public List <GpsPosition> GetHistoryData([FromBody] HistoryRequest historyRequest)
 {
     if (User.Identity.IsAuthenticated && historyRequest.DeviceId.HasValue && historyRequest.Start.HasValue && historyRequest.End.HasValue)
     {
         return(DbContext.GpsPosition.Where(p => p.DeviceId == historyRequest.DeviceId && p.GpsPositionDate >= historyRequest.Start && p.GpsPositionDate <= historyRequest.End).OrderBy(p => p.GpsPositionDate).ToList());
         // return DbContext.GpsPosition.Where(p => p.TrackedObject.TrackedObjectId == historyRequest.trackedObjectId && p.TrackedObject.UserId == User.Claims.FirstOrDefault().Value && p.GpsPositionDate >= historyRequest.start && p.GpsPositionDate <= historyRequest.end).OrderBy(p => p.GpsPositionDate).ToList();
     }
     return(null);
 }
コード例 #26
0
ファイル: Kernel.cs プロジェクト: stayyule/icsharp.kernel
        public void historyRequest(KernelMessage msg, HistoryRequest content)
        {
            var reply = new HistoryReply()
            {
                history = new List <string>()
            };

            sendMessage(shellSocket, msg, "history_reply", reply);
        }
コード例 #27
0
ファイル: QCAlgorithm.History.cs プロジェクト: manisin/Lean
        /// <summary>
        /// Get the last known price using the history provider.
        /// Useful for seeding securities with the correct price
        /// </summary>
        /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param>
        /// <returns>A single <see cref="BaseData"/> object with the last known price</returns>
        public BaseData GetLastKnownPrice(Security security)
        {
            if (security.Symbol.IsCanonical() || HistoryProvider == null)
            {
                return(null);
            }

            // For speed and memory usage, use Resolution.Minute as the minimum resolution
            var resolution = (Resolution)Math.Max((int)Resolution.Minute, (int)security.Resolution);

            var startTime = GetStartTimeAlgoTzForSecurity(security, 1, resolution);
            var endTime   = Time.RoundDown(resolution.ToTimeSpan());

            // request QuoteBar for Options and Futures
            var dataType = typeof(BaseData);

            if (security.Type == SecurityType.Option || security.Type == SecurityType.Future)
            {
                dataType = LeanData.GetDataType(resolution, TickType.Quote);
            }

            // Get the config with the largest resolution
            var subscriptionDataConfig = GetMatchingSubscription(security, dataType);

            // if subscription resolution is Tick, we also need to update the data type from Tick to TradeBar/QuoteBar
            if (subscriptionDataConfig != null && subscriptionDataConfig.Resolution == Resolution.Tick)
            {
                dataType = LeanData.GetDataType(resolution, subscriptionDataConfig.TickType);
                subscriptionDataConfig = new SubscriptionDataConfig(subscriptionDataConfig, dataType, resolution: resolution);
            }

            var request = new HistoryRequest(
                startTime.ConvertToUtc(_localTimeKeeper.TimeZone),
                endTime.ConvertToUtc(_localTimeKeeper.TimeZone),
                subscriptionDataConfig == null ? typeof(TradeBar) : subscriptionDataConfig.Type,
                security.Symbol,
                resolution,
                security.Exchange.Hours,
                MarketHoursDatabase.FromDataFolder().GetDataTimeZone(security.Symbol.ID.Market, security.Symbol, security.Symbol.SecurityType),
                resolution,
                security.IsExtendedMarketHours,
                security.IsCustomData(),
                security.DataNormalizationMode,
                subscriptionDataConfig == null ? LeanData.GetCommonTickTypeForCommonDataTypes(typeof(TradeBar), security.Type) : subscriptionDataConfig.TickType
                );

            var history = History(new List <HistoryRequest> {
                request
            }).ToList();

            if (history.Any() && history.First().Values.Any())
            {
                return(history.First().Values.First());
            }

            return(null);
        }
コード例 #28
0
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="dataDownloaderGetParameters">model class for passing in parameters for historical data</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable <BaseData> Get(DataDownloaderGetParameters dataDownloaderGetParameters)
        {
            var symbol     = dataDownloaderGetParameters.Symbol;
            var resolution = dataDownloaderGetParameters.Resolution;
            var startUtc   = dataDownloaderGetParameters.StartUtc;
            var endUtc     = dataDownloaderGetParameters.EndUtc;
            var tickType   = dataDownloaderGetParameters.TickType;

            if (tickType != TickType.Quote)
            {
                yield break;
            }

            if (resolution == Resolution.Tick)
            {
                throw new NotSupportedException("Resolution not available: " + resolution);
            }

            if (endUtc < startUtc)
            {
                throw new ArgumentException("The end date must be greater or equal than the start date.");
            }

            var symbols = new List <Symbol> {
                symbol
            };

            if (symbol.IsCanonical())
            {
                symbols = GetChainSymbols(symbol, true).ToList();
            }

            var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(symbol.ID.Market, symbol, symbol.SecurityType);
            var dataTimeZone  = MarketHoursDatabase.FromDataFolder().GetDataTimeZone(symbol.ID.Market, symbol, symbol.SecurityType);

            foreach (var targetSymbol in symbols)
            {
                var historyRequest = new HistoryRequest(startUtc,
                                                        endUtc,
                                                        typeof(QuoteBar),
                                                        targetSymbol,
                                                        resolution,
                                                        exchangeHours: exchangeHours,
                                                        dataTimeZone: dataTimeZone,
                                                        resolution,
                                                        includeExtendedMarketHours: true,
                                                        false,
                                                        DataNormalizationMode.Adjusted,
                                                        TickType.Quote);

                foreach (var baseData in _brokerage.GetHistory(historyRequest))
                {
                    yield return(baseData);
                }
            }
        }
コード例 #29
0
        public async Task <ActionResult <HistoryResponse> > Get([FromQuery] HistoryRequest req)
        {
            var history = await _bingeWatchService.GetUserWatchingHistory(req.UserId);

            return(Ok(new HistoryResponse
            {
                UserId = req.UserId,
                Content = _mapper.Map <List <HistoryViewModel> >(history)
            }));
        }
コード例 #30
0
 /// <summary>
 /// Lists history of a specific market between two dates
 /// </summary>
 /// <returns>
 /// Array of <typeparamref name="HistoryResult"/>
 /// </returns>
 public async Task <HistoryResult[]> GetHistory(HistoryRequest historyRequest)
 {
     return(await GetAsync <HistoryResult[]>(
                string.Format("history/{0}/{1}/{2}/{3}/{4}",
                              historyRequest.ListingCurrency,
                              historyRequest.ReferenceCurrency,
                              historyRequest.StartJs,
                              historyRequest.EndJs,
                              historyRequest.Periods?.ToString() ?? string.Empty)));
 }
コード例 #31
0
        private HistoryRequest CreateHistoryRequest(Security security, DateTime start, DateTime end, Resolution?resolution)
        {
            resolution = resolution ?? security.Resolution;
            var request = new HistoryRequest(security, start.ConvertToUtc(TimeZone), end.ConvertToUtc(TimeZone))
            {
                Resolution            = resolution.Value,
                FillForwardResolution = security.IsFillDataForward ? resolution : null
            };

            return(request);
        }
コード例 #32
0
        public HistoryViewModel Execute(HistoryRequest request)
        {
            var workflowObject = WorkflowObject.Create(request.Type, request.Id);

            if (request.DaysOfHistory> 0)
            {
                var since = _systemTime.Now.Subtract(TimeSpan.FromDays(request.DaysOfHistory));
                return _historyAssembler.GetHistorySince(workflowObject, since);
            }

            return _historyAssembler.GetHistory(workflowObject);
        }
コード例 #33
0
        public HistoryViewModel Execute(GETHistoryRequest request)
        {
            var workflowObject = WorkflowObject.Create(request.Type, request.Id);

            var historyRequest = new HistoryRequest {WorkflowObject = workflowObject, ShowAllActivities = request.IsVerbose};

            if (request.DaysOfHistory > 0)
            {
                var since = _systemTime.Now.Subtract(TimeSpan.FromDays(request.DaysOfHistory));
                historyRequest.Since = since;
            }

            return _historyAssembler.GetHistory(historyRequest);
        }
コード例 #34
0
 public IEnumerable<HistoryItem> BuildHistory(HistoryRequest request)
 {
     return _historyBuilder.Build(request);
 }