43 lines
2.2 KiB
C#
43 lines
2.2 KiB
C#
using CH.CryptoStats.Abstractions;
|
|
using Microsoft.Extensions.Configuration;
|
|
using System.Text.Json;
|
|
namespace CH.CryptoStats.CoinMarketCap;
|
|
|
|
public class CoinMarketCap(HttpClient httpClient, IConfiguration configuration) : ICryptoStats
|
|
{
|
|
public Task<Abstractions.CryptoStats> GetCryptoStats(string cryptoName, string currency, CancellationToken cancellationToken)
|
|
{
|
|
var apiKey = configuration.GetValue<string>("CoinMarketCap:ApiKey");
|
|
var apiUrl = configuration.GetValue<string>("CoinMarketCap:ApiUrl");
|
|
var result = httpClient.GetAsync($"{apiUrl}slug={cryptoName}&convert={currency}&CMC_PRO_API_KEY={apiKey}",cancellationToken).Result;
|
|
return ParseCryptoStats(result, currency, cancellationToken);
|
|
|
|
}
|
|
|
|
public Task<Abstractions.CryptoStats> ParseCryptoStats(HttpResponseMessage result, string currency, CancellationToken cancellationToken)
|
|
{
|
|
var jsonResponse = result.Content.ReadAsStringAsync(cancellationToken);
|
|
var jsonDocument = JsonDocument.Parse(jsonResponse.Result);
|
|
var data = jsonDocument.RootElement.GetProperty("data");
|
|
var cryptoElement = data.GetProperty("1");
|
|
var quoteElement = cryptoElement.GetProperty("quote").GetProperty("CAD");
|
|
var cryptoStats = new Abstractions.CryptoStats
|
|
{
|
|
Name = cryptoElement.GetProperty("name").GetString(),
|
|
Symbol = cryptoElement.GetProperty("symbol").GetString(),
|
|
MaxSupply = cryptoElement.GetProperty("max_supply").GetInt32(),
|
|
CirculatingSupply = cryptoElement.GetProperty("circulating_supply").GetInt32(),
|
|
TotalSupply = cryptoElement.GetProperty("total_supply").GetInt32(),
|
|
Currency = currency,
|
|
UpdatedAt = DateTime.Parse(quoteElement .GetProperty("last_updated").GetString()),
|
|
Price = quoteElement .GetProperty("price").GetDecimal(),
|
|
Volume24H = quoteElement .GetProperty("volume_24h").GetDecimal(),
|
|
VolumeChange24H = quoteElement .GetProperty("volume_change_24h").GetDecimal(),
|
|
MarketCap = quoteElement .GetProperty("market_cap").GetDecimal(),
|
|
MarketCapDominance = quoteElement .GetProperty("market_cap_dominance").GetDecimal(),
|
|
FullyDilutedMarketCap = quoteElement .GetProperty("fully_diluted_market_cap").GetDecimal()
|
|
};
|
|
return Task.FromResult(cryptoStats);
|
|
}
|
|
}
|