I am making a UI where a user enters a stock symbol/ticker and presses a button to get data on the stock like open price, high, low, and closing price. I am using this all through the Alpha Vantage API. This link shows the JSON data of the API call I am using in this question on a daily basis for the last 100 days on the Microsoft stock. In order to get each of the last 100 business days (or weekdays: Monday-Friday) from today, I use this C# code:
public List<DateTime> GetDatesBetween(DateTime start, DateTime end, params DayOfWeek[] weekdays)
{
bool allDays = weekdays == null || !weekdays.Any();
var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.Where(d => allDays || weekdays.Contains(d.DayOfWeek))
.ToList();
return dates;
}
And then I iterate through the list values of the GetDatesBetween()
function, passing the properly-formatted dates in the JObject.Parse()
method for retrieving the JSON from the RestSharp client's GET request:
using RestSharp;
using Newtonsoft.Json.Linq;
using FluentDateTime;
var client = new RestClient(String.Format("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={0}&apikey={1}",
TextBox89.Text, "MY_API_KEY"));
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
List<DateTime> lst = GetDatesBetween(DateTime.Now.SubtractBusinessDays(100), DateTime.Now,
DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday);
foreach (var date in lst)
{
var open = JObject.Parse(response.Content)["Time Series (Daily)"][date.ToString("yyyy-MM-dd")]["1. open"];
}
Except I keep getting "System.NullReferenceException: Object reference not set to an instance of an object" for this line:
var open = JObject.Parse(response.Content)["Time Series (Daily)"][date.ToString("yyyy-MM-dd")]["1. open"];
I checked the output of the date.ToString("yyyy-MM-dd")
code, and it is in parallel with the format of the JSON from Alpha Vantage, like with today being "2020-01-12". I also tried putting in a date string myself, and it worked:
var open = JObject.Parse(response.Content)["Time Series (Daily)"]["2020-01-10"]["1. open"];
What am I doing wrong? Is there some syntax issue with the string? Sorry if this complex problem seems off-topic, but I'd really appreciate some help since this is getting awfully frustrating lately. Please refer to the link above on the JSON in order to help me with this issue.