如何在 ASP.NET C# 中获取相应美元价值的比特币价值?

How to get Bitcoin value for corresponding USD value in ASP.NET C#?

我想获取相应美元价值的比特币价值并将其存储在 table 或变量中。我得到了这个 URL,我可以从中获得 USK 金额的比特币价值。我在区块链上搜索并找到了这个 URL.

例如:

500usd = 0.76105818 btc

我试过了:

https://blockchain.info/tobtc?currency=USD&value=500

最后,我们要将其转换为比特币的美元价值。 我想在 C#(后端)中的变量中获取结果。

我怎样才能做到这一点?

您只需调用服务器并解析响应即可。

var uri = String.Format("https://blockchain.info/tobtc?currency=USD&value={0}", 500);

WebClient client = new WebClient();
client.UseDefaultCredentials = true;
var data = client.DownloadString(uri);

var result = Convert.ToDouble(data);

安装包 CoinMarketCapClient

使用 CoinMarketCap;

public static async Task<double> GetBitcoinInUsd(double usd){
            //https://api.coinmarketcap.com/v1/ticker/bitcoin/
            CoinMarketCapClient client = CoinMarketCapClient.GetInstance();
            var entity = await client.GetTickerAsync("bitcoin");
            return entity.PriceUsd * usd;
}

var uri = String.Format(@"https://blockchain.info/tobtc?currency=USD&value={0}",1);

WebClient 客户端 = new WebClient();

client.UseDefaultCredentials = 真;

var 数据 = client.DownloadString(uri);

var 结果 = 1/Convert.ToDouble(data.Replace('.',',')); //你将收到 1 btc = result;

有几个 API 可以让您请求加密货币列表的价格,and/or 法定货币。问题是所有 API 都以完全不同的方式进行。随之而来的是,任何人都可能在任何给定时间出现故障,因此您需要内置一些容错能力。即代码应尝试使用一个 API,如果失败,则移至下一个。当然,由于价格是主观的并且受特定国家、交易所等因素影响,这使情况变得更加复杂。因此,获得准确的值非常困难。

这是来自 CryptoCurrency.Net (https://github.com/MelbourneDeveloper/CryptoCurrency.Net/blob/master/src/CryptoCurrency.Net/APIClients/PriceEstimationClients/CryptoCompareClient.cs) 的示例 Crypto Compare 客户端:

public class CryptoCompareClient : PriceEstimationClientBase, IPriceEstimationClient
    {
        public CryptoCompareClient(IRestClientFactory restClientFactory) : base(restClientFactory)
        {
            RESTClient = restClientFactory.CreateRESTClient(new Uri("https://min-api.cryptocompare.com"));
        }

        protected override Func<GetPricesArgs, Task<EstimatedPricesModel>> GetPricesFunc { get; } = async a =>
        {
            var retVal = new EstimatedPricesModel();

            if (a.Currencies.ToList().Count == 0)
            {
                return retVal;
            }

            retVal.LastUpdate = DateTime.Now;

            var symbolsPart = string.Join(",", a.Currencies.Select(c => c.Name));

            var priceJson = await a.RESTClient.GetAsync<string>($"data/pricemultifull?fsyms={symbolsPart}&tsyms={a.FiatCurrency}");

            var jObject = (JObject)JsonConvert.DeserializeObject(priceJson);

            var rawNode = (JObject)jObject.First.First;

            foreach (JProperty coinNode in rawNode.Children())
            {
                var fiatNode = (JProperty)coinNode.First().First;

                var allProperties = fiatNode.First.Children().Cast<JProperty>().ToList();

                var change24HourProperty = allProperties.FirstOrDefault(p => string.Compare(p.Name, "CHANGEPCT24HOUR", true) == 0);
                var priceProperty = allProperties.FirstOrDefault(p => string.Compare(p.Name, "PRICE", true) == 0);

                var price = (decimal)priceProperty.Value;
                var change24Hour = (decimal)change24HourProperty.Value;
                retVal.Result.Add(new CoinEstimate { CurrencySymbol = new CurrencySymbol(coinNode.Name), ChangePercentage24Hour = change24Hour, FiatEstimate = price, LastUpdate = DateTime.Now });
            }

            //Extreme hack. It's better to show zero than nothing at all and get the coins stuck
            foreach (var currency in a.Currencies)
            {
                if (retVal.Result.FirstOrDefault(ce => ce.CurrencySymbol.Equals(currency)) == null)
                {
                    retVal.Result.Add(new CoinEstimate { ChangePercentage24Hour = 0, CurrencySymbol = currency, FiatEstimate = 0, LastUpdate = DateTime.Now });
                }
            }

            return retVal;
        };
}

PriceEstimationManager 将快速浏览 API 秒,直到找到一个有效的 (https://github.com/MelbourneDeveloper/CryptoCurrency.Net/blob/master/src/CryptoCurrency.Net/APIClients/PriceEstimationClients/PriceEstimationManager.cs):

public class PriceEstimationManager
{
    #region Fields
    private readonly Collection<IPriceEstimationClient> _Clients = new Collection<IPriceEstimationClient>();
    #endregion

    #region Constructor
    public PriceEstimationManager(IRestClientFactory restClientFactory)
    {
        foreach (var typeInfo in typeof(PriceEstimationManager).GetTypeInfo().Assembly.DefinedTypes)
        {
            var type = typeInfo.AsType();

            if (typeInfo.ImplementedInterfaces.Contains(typeof(IPriceEstimationClient)))
            {
                _Clients.Add((IPriceEstimationClient)Activator.CreateInstance(type, restClientFactory));
            }
        }
    }
    #endregion

    #region Public Methods

    /// <summary>
    /// TODO: This needs to be averaged. The two current clients give wildly different values. Need to include some Australian exchanges etc.
    /// </summary>
    public async Task<EstimatedPricesModel> GetPrices(IEnumerable<CurrencySymbol> currencySymbols, string fiatCurrency)
    {
        //Lets try a client that hasn't been used before if there is one
        var client = _Clients.FirstOrDefault(c => c.AverageCallTimespan.TotalMilliseconds == 0);
        var currencies = currencySymbols.ToList();
        if (client != null)
        {
            try
            {
                return await client.GetPrices(currencies, fiatCurrency);
            }
            catch
            {
                //Do nothing
            }
        }

        foreach (var client2 in _Clients.OrderBy(c => c.SuccessRate).ThenBy(c => c.AverageCallTimespan).ToList())
        {
            try
            {
                return await client2.GetPrices(currencies, fiatCurrency);
            }
            catch (Exception ex)
            {
                Logger.Log("Error Getting Prices", ex, nameof(PriceEstimationManager));
            }
        }

        throw new Exception("Can't get prices");
    }
    #endregion
}

在更高层次上,您可以使用这样的代码 (https://github.com/MelbourneDeveloper/CryptoCurrency.Net/blob/master/src/CryptoCurrency.Net.UnitTests/PricingTests.cs):

public async Task GetUSDBitcoinPrice()
{
    var priceEstimationManager = new PriceEstimationManager(new RESTClientFactory());
    var estimatedPrice = await priceEstimationManager.GetPrices(new List<CurrencySymbol> { CurrencySymbol.Bitcoin }, "USD");
    Console.WriteLine($"Estimate: {estimatedPrice.Result.First().FiatEstimate}");
}

随着越来越多的定价客户加入,它会变得越来越可靠。