Get currency exchange rates in C#

[currency exchange rates]


This example shows how you can get currency exchange rates from finance.yahoo.com. When it starts, the program uses the following code to get the currency exchange rates.

// Get the currency symbols.
private void Form1_Load(object sender, EventArgs e)
{
    string url = "http://finance.yahoo.com/webservice/" +
        "v1/symbols/allcurrencies/quote?format=xml";
    try
    {
        // Load the data.
        XmlDocument doc = new XmlDocument();
        doc.Load(url);

        // Process the resource nodes.
        XmlNode root = doc.DocumentElement;
        string xquery = "descendant::resource[@classname='Quote']";
        foreach (XmlNode node in root.SelectNodes(xquery))
        {
            const string name_query =
                "descendant::field[@name='name']";
            const string price_query =
                "descendant::field[@name='price']";
            string name =
                node.SelectSingleNode(name_query).InnerText;
            string price =
                node.SelectSingleNode(price_query).InnerText;
            decimal inverse = 1m / decimal.Parse(price);

            ListViewItem item = lvwPrices.Items.Add(name);
            item.SubItems.Add(price);
            item.SubItems.Add(inverse.ToString("f6"));
        }

        // Sort.
        lvwPrices.Sorting = SortOrder.Ascending;
        lvwPrices.FullRowSelect = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Read Error",
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
}

This code loads an XmlDocument from the following url.

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=xml

You can execute this URL in your browser to see what the result looks like. The following text shows what an entry that holds currency exchange rates looks like.

<resource classname="Quote">
  <field name="name">USD/KRW</field>
  <field name="price">1169.650024</field>
  <field name="symbol">KRW=X</field>
  <field name="ts">1480609630</field>
  <field name="type">currency</field>
  <field name="utctime">2016-12-01T16:27:10+0000</field>
  <field name="volume">0</field>
</resource>

Next the code finds the document’s root node and uses its SelectNodes method to make a list of nodes that have the tag type resource and that have a field named classname with value Quote. The program uses a while loop to iterate through the resulting nodes.

Inside the loop, the code gets the Quote node’s descendants of type field with name name and price. It saves their text contents in variables name and price.

I think the names of the currency exchange rates are a bit misleading. For example, USD/JPY is the exchange rate between US dollars and Japanese yen. Currently the price is 114.528, which means one USD is worth 114.528 JPY. But mathematically the name USD/JPY means “dollars per yen” not “yen per dollar.”

To make the exchanges a bit easier to read, the program parses the price and inverts it so you can see the number of dollars per yen and the number of yen per dollar.

The loop displays the name, price, and inverted price in the ListView control lvwPrices.

The code finishes by sorting the ListView values (they are not sorted in the XML data) and making the ListView select full rows when you click on it.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in finance, internet, mathematics, web and tagged , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

3 Responses to Get currency exchange rates in C#

  1. Mariano says:

    For me Rod is the best developer c# into the world. Congratulation Rod, fantastic article. Best regards, Mariano, from Sardinia, Italy!

    • RodStephens says:

      Thanks, Mariano. It’s always nice to hear that someone is getting some use out of this stuff!

      • Mariano says:

        I always followed you with great interest. We have implemented in our open source project some of your techniques. You will be cited and thanked when the project will be available to users. Thanks Rod, is a pleasure to follow you! Saludoso dae Sardigna!

Leave a Reply

Your email address will not be published. Required fields are marked *