giovedì 5 maggio 2016

WebService gratuiti per valute e Bitcoin con c#

Ero alla ricerca di alcuni WebService o API gratuite (difficili a trovarli, spesso 'api' a pagamento oppure previa registrazione) con cadenza giornaliera, per avere una tabella delle valute del database sempre aggiornata.
Quindi dovevo trovare importi in sterline, yen, dollari e soprattutto Bitcoin (avere una stima) pronti ad essere convertiti in Euro.
L'esempio seguente mostra come aggiornare le valute in una tabella (Tab_Valuta) calcolando poi il corrispettivo in Euro.
I link scelti per le valute e Bitcoin sono: http://www.ecb.europa.eu e https://cex.io
Navigando su questi siti si possono vedere meglio le modalità di richiamo dei vari servizi.
Altri link utili (ma bisogna registrarsi per lavorare con le API) sono https://it.bitstamp.net/ e https://btc-e.com/
N.B. Ho portato tutto in tipo stringa perchè possono esserci problemi con i decimali e quindi con il tipo internazionale delle valute scelto sul server.

class Program
{
static string dollar = "0";
static string gbp = "0";
static string yen = "0";
static string btc = "0";

static void Main(string[] args)
{
Conversion();
UpdateCurrency();
}

private static void UpdateCurrency()
{
  string SQL = "";
  if(Convert.ToDouble(dollaro)>0)
  SQL += "update Tab_Valuta set Cambio=cast('" + dollar + "' as numeric(18,5)) where id_valuta=1; ";

  if (Convert.ToDouble(sterlina) > 0)
  SQL += "update Tab_Valuta set Cambio=cast('" + gbp + "' as numeric(18,5)) where id_valuta=3; ";

  if (Convert.ToDouble(yen) > 0)
  SQL += "update Tab_Valuta set Cambio=cast('" + yen + "' as numeric(18,5)) where id_valuta=4;";

  if (Convert.ToDouble(btc) > 0)
  SQL += "update Tab_Valuta set Cambio=cast('" + btc + "' as numeric(18,5)) where id_valuta=5;";

  SqlConnection con = new SqlConnection();
  try
  {
    string dbConString = ConfigurationManager.ConnectionStrings["ConnectionDB"].ConnectionString;

    con.ConnectionString = dbConString;
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = SQL;
    cmd.ExecuteNonQuery();
  }
  catch (Exception ex)
  {
  }
  finally
  {
  con.Close();
  }
}

private static void Conversion()
{
XmlDocument doc = new XmlDocument();
try
{
  doc.Load("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

  //normal currency
  foreach (XmlNode node in doc.DocumentElement.ChildNodes)
  {
    foreach (XmlNode locNode in node)
    {
      if (locNode.Name.Equals("Cube"))
      {
        foreach (XmlNode locNode2 in locNode)
        {
            if (locNode2.Attributes["currency"].Value == "USD")
            {
            dollar = locNode2.Attributes["rate"].Value.Replace(",", ".");
            }
            if (locNode2.Attributes["currency"].Value == "GBP")
            {
            gbp = locNode2.Attributes["rate"].Value.Replace(",", ".");
            }
            if (locNode2.Attributes["currency"].Value == "JPY")
            {
            yen = locNode2.Attributes["rate"].Value.Replace(",", ".");
            }
        }
      }
    }
  }
}
catch (Exception ex)
{}

//Bitcoin
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://cex.io/api/last_price/BTC/EUR");
Price m = JsonConvert.DeserializeObject(json);
btc = Convert.ToString( 1 / Convert.ToDouble(m.LPrice));
}
}
}
class Price
{
[JsonProperty("lprice")]
public String LPrice { get; set; }
}