private async Task <List <SecuritySymbol> > ObtainSymbolsFromIeXAsync()
        {
            if (symbols != null && symbols.Count >= 5 && (DateTime.Now - lastSymbolUpdate).TotalDays < 1)
            {
                return(symbols);
            }
            var urlToUse = iexSymbolListURL.Replace(apiKey, _envHandler.GetApiKey(iexTradingProvider));

            try
            {
                using (var wc = new WebClient())
                {
                    string data = "{}";
                    data = await wc.DownloadStringTaskAsync(urlToUse);

                    symbols          = JsonConvert.DeserializeObject <IEnumerable <SecuritySymbol> >(data).ToList();
                    lastSymbolUpdate = DateTime.Now;
                    return(symbols);
                }
            }
            catch (Exception ex)
            {
                _log.LogError("Error while getting data from IEX trading");
                _log.LogError(ex.Message);
                return(new List <SecuritySymbol>());
            }
        }
Example #2
0
        private async Task <List <SecuritySymbol> > ObtainSymbolsFromIeXAsync()
        {
            LastUpateCollectionMd lastUpdateDate = null;

            if (symbols != null && symbols.Count >= 100 && (DateTime.Now - lastSymbolUpdate).TotalDays < 1)
            {
                return(symbols);
            }

            lastUpdateDate = GetSymbolsFromDb();
            if (symbols != null && symbols.Count >= 100)
            {
                lastSymbolUpdate = lastUpdateDate.LastUpdate;
                return(symbols);
            }
            if (symbols == null)
            {
                symbols = new List <SecuritySymbol>();
            }
            else
            {
                symbols.Clear();
            }
            var urlToUse  = iexSymbolListURL.Replace(apiKey, _envHandler.GetApiKey(iexTradingProvider));
            var url1ToUse = iexOTCSymbolListURL.Replace(apiKey, _envHandler.GetApiKey(iexTradingProvider));

            try
            {
                using (var httpClient = new HttpClient())
                {
                    string data = "{}";
                    data = await httpClient.GetStringAsync(urlToUse);

                    var settings = new JsonSerializerSettings
                    {
                        NullValueHandling     = NullValueHandling.Ignore,
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };
                    var symbols0 = JsonConvert.DeserializeObject <IEnumerable <SecuritySymbol> >(data, settings).ToList();
                    symbols.AddRange(symbols0);
                    var data1 = "{}";
                    data1 = await httpClient.GetStringAsync(url1ToUse);

                    var symbols1 = JsonConvert.DeserializeObject <IEnumerable <SecuritySymbol> >(data1, settings).ToList();
                    symbols.AddRange(symbols1);
                    lastSymbolUpdate = DateTime.Now;
                    lastUpdateDate   = await PopulateSymbolsToDbAsync(lastUpdateDate);

                    return(symbols);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Error while getting data from IEX trading");
                _logger.LogError(ex.Message);
                return(new List <SecuritySymbol>());
            }
        }
Example #3
0
        /// <summary>
        /// Gets  external news.
        /// </summary>
        /// <param name="newsSource">The news source.</param>
        /// <returns></returns>
        public async Task <string> GetExternalNews(string newsSource)
        {
            var apiKey   = _envHandler.GetApiKey(newsAPIKey);
            var urlToUse = mediaNews.Replace("newsMedia", newsSource.ToLower().Trim())
                           .Replace("API_KEY", apiKey);
            NewsExtract extracts = await ObtainNewAPIDta(urlToUse);

            if (extracts == null)
            {
                return(null);
            }
            return(ExtractHeadlines(extracts));
        }
Example #4
0
        private async Task <CompanyKeyStats> ObtainCompanyStats(string ticker)
        {
            var urlToUse = iexCompanyStatssURL.Replace("{ticker}", ticker)
                           .Replace(apiKey, _envHandler.GetApiKey(iexTradingProvider));

            try
            {
                using (var hc = new HttpClient())
                {
                    string data = "{}";
                    data = await hc.GetStringAsync(urlToUse);

                    var settings = new JsonSerializerSettings
                    {
                        NullValueHandling     = NullValueHandling.Ignore,
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };
                    var companyOverview = JsonConvert.DeserializeObject <CompanyKeyStats>(data, settings);
                    return(companyOverview);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Error while getting data from IEX Trading");
                _logger.LogError(ex.Message);
                if (ex.InnerException != null)
                {
                    _logger.LogError(ex.InnerException.Message);
                }
                return(new CompanyKeyStats());
            }
        }
        private async Task <string> BuildAnalystsRatings(string ticker)
        {
            var urlToUseForAnalystRating = iexAnalystRatings.Replace(@"{ticker}", ticker)
                                           .Replace(@"{api-key}", _envHandler.GetApiKey(iexTradingProvider));

            try
            {
                using (var wc = new WebClient())
                {
                    string data = "[]";
                    data = await wc.DownloadStringTaskAsync(urlToUseForAnalystRating);

                    var ratingsArray = JsonConvert.DeserializeObject <IEnumerable <Ratings> >(data).ToList();
                    if (ratingsArray == null || !ratingsArray.Any())
                    {
                        return("");
                    }
                    var ratingsToUse = ratingsArray.OrderBy(r => r.ConsensusEndDate).FirstOrDefault();
                    var totalRatings = ratingsToUse.RatingBuy + ratingsToUse.RatingOverweight
                                       + ratingsToUse.RatingHold + ratingsToUse.RatingUnderweight
                                       + ratingsToUse.RatingSell + ratingsToUse.RatingNone;
                    if (totalRatings == 0)
                    {
                        return("");
                    }
                    StringBuilder returnString = BuildRatingsMessage(ratingsToUse, totalRatings);
                    return(returnString.ToString());
                }
            }
            catch (Exception ex)
            {
                _log.LogError($"Error in BuildAnalystsRatings; message\n{ex.Message}\n ");
                return("");
            }
        }
        public static IServiceCollection AddMongoRepository(this IServiceCollection services)
        {
            var mongoURL = EnvHandler.GetApiKey("InvestDb");

            services.AddSingleton <IAppRepository <string> >(r => new Repository <string>(mongoURL));
            return(services);
        }
Example #7
0
        private string BuildUrlToUse(string newsSourceRequested, out string readableParameter)
        {
            readableParameter = "";

            string newsMedia = "sources=";

            switch (newsSourceRequested.ToLower())
            {
            case "cnbc":
                newsMedia += newsSourceRequested.ToLower().Trim();
                break;

            case "the-new-york-times":
                newsMedia += newsSourceRequested.ToLower().Trim();
                break;

            case "the-wall-street-journal":
                newsMedia += newsSourceRequested.ToLower().Trim();
                break;

            case "the-hindu":
                newsMedia += newsSourceRequested.ToLower().Trim();
                break;

            default:
                newsMedia = "country=us";
                break;
            }
            string apiKey = _envHandler.GetApiKey(Provider);
            var    urlStr = $"https://newsapi.org/v2/top-headlines?{newsMedia}&apiKey={apiKey}";

            return(urlStr);
        }
        public SecurityPriceSave(ILogger <SecurityPriceSave> logger,
                                 IMapper mapper,
                                 IAppRepository <string> appRepository,
                                 IHttpClientFactory clientFactory)
        {
            this.logger        = logger;
            this.mapper        = mapper;
            this.appRepository = appRepository;

            //SQS
            sqs = new AmazonSQSClient(RegionEndpoint.USEast1);
            queueUrlResponse = sqs.GetQueueUrlAsync(QueueName).Result;

            //HttpClient
            client = clientFactory.CreateClient();

            //TDA
            apiKey = EnvHandler.GetApiKey(@"tdameritrade");

            //API Gateway key
            isrKey = EnvHandler.GetApiKey(@"ISRApiHandler");

            //Security list
            securityList = GetTickerList().Result;
        }
        public static bool IsEnglish(this string inputString)
        {
            var    envHandler = new EnvHandler();
            var    key        = envHandler.GetApiKey(KeyForTraslator);
            string host       = HostName;
            string route      = RouteName;

            return(DetectTextRequest(key, host, route, inputString.TruncateAtWord(50)));
        }
Example #10
0
        private async Task <string> GetTargetPriceAsync(string ticker)
        {
            var urlToUseForTarget = iexTargetPrice.Replace(@"{ticker}", ticker)
                                    .Replace(@"{api-key}", _envHandler.GetApiKey(iexTradingProvider));
            var urlToUseForPrice = iexLastTradePrice.Replace(@"{ticker}", ticker)
                                   .Replace(@"{api-key}", _envHandler.GetApiKey(iexTradingProvider));

            try
            {
                using (var wc = new WebClient())
                {
                    string data           = "{}";
                    string lastTradePrice = "";
                    data = await wc.DownloadStringTaskAsync(urlToUseForTarget);

                    lastTradePrice = await wc.DownloadStringTaskAsync(urlToUseForPrice);

                    var targetPrice = JsonConvert.DeserializeObject <TargetPrice>(data);
                    if (targetPrice != null && !targetPrice.Symbol.IsNullOrWhiteSpace())
                    {
                        var returnString = $"\n As of {targetPrice.UpdatedDate.ToString("MMMM dd")} {targetPrice.NumberOfAnalysts} Analysts project {targetPrice.PriceTargetAverage.ToString("c2")} as target price \n";
                        returnString += $"The target ranges between {targetPrice.PriceTargetLow.ToString("c2")} to {targetPrice.PriceTargetHigh.ToString("c2")} \n";
                        if (!lastTradePrice.IsNullOrWhiteSpace())
                        {
                            returnString += $" It last traded at ${lastTradePrice}\n\n ";
                        }
                        return(returnString);
                    }
                    return("");
                }
            }
            catch (Exception ex)
            {
                _log.LogError("Error while getting data from IEX Trading");
                _log.LogError(ex.Message);
                if (ex.InnerException != null)
                {
                    _log.LogError(ex.InnerException.Message);
                }
                return("");
            }
        }
        /// <summary>
        /// Gets the stock quotes.
        /// </summary>
        /// <param name="tickersToUse">The tickers to use.</param>
        /// <returns></returns>
        public async Task <QuotesFromWorldTrading> GetStockQuotes(string tickersToUse)
        {
            var apiKey = _envHandler.GetApiKey("WorldTradingDataKey");

            if (string.IsNullOrWhiteSpace(apiKey))
            {
                _logger.LogError("Did not find api key; calls will fail");
            }
            string urlStr = quotesAPI.Replace("{tickersToUse}", tickersToUse)
                            .Replace("{apiKey}", apiKey);
            string data = "{}";

            try
            {
                using (var httpClient = new HttpClient())
                {
                    data = await httpClient.GetStringAsync(urlStr);
                }
                data = data.Replace(":\"N/A\"", ":null");
                var settings = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore,
                };
                var indexData = JsonConvert.DeserializeObject <QuotesFromWorldTrading>(data, settings);
                return(indexData);
            }
            catch (Exception ex)
            {
                _logger.LogCritical($"Error processing data from World Trading.\n{ex.Message}");
                return(new QuotesFromWorldTrading
                {
                    Data = new Datum[0]
                });
            }
        }
Example #12
0
        private static void ConfigureServices(ServiceCollection serviceCollection)
        {
            SetApplicationEnvVar.SetEnvVariablesFromS3();

            var mongoURL = EnvHandler.GetApiKey("InvestDb");

            serviceCollection.AddScoped <IAppRepository <string> >(r => new Repository <string>(mongoURL));

            serviceCollection.AddAutoMapper(typeof(AMProfile));
            MapperConfiguration config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <AMProfile>();
            });

            config.AssertConfigurationIsValid();
            serviceCollection.AddSingleton <IReadSCFile, ReadSCFile>();
        }
        public EvaluateSecurity(
            ILogger <EvaluateSecurity> logger,
            IMapper mapper,
            IAppRepository <string> appRepository,
            IHttpClientFactory clientFactory)
        {
            this.logger        = logger;
            this.mapper        = mapper;
            this.appRepository = appRepository;

            //HttpClient
            client  = clientFactory.CreateClient();
            client1 = clientFactory.CreateClient();

            //API Gateway key
            IsrKey       = EnvHandler.GetApiKey(@"ISRApiHandler");
            simFinAPIKey = EnvHandler.GetApiKey(@"SimFinKey");
        }
Example #14
0
        private void ConfigureServices(IServiceCollection serviceCollection)
        {
            SetApplicationEnvVar.SetEnvVariablesFromS3();
            var mongoURL = EnvHandler.GetApiKey("InvestDb");

            serviceCollection.AddScoped <IAppRepository <string> >(r => new Repository <string>(mongoURL));

            serviceCollection.AddAutoMapper(typeof(AMProfile));
            MapperConfiguration config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <AMProfile>();
            });

            config.AssertConfigurationIsValid();
            serviceCollection.AddLogging(c => c.AddNLog())
            .Configure <LoggerFilterOptions>(o => o.MinLevel = LogLevel.Debug)
            .AddTransient(typeof(ILogger <>), typeof(Logger <>));
            serviceCollection.AddScoped <IPopulateSQS, PopulateSQS>();
            serviceCollection.AddScoped <ISecurityPriceSave, SecurityPriceSave>();
            serviceCollection.AddScoped <IEvaluateSecurity, EvaluateSecurity>();
            serviceCollection.AddHttpClient();
        }