The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

CurrencyHelper.cs 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. namespace Teknik.Utilities
  8. {
  9. public static class CurrencyHelper
  10. {
  11. private static decimal m_CurrentBTCPrice = 0;
  12. private static DateTime m_LastBTCQuery = DateTime.MinValue;
  13. private static TimeSpan m_MaxBTCQueryTime = new TimeSpan(1, 0, 0); // Max query of every hour
  14. /// <summary>
  15. /// Gets the exchange rate for a given currency relative to USD
  16. /// </summary>
  17. /// <param name="target"></param>
  18. /// <returns></returns>
  19. public static decimal GetExchangeRate(CurrencyType target)
  20. {
  21. decimal exchangeRate = 1;
  22. switch (target)
  23. {
  24. case CurrencyType.USD:
  25. exchangeRate = 1;
  26. break;
  27. case CurrencyType.BTC:
  28. // get BTC usd price
  29. exchangeRate = GetBTCPrice();
  30. break;
  31. }
  32. return exchangeRate;
  33. }
  34. public static decimal GetBTCPrice()
  35. {
  36. DateTime curTime = DateTime.Now;
  37. if (curTime - m_LastBTCQuery > m_MaxBTCQueryTime)
  38. {
  39. m_LastBTCQuery = curTime;
  40. string url = "http://api.bitcoincharts.com/v1/weighted_prices.json";
  41. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  42. try
  43. {
  44. WebResponse response = request.GetResponse();
  45. using (Stream responseStream = response.GetResponseStream())
  46. {
  47. StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
  48. string jsonResult = reader.ReadToEnd();
  49. JObject result = JsonConvert.DeserializeObject<JObject>(jsonResult);
  50. if (result["USD"] != null)
  51. {
  52. string priceStr = result["USD"]["24h"].ToString();
  53. decimal.TryParse(priceStr, out m_CurrentBTCPrice);
  54. }
  55. }
  56. }
  57. catch (WebException ex)
  58. {
  59. WebResponse errorResponse = ex.Response;
  60. using (Stream responseStream = errorResponse.GetResponseStream())
  61. {
  62. StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
  63. String errorText = reader.ReadToEnd();
  64. }
  65. }
  66. }
  67. return m_CurrentBTCPrice;
  68. }
  69. }
  70. }