public async Task GetPriceHistoryAsync(CancellationToken cancellationToken) { _logger.LogInformation("GetPriceHistoryAsync started {now}", DateTime.Now); long start; long end; DateTime dateTime; int count; StockCandles stockCandle; IAsyncEnumerable <Models.TdAmeritrade.Account.Instrument> instruments; _dataAdapter.JsonSerializerOptions = new(); _dataAdapter.JsonSerializerOptions.PropertyNameCaseInsensitive = true; dateTime = new DateTime(2015, 1, 1); instruments = _dataAdapter.StocksDbContext.Instrument; await foreach (Instrument instrument in instruments) { try { using StocksDbContext stocksDbContext = _dataAdapter.StocksDbContextFactory.CreateDbContext(); count = stocksDbContext.PriceHistory.Count(x => x.Exchange == instrument.Exchange && x.Symbol == instrument.Symbol); start = count > 0 ? new DateTimeOffset(stocksDbContext.PriceHistory.Where(x => x.Exchange == instrument.Exchange && x.Symbol == instrument.Symbol).OrderBy(x => x.DateTime).Last().DateTime.Date).AddDays(1).ToUnixTimeMilliseconds() : new DateTimeOffset(dateTime).ToUnixTimeMilliseconds(); end = DateTimeOffset.Now.ToUnixTimeMilliseconds(); _dataAdapter.Json = await Requester.SendRequestAsync(Enums.HttpVerb.Get, $"{_dataAdapter.Settings["MarketDataUri"]}/{instrument.Symbol}/pricehistory?apikey={_dataAdapter.Settings["ApiKey"]}&periodType=year&frequencyType=daily&startDate={start}&endDate={end}", null, cancellationToken); _dataAdapter.Json = Toolbox.Json.RemoveEntry(_dataAdapter.Json, "NaN"); stockCandle = JsonSerializer.Deserialize <StockCandles>(_dataAdapter.Json, _dataAdapter.JsonSerializerOptions); if (stockCandle.Empty) { _logger.LogInformation("GetPriceHistoryAsync empty {exchange} {symbol}", instrument.Exchange, instrument.Symbol); } else { await stocksDbContext.AddRangeAsync(stockCandle.Candles.Select(x => new PriceHistory() { Symbol = instrument.Symbol, DateTime = DateTime.UnixEpoch.AddMilliseconds(x.DateTime), Exchange = instrument.Exchange, Open = x.Open, Close = x.Close, High = x.High, Low = x.Low, Volume = x.Volume, //Instrument = instrument, Updated = DateTime.UtcNow }).OrderBy(x => x.DateTime), cancellationToken); await stocksDbContext.SaveChangesAsync(cancellationToken); _logger.LogInformation("GetPriceHistoryAsync added {exchange} {symbol}", instrument.Exchange, instrument.Symbol); } } catch (Exception exception) { _logger.LogWarning("GetPriceHistoryAsync {exchange} {symbol} {message}", instrument.Exchange, instrument.Symbol, exception.Message); } } _logger.LogInformation("GetPriceHistoryAsync completed {now}", DateTime.Now); }