Beispiel #1
0
        public async Task <StockSummary> GetStockQuote(string ticker)
        {
            var securities = await Yahoo.Symbols(ticker).Fields(Field.LongName, Field.RegularMarketPrice, Field.RegularMarketChange, Field.RegularMarketChangePercent, Field.FiftyTwoWeekHigh, Field.FiftyTwoWeekLow, Field.RegularMarketDayLow, Field.RegularMarketDayHigh, Field.RegularMarketOpen, Field.RegularMarketPreviousClose, Field.RegularMarketVolume, Field.Bid, Field.BidSize, Field.Ask, Field.AskSize, Field.EarningsTimestamp, Field.EpsForward, Field.FinancialCurrency, Field.MarketCap).QueryAsync();

            var security = securities[ticker.ToUpper()];

            security.Fields.TryGetValue(ticker, out dynamic key);
            StockSummary models = new StockSummary()
            {
                Ticker        = ticker,
                Name          = security.LongName,
                Change        = security.RegularMarketChange,
                ChangePercent = security.RegularMarketChangePercent,
                weekHigh      = security.FiftyTwoWeekHigh,
                weekLow       = security.FiftyTwoWeekLow,
                dayHigh       = security.RegularMarketDayHigh,
                dayLow        = security.RegularMarketDayLow,
                Open          = Convert.ToDecimal(security.RegularMarketOpen),
                Close         = Convert.ToDecimal(security.RegularMarketPreviousClose),
                Bid           = security.Bid,
                Ask           = security.Ask,
                BidSize       = security.BidSize,
                AskSize       = security.AskSize,
                market        = security.MarketCap,
                Currency      = security.Currency,
                Volume        = security.RegularMarketVolume
            };

            return(models);
        }
Beispiel #2
0
        public async Task <Quote> GetQuote(string scrip)
        {
            // You could query multiple symbols with multiple fields through the following steps:
            var securities = await Yahoo.Symbols(scrip).Fields(Field.Symbol, Field.RegularMarketPrice, Field.FiftyTwoWeekHigh,
                                                               Field.RegularMarketDayHigh, Field.RegularMarketDayLow, Field.RegularMarketPreviousClose, Field.AverageDailyVolume10Day,
                                                               Field.RegularMarketVolume, Field.FiftyDayAverage, Field.FiftyDayAverageChange, Field.FiftyDayAverageChangePercent, Field.RegularMarketTime
                                                               ).QueryAsync();

            var sec = securities[scrip];

            //trend over past years
            var history = await Yahoo.GetHistoricalAsync(scrip, new DateTime(2019, 1, 1), new DateTime(2020, 4, 1), Period.Monthly);

            Quote myQuote = new Quote();

            myQuote.Scrip           = sec.Symbol;
            myQuote.MktTime         = sec.RegularMarketTime;
            myQuote.Currentprice    = sec.RegularMarketPrice;
            myQuote.High            = sec.RegularMarketDayHigh;
            myQuote.Low             = sec.RegularMarketDayLow;
            myQuote.Volume          = sec.RegularMarketVolume;
            myQuote.Avg10DVolume    = sec.AverageDailyVolume10Day;
            myQuote.FiftyDayAverage = sec.FiftyDayAverage;
            myQuote.PreviousClose   = sec.RegularMarketPreviousClose;
            myQuote.History         = history;

            return(myQuote);
        }
        // Method to create the ticker from YahooFinance and add it to a list.
        private async void GetTicker(string name)
        {
            try
            {
                var securities = await Yahoo.Symbols(name).Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketVolume, Field.RegularMarketOpen, Field.FiftyTwoWeekHigh).QueryAsync();

                var    aapl   = securities[name];
                Ticker ticker = new Ticker();
                ticker.Name      = name;
                ticker.CurrPrice = aapl.RegularMarketPrice;
                ticker.OpenPrice = aapl.RegularMarketOpen;
                ticker.Volume    = FormatNumber(aapl.RegularMarketVolume);
                tickerList.Add(ticker);
                this.tickerListView.Items.Add(ticker);
            }
            // Check if the symbol name is valid. If not remove from DB.
            catch
            {
                MessageBox.Show("Invalid Ticker symbol.");
                string query = "DELETE FROM Ticker WHERE Name=@Name";

                using (connection = new SqlConnection(connectionString))
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        connection.Open();
                        command.Parameters.AddWithValue("@Name", name);
                        command.ExecuteScalar();
                    }
            }
        }
Beispiel #4
0
        static async Task Archivess()
        {
            // Sometimes, yahoo returns broken rows for historical calls, you could decide if these invalid rows is ignored or not by the following statement
            Yahoo.IgnoreEmptyRows = true;



            object securities;
            // You could query multiple symbols with multiple fields through the following steps:
            await Task.Run(() => securities = Yahoo.Symbols("TRCH", "GOOG").Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketDayLow, Field.RegularMarketOpen, Field.RegularMarketPreviousClose).QueryAsync());

            //var TRCH = securities["TRCH"];
            //var price = TRCH[Field.RegularMarketPrice]; // or, you could use aapl.RegularMarketPrice directly for typed-value



            var testo = await Yahoo.Symbols("TRCH").Fields(Field.RegularMarketPrice, Field.RegularMarketDayLow, Field.RegularMarketOpen, Field.RegularMarketDayHigh).QueryAsync();



            // You should be able to query data from various markets including US, HK, TW
            // The startTime & endTime here defaults to EST timezone
            var history = await Yahoo.GetHistoricalAsync("SI", DateTime.Today.AddDays(-60), DateTime.Today, Period.Daily);

            foreach (var candle in history)
            {
                Console.WriteLine($"DateTime: {candle.DateTime}, Open: {candle.Open}, High: {candle.High}, Low: {candle.Low}, Close: {candle.Close}, Volume: {candle.Volume}, AdjustedClose: {candle.AdjustedClose}");
            }
        }
Beispiel #5
0
        static async Task <List <CLASS_Ticker_Info> > LIST_Get_Tickers_Current_From_Array(string[] ARRAY_Input_Tickers)
        {
            List <CLASS_Ticker_Info> LIST_Tickers         = new List <CLASS_Ticker_Info>();
            CLASS_Ticker_Info        OBJECT_Actual_Ticker = new CLASS_Ticker_Info();

            Yahoo.IgnoreEmptyRows = true;

            IReadOnlyDictionary <string, Security> Securities = await Yahoo.Symbols(ARRAY_Input_Tickers).Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketDayLow, Field.RegularMarketOpen, Field.RegularMarketDayHigh).QueryAsync();

            for (int i = 0; i <= ARRAY_Input_Tickers.Length - 1; i++)
            {
                try
                {
                    OBJECT_Actual_Ticker        = new CLASS_Ticker_Info();
                    OBJECT_Actual_Ticker.Ticker = ARRAY_Input_Tickers[i];
                    try { OBJECT_Actual_Ticker.Open = Securities[ARRAY_Input_Tickers[i]][Field.RegularMarketOpen]; } catch { }
                    try { OBJECT_Actual_Ticker.Current = Securities[ARRAY_Input_Tickers[i]][Field.RegularMarketPrice]; } catch { }
                    try { OBJECT_Actual_Ticker.High = Securities[ARRAY_Input_Tickers[i]][Field.RegularMarketDayHigh]; } catch { }
                    try { OBJECT_Actual_Ticker.Low = Securities[ARRAY_Input_Tickers[i]][Field.RegularMarketDayLow]; } catch { }
                    LIST_Tickers.Add(OBJECT_Actual_Ticker);
                }
                catch { }
            }

            return(LIST_Tickers);
        }
Beispiel #6
0
 public YahooStockModel GetStockDetails()
 {
     try
     {
         StockDetails[] stocks = new StockDetails[2];
         Task <IReadOnlyDictionary <string, Security> > task    = Yahoo.Symbols("FOLD", "GOOG").Fields(Field.Symbol, Field.LongName, Field.RegularMarketPrice, Field.RegularMarketChangePercent).QueryAsync();
         IReadOnlyDictionary <string, Security>         results = task.Result;
         int index = 0;
         foreach (Security security in results.Values)
         {
             StockDetails stock = new StockDetails()
             {
                 StockCode     = security[Field.Symbol],
                 Description   = security[Field.LongName],
                 CurrentPrice  = security[Field.RegularMarketPrice],
                 MarketChanges = security[Field.RegularMarketChangePercent]
             };
             stocks[index] = stock;
             index++;
         }
         return(new YahooStockModel()
         {
             Stocks = stocks
         });
     }
     catch
     {
         throw new WebException(@"There is an ERROR using Yahoo Finance API.");
     }
 }
Beispiel #7
0
        public static async Task DownloadAsync()
        {
            var symbols = DbHelper.GetUsaStockSymbols("select symbol from UsaStock");

            // You could query multiple symbols with multiple fields through the following steps:
            //var securities = await Yahoo.Symbols("AAPL", "GOOG").Fields(Field.Symbol, Field.RegularMarketPrice, Field.FiftyTwoWeekHigh).QueryAsync();
            // Sometimes, yahoo returns broken rows for historical calls, you could decide if these invalid rows is ignored or not by the following statement
            Yahoo.IgnoreEmptyRows = true;
            var batchSize        = 100;
            var totalSymbolCount = symbols.Count();

            //totalSymbolCount = 5;

            for (var index = 0; index < totalSymbolCount; index += batchSize)
            {
                var currentSymbols = symbols.Skip(index).Take(batchSize);
                var securities     = await Yahoo.Symbols(currentSymbols.ToArray()).QueryAsync();

                DbHelper.SaveToDatabase(securities);

                //sleep for some time
                System.Threading.Thread.Sleep(2000);
            }


            //var securities = await Yahoo.Symbols("AAPL", "GOOG").QueryAsync();
            //var aapl = securities["AAPL"];
            //var price = aapl[Field.RegularMarketPrice]; // or, you could use aapl.RegularMarketPrice directly for typed-value
        }
Beispiel #8
0
        public async Task TestQuoteAsync()
        {
            const string AAPL = "AAPL";

            var quote = await Yahoo.Symbols(AAPL).Fields(
                Field.RegularMarketOpen,
                Field.RegularMarketDayHigh,
                Field.RegularMarketDayLow,
                Field.RegularMarketPrice,
                Field.RegularMarketVolume,
                Field.RegularMarketTime)
                        .QueryAsync();

            var aaplQuote        = quote[AAPL];
            var aaplOpen         = aaplQuote[Field.RegularMarketOpen.ToString()];
            var aaplHigh         = aaplQuote[Field.RegularMarketDayHigh.ToString()];
            var aaplLow          = aaplQuote[Field.RegularMarketDayLow.ToString()];
            var aaplCurrentPrice = aaplQuote[Field.RegularMarketPrice.ToString()];
            var aaplVolume       = aaplQuote[Field.RegularMarketVolume.ToString()];
            var aaplTime         = aaplQuote[Field.RegularMarketTime.ToString()];

            // Get New York Timezone for conversion from UTC to New York Time for Yahoo Quotes
            TimeZoneInfo TzEst = TimeZoneInfo
                                 .GetSystemTimeZones()
                                 .Single(tz => tz.Id == "Eastern Standard Time" || tz.Id == "America/New_York");

            long     unixDate = 1568232001; // Any unix timestamp
            DateTime start    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            DateTime date     = start.AddSeconds(unixDate);
            DateTime estDate  = TimeZoneInfo.ConvertTimeFromUtc(date, TzEst);
        }
Beispiel #9
0
        public async Task TestQuery()
        {
            var securities = await Yahoo
                             .Symbols("C", "AAPL")
                             // Can use string field names:
                             .Fields("Bid", "Ask", "Tradeable", "LongName")
                             // and/or field enums:
                             .Fields(Field.RegularMarketPrice, Field.Currency)
                             .QueryAsync();

            Assert.Equal(2, securities.Count());
            var security = securities["C"];

            // Bid string or enum indexer returns dynamic type.
            security.Fields.TryGetValue("Bid", out dynamic bid);
            bid = security.Fields["Bid"];
            bid = security["Bid"];
            bid = security[Field.Bid];

            // Bid property returns static type.
            var bid2 = security.Bid;

            Assert.True(securities["C"][Field.Tradeable]);
            Assert.Equal("Apple Inc.", securities["AAPL"]["LongName"]);
        }
Beispiel #10
0
        /// <summary>
        /// Store the stock symbol in database for future retrieval.
        /// /// </summary>
        /// <param name="stockSymbol"></param>
        /// <returns></returns>
        public async Task <bool> StoreSymbolAsync(string stockSymbol)
        {
            IReadOnlyDictionary <string, Security> securities = new Dictionary <string, Security>();

            try {
                securities = await Yahoo.Symbols(stockSymbol).Fields(fieldList.ToArray()).QueryAsync();
            } catch {
                throw;
            }
            if (securities.Count.Equals(0))
            {
                throw new ArgumentException("Invalid stock symbol: " + stockSymbol);
            }
            var insNu = symbolCollection.Insert(new BsonDocument {
                ["Symbol"] = stockSymbol.ToUpper()
            });

            if (insNu != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #11
0
        public async Task <List <Candle> > GetHistoricalAsyn(string symbol, DateTime from, DateTime to)
        {
            var history = await Yahoo.GetHistoricalAsync("XELA", new DateTime(2016, 1, 1), new DateTime(2020, 7, 1), Period.Daily);

            var aaa = Yahoo.Symbols();

            return(history.ToList());
        }
Beispiel #12
0
        private static async Task callYahoo(string stockCode)
        {
            var securities = await Yahoo.Symbols(stockCode).Fields(Field.Symbol, Field.RegularMarketPrice).QueryAsync();

            var stk = securities[stockCode];

            sValue = Convert.ToString(stk.RegularMarketPrice);
        }
Beispiel #13
0
        public void MainLogic()
        {
            // Get the Symbol List
            LoadByCategory();

            // Overall Analysis
            foreach (var item in alls)// for each symbol
            {
                try
                {
                    var securities = Yahoo.Symbols(item.Key).Fields(Field.TrailingPE).QueryAsync().Result;
                    item.Value.TrailingPE = securities[item.Key].TrailingPE;
                }
                catch (Exception e)
                {
                    if (e.Message == "The given key was not present in the dictionary.")
                    {
                        continue;
                    }
                    throw;
                }
            }

            // Get their history data and generate feature
            foreach (var item in interested)// for each symbol
            {
                item.Value.HisData.Add(Yahoo.GetHistoricalAsync(item.Key, DateTime.Now.AddYears(-1 * lookBackYear), DateTime.Now).Result.ToList());

                CurrentPriceAnalysis(item);

                CycleAnlaysis(item);

                item.Value.Prepare();// Prepare to show
            }

            // Prepare the bought stocks data

            using (StreamReader sr = new StreamReader(File.OpenRead("Bought.txt")))
            {
                while (!sr.EndOfStream)
                {
                    string symbol = sr.ReadLine();
                    interested[symbol].IBoughtPrice            = double.Parse(sr.ReadLine());
                    interested[symbol].IBoughtAmount           = double.Parse(sr.ReadLine());
                    interested[symbol].IBoughtDate             = new DateTime(int.Parse(sr.ReadLine()), int.Parse(sr.ReadLine()), int.Parse(sr.ReadLine()));
                    interested[symbol].CurrentProfitPercentage = Math.Round(((double)interested[symbol].HisData[0].Last().Close - interested[symbol].IBoughtPrice) / interested[symbol].IBoughtPrice * 100, 2);
                    for (int i = 0; i < 7; i++)
                    {
                        double yes    = (double)interested[symbol].HisData[0][interested[symbol].HisData[0].Count - 1 - i].Close;
                        double yesyes = (double)interested[symbol].HisData[0][interested[symbol].HisData[0].Count - 2 - i].Close;
                        interested[symbol].ProfitPercentageComparedToBefore.Add(Math.Round((yes - yesyes) / yesyes * 100, 2));
                    }
                    interested[symbol].CurrentProfitAmount = Math.Round(interested[symbol].CurrentProfitPercentage * interested[symbol].IBoughtAmount * interested[symbol].IBoughtPrice / 100, 2);
                    interested[symbol].Bought = true;
                    bought.Add(symbol, interested[symbol]);
                }
            }
        }
Beispiel #14
0
        public static async Task <Security> GetQuoteAsync(string symbol)
        {
            // You could query multiple symbols with multiple fields through the following steps:
            var securities = await Yahoo.Symbols(symbol).QueryAsync();

            var quote = securities[symbol];

            return(quote);
        }
Beispiel #15
0
        public async Task <object> GetStockDetails(string symbol)
        {
            symbol = symbol.ToUpper();
            var result = await Yahoo.Symbols(symbol)
                         .Fields(Enum.GetValues <Field>())
                         .QueryAsync();

            return(result[symbol].Fields);
        }
        // Method to add alarms.
        private async void AddAlarm(object sender, RoutedEventArgs e)
        {
            string query = "INSERT INTO Alarm VALUES (@Ticker, @Price)";

            try
            {
                // Used for checking if the symbol is valid, else show message box.
                var securities = await Yahoo.Symbols(this.textBoxTicker.Text).Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketVolume, Field.RegularMarketOpen, Field.FiftyTwoWeekHigh).QueryAsync();

                var check = securities[this.textBoxTicker.Text];
                var price = check.RegularMarketVolume;

                bool alreadyExists = false;

                // Used to check if the alarm already exists, else show message box.
                using (connection = new SqlConnection(connectionString))
                    using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Alarm", connection))
                    {
                        DataTable alarmTable = new DataTable();
                        adapter.Fill(alarmTable);
                        foreach (DataRow row in alarmTable.Rows)
                        {
                            if (this.textBoxTicker.Text.Equals(row.Field <string>(1)) && double.Parse(this.textBoxPrice.Text) == row.Field <double>(2))
                            {
                                alreadyExists = true;
                            }
                        }
                    }

                // Add the alarm.
                if (!alreadyExists)
                {
                    using (connection = new SqlConnection(connectionString))
                        using (SqlCommand command = new SqlCommand(query, connection))
                        {
                            connection.Open();
                            command.Parameters.AddWithValue("@Ticker", this.textBoxTicker.Text);
                            command.Parameters.AddWithValue("@Price", decimal.Parse(this.textBoxPrice.Text));
                            command.ExecuteScalar();
                        }
                }
                else
                {
                    MessageBox.Show("Alarm for this target already exists.");
                }
            }
            catch
            {
                MessageBox.Show("Invalid Ticker symbol.");
            }

            this.textBoxPrice.Clear();
            this.textBoxTicker.Clear();
        }
Beispiel #17
0
        public static async Task <string> GetEntryPriceFromYahooAsync(string curr)
        {
            // You could query multiple symbols with multiple fields through the following steps:
            var securities = await Yahoo.Symbols(curr).Fields(Field.Currency, Field.RegularMarketPrice).QueryAsync();

            var aapl = securities[curr.ToUpper()].RegularMarketPrice;

            //var price = aapl.Values[Field.RegularMarketPrice];
            ss = aapl.ToString();
            return(ss);
        }
Beispiel #18
0
        public async Task Execute(MessageEnvelope env)
        {
            string        prepared = env.Raw.Content.TrimStart().ToLower();
            List <string> symbols  = new List <string>();
            StringBuilder str      = new StringBuilder();

            foreach (char c in prepared)
            {
                if (char.IsLetterOrDigit(c))
                {
                    str.Append(c);
                }
                else if (str.Length > 0)
                {
                    symbols.Add(str.ToString());
                    str.Clear();
                }
            }

            if (str.Length > 0)
            {
                symbols.Add(str.ToString());
            }

            var stocks = await Yahoo.Symbols(symbols.ToArray()).Fields(
                Field.Symbol,
                Field.LongName,
                Field.RegularMarketPrice,
                Field.RegularMarketChange,
                Field.RegularMarketChangePercent
                ).QueryAsync();

            foreach (Security stock in stocks.Values)
            {
                EmbedBuilder eb = new EmbedBuilder();
                eb.WithAuthor(author =>
                {
                    author.Name = stock.LongName;
                    author.Url  = $"https://finance.yahoo.com/quote/{stock.Symbol}";
                });
                eb.Title = stock.Symbol;
                eb.Color = (stock.RegularMarketChange > 0) ? Color.DarkGreen : Color.DarkRed;
                eb.WithFooter(footer =>
                {
                    footer.Text = "Yahoo Finance Quote";
                });
                eb.WithCurrentTimestamp();
                StringBuilder desc = new StringBuilder();
                desc.Append($"{stock.RegularMarketPrice.ToString("0.00")} ({Stocks.AddPlusOrMinus(stock.RegularMarketChange)} / {Stocks.AddPlusOrMinus(stock.RegularMarketChangePercent)}%)");

                eb.Description = desc.ToString();
                await env.Raw.Channel.SendMessageAsync(embed : eb.Build());
            }
        }
Beispiel #19
0
        static async Task GetData()
        {
            string[] faangm = { "FB", "AMZN", "AAPL", "NFLX", "GOOG", "MSFT" };

            IReadOnlyDictionary <string, Security> securities =
                await Yahoo.Symbols(faangm).Fields(Field.Symbol, Field.RegularMarketPrice).QueryAsync();

            foreach (var security in securities)
            {
                Console.WriteLine($"{security.Key}, {security.Value.RegularMarketPrice}");
            }
        }
Beispiel #20
0
        public async Task TestGetDataAsync2()
        {
            IReadOnlyDictionary <string, Security> securities =
                await Yahoo.Symbols(faang).Fields("Symbol", "RegularMarketPrice").QueryAsync();

            // Console.WriteLine($"{securities["AAPL"].Symbol}\n{securities["AAPL"].RegularMarketPrice}");

            foreach (var security in securities)
            {
                Console.WriteLine($"{security.Key}, {security.Value.RegularMarketPrice}");
            }
        }
Beispiel #21
0
        public async Task TestGetDataAsync()
        {
            IReadOnlyDictionary <string, Security> securities =
                await Yahoo.Symbols(faang).Fields(Field.Symbol, Field.RegularMarketPrice, Field.FiftyTwoWeekHigh).QueryAsync();

            var msft = securities["MSFT"];

            var symbol = msft[Field.Symbol];

            var price = msft[Field.RegularMarketPrice];

            Console.WriteLine($"{symbol}: {price}");
        }
Beispiel #22
0
        public static async Task <Tuple <double, double> > GetStockData(string ticker)
        {
            IReadOnlyDictionary <string, Security> securities = await Yahoo.Symbols(ticker).Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketOpen).QueryAsync();

            Security stock              = securities[ticker];
            double   regularMarketOpen  = stock.RegularMarketOpen;
            double   regularMarketPrice = stock.RegularMarketPrice;
            string   color              = regularMarketPrice > regularMarketOpen ? "green" : "red";

            Console.WriteLine($"regularMarketOpen: {regularMarketOpen} regularMarketPrice: {regularMarketPrice} color -> {color}");

            return(new Tuple <double, double>(regularMarketOpen, regularMarketPrice));
        }
Beispiel #23
0
        public Security GetSecurityStaticData(string symbol)
        {
            _logger.Information($"YahooFinanceApiManager: Retrieving static data for {symbol}");

            Task <IReadOnlyDictionary <string, Security> > marketDataTask = Yahoo
                                                                            .Symbols(symbol)
                                                                            .Fields(Field.Symbol, Field.ShortName, Field.Exchange, Field.FullExchangeName)
                                                                            .QueryAsync();

            marketDataTask.Wait();

            return(marketDataTask.Result[symbol]);
        }
Beispiel #24
0
        private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Declare stock and fields
                var securities = await Yahoo.Symbols(txtTicker.Text).Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketChange, Field.RegularMarketChangePercent, Field.LongName).QueryAsync();

                // Declare the stock
                var indexData = securities[txtTicker.Text];

                // Update textbox with the stock name
                txtName.Text = indexData.LongName;

                // Set validticker to true
                ValidTicker = true;

                // Declare xml file path
                var xmlFilePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyWatchlist\\data.xml");

                // Declare xml document and open
                var xdoc = XDocument.Load(xmlFilePath);

                // Declare location the the stock in xml file
                var hasElement = xdoc.Root.Elements("WATCHLIST").Where(y =>
                                                                       y.Element("NAME").Value == cbWL.SelectedItem.ToString()).Single()
                                 .Element("STOCKS").Elements("STOCK").Any(yy => yy.Element("TICKER").Value == txtTicker.Text);

                // If the location not exists add stock
                if (!hasElement)
                {
                    var xelement = new XElement(new XElement("STOCK", new XAttribute("list", cbWL.SelectedItem.ToString()), new XElement("NAME", txtName.Text), new XElement("TICKER", txtTicker.Text), new XElement("AVGPRICE", txtAvgPrice.Text), new XElement("SHARES", txtShares.Text)));
                    xdoc.Root.Elements("WATCHLIST").Where(x => x.Element("NAME").Value == cbWL.SelectedItem.ToString()).Single().Element("STOCKS").Add(xelement);

                    // Save xml file
                    xdoc.Save(xmlFilePath);

                    // Set dialogresult to true
                    this.DialogResult = true;
                }
                // If the location exists display error message
                else
                {
                    MessageBox.Show(txtTicker.Text + " already exists in " + cbWL.SelectedItem.ToString() + "!", "MyWatchlist", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception)
            {
                // If errors, disable add button
                ValidTicker = false;
            }
        }
Beispiel #25
0
        private async void GetData(string stock)
        {
            var securities = await Yahoo.Symbols(stock).QueryAsync();

            var company = securities[stock];


            double pe, dividendRate;
            string dividendDate;

            try
            {
                pe = company[Field.TrailingPE];
            }
            catch (KeyNotFoundException)
            {
                pe = 0;
            }

            try
            {
                dividendRate = company[Field.TrailingAnnualDividendRate];
            }
            catch (KeyNotFoundException)
            {
                dividendRate = 0;
            }

            try
            {
                dividendDate = DateTimeOffset.FromUnixTimeSeconds(company.DividendDate).ToString("MM/dd/yyyy");
            }
            catch (KeyNotFoundException)
            {
                dividendDate = "N/A";
            }

            StockListDG.Items.Add(new Stock()
            {
                Symbol                      = company.Symbol,
                Company                     = company.ShortName,
                Price                       = company[Field.RegularMarketPrice],
                TrailingPE                  = Math.Round(pe, 2),
                RegularMarketVolume         = company.RegularMarketVolume,
                RegularMarketChangePercent  = Math.Round(company.RegularMarketChangePercent, 2),
                TrailingAnnualDividendYield = Math.Round(dividendRate, 2),
                DividendDate                = dividendDate
            });
        }
Beispiel #26
0
        public async Task <StockSummary> GetStockQuote(string ticker)
        {
            var securities = await Yahoo.Symbols(ticker).Fields("Change", "ChangePercent").Fields(Field.RegularMarketChange, Field.RegularMarketChangePercent).QueryAsync();

            var security = securities[ticker.ToUpper()];

            security.Fields.TryGetValue(ticker, out dynamic key);
            StockSummary models = new StockSummary()
            {
                Ticker        = ticker,
                Change        = security.RegularMarketChange,
                ChangePercent = security.RegularMarketChangePercent
            };

            return(models);
        }
        // Get index prices and Market change percent
        async void GetIndexPrice()
        {
            // Declare tickers and fields
            var securities = await Yahoo.Symbols("^OMX", "^OMXSPI", "^IXIC", "^GSPC").Fields(Field.RegularMarketPrice, Field.RegularMarketChangePercent).QueryAsync();

            // Declare every index
            var omxData    = securities["^OMX"];
            var omxspiData = securities["^OMXSPI"];
            var nasdaqData = securities["^IXIC"];
            var spData     = securities["^GSPC"];

            // Add to each lbl
            lblOmx.Content    = "OMXS: " + omxData.RegularMarketPrice + "(" + Math.Round(omxData.RegularMarketChangePercent, 2) + "%)";
            lblOmxspi.Content = "OMXSPI: " + omxspiData.RegularMarketPrice + "(" + Math.Round(omxspiData.RegularMarketChangePercent, 2) + "%)";
            lblNasdaq.Content = "S&P 500: " + nasdaqData.RegularMarketPrice + "(" + Math.Round(nasdaqData.RegularMarketChangePercent, 2) + "%)";
            lblSp500.Content  = "Nasdaq: " + spData.RegularMarketPrice + "(" + Math.Round(spData.RegularMarketChangePercent, 2) + "%)";
        }
Beispiel #28
0
        public async Task <ApiStock?> GetStock(string?symbol)
        {
            symbol = symbol?.ToUpper();
            var result = await Yahoo.Symbols(symbol)
                         .Fields(Field.Symbol, Field.RegularMarketPrice, Field.FiftyTwoWeekHigh,
                                 Field.Currency,
                                 Field.FinancialCurrency,
                                 Field.LongName,
                                 Field.ShortName,
                                 Field.Language,
                                 Field.QuoteType)
                         .QueryAsync();

            if (!result.ContainsKey(symbol))
            {
                return(null);
            }

            var data  = result[symbol];
            var model = new ApiStock
            {
                Symbol    = data.Symbol,
                Market    = data.Market,
                Time      = DateTimeOffset.FromUnixTimeSeconds(data.RegularMarketTime).UtcDateTime,
                Timezone  = data.ExchangeTimezoneName,
                ShortName = data.ShortName,
                Currency  = data.Currency,
                Language  = data.Language,
                QuoteType = data.QuoteType
            };

            if (data.Fields.ContainsKey("LongName"))
            {
                model = model with {
                    LongName = data.LongName
                }
            }
            ;

            if (data.Fields.ContainsKey("FinancialCurrency"))
            {
                model.FinancialCurrency = data.FinancialCurrency;
            }

            return(model);
        }
Beispiel #29
0
        protected async Task <bool> insert(string symbols)
        {
            try
            {
                var securities = await Yahoo.Symbols(symbols).Fields(Field.Symbol, Field.RegularMarketPrice, Field.FiftyTwoWeekHigh, Field.RegularMarketDayLow, Field.RegularMarketVolume).QueryAsync();

                var aapl  = securities[symbols];
                var price = aapl[Field.RegularMarketPrice]; // or, you could use aapl.RegularMarketPrice directly for typed-value


                decimal marketprice = Convert.ToDecimal(price);



                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StockConnectionDB"].ConnectionString);
                con.Open();

                string     read    = "SELECT symbols from Compare Where symbols = @symbols";
                SqlCommand reading = new SqlCommand(read, con);
                reading.Parameters.AddWithValue("@symbols", symbols);
                SqlDataReader reader = reading.ExecuteReader();
                if (reader.Read())
                {
                    return(false);
                }
                else
                {
                    reader.Close();
                    string     insert = "insert into Compare (symbols, openstock, High, Low, Volume) values(@symbols, @openstock, @High, @Low, @Volume)";
                    SqlCommand cmd    = new SqlCommand(insert, con);
                    cmd.Parameters.AddWithValue("@symbols", symbols);
                    cmd.Parameters.AddWithValue("@openstock", aapl.RegularMarketPrice);
                    cmd.Parameters.AddWithValue("@High", aapl.RegularMarketDayHigh);
                    cmd.Parameters.AddWithValue("@Low", aapl.RegularMarketDayLow);
                    cmd.Parameters.AddWithValue("@Volume", aapl.RegularMarketVolume);
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        // Get stocks for each watchlist
        public async void GetWatchListStocks()
        {
            // If any watchlist exists
            if (cbLists.Items.Count > 0)
            {
                // Declare xml document and open
                var xdoc = XDocument.Load(xmlFileFullPath);

                // Declare watchlists location in xml document
                var watchlists = xdoc.Root.Descendants("WATCHLIST").Select(x => new Watchlist(x.Element("NAME").Value));

                // Declare stocks location in xml document
                var stocks = xdoc.Root.Descendants("STOCK").Select(x => new WatchlistStocks(x.Element("NAME").Value, x.Element("TICKER").Value, double.Parse(x.Element("AVGPRICE").Value.Replace(",", ".")), int.Parse(x.Element("SHARES").Value), x.Attribute("list").Value));

                // Clear WatchlistStocks list
                wlStocks.Clear();

                // Add every stock to respective watchlist
                foreach (var stock in stocks)
                {
                    // If stock parameter equals the selected watchlist, add to datagrid and listview
                    if (stock.watchlist.ToString() == cbLists.SelectedItem.ToString())
                    {
                        // Declare tickers and fields
                        var securities = await Yahoo.Symbols(stock.ticker).Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketChange, Field.RegularMarketChangePercent, Field.Currency).QueryAsync();

                        var stockData = securities[stock.ticker];

                        // Add stock to WatchlistStocks list
                        wlStocks.Add(new WatchlistStocks(stock.name, stock.ticker, stock.avgPrice, stock.shares, stock.watchlist, stockData.RegularMarketPrice, stockData.RegularMarketChange, stockData.RegularMarketChangePercent));

                        // Declare listview and datagrid source to WatchlistStocks list
                        lstStocks.ItemsSource = wlStocks;
                        dgStocks.ItemsSource  = wlStocks;

                        // Refresh datagrid and listview
                        dgStocks.Items.Refresh();
                        lstStocks.Items.Refresh();
                    }
                }
            }
            // Refresh datagrid and listview
            dgStocks.Items.Refresh();
            lstStocks.Items.Refresh();
        }