Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Monday, July 18, 2022

Forex REST JSON API with C#

 In this tutorial, we will help you set up your Visual Studio Code environment and write a program to request Live Forex data from TraderMade's REST API, parse that data, and output it to the console. If you already have your visual studio setup you can skip the first section of this tutorial and jump to the coding section or download a version of the code pre-populated with your API key. This tutorial covers the live endpoint but could be adapted to work for any of the endpoints with a few small adjustments.

First Up, We need to set up the environment

First up, download and install .NET Core SDK and then install Visual Studio Code. Now we need to set up and install the extension for c# to work in Visual Studio Code. Open visual studio code and select View->Extensions in the search box enter c#. There are lots of extension options but for this example, we will use the OmniSharp one. Click the install button.

Initialize you project

Now we can build the project to pull the live Forex data - In windows explorer create a new directory in your location of choice you can call this we are going to call this “crest” as this is a C# REST Example. Now in VSCode click the explorer tab and select the folder you just created.

Once this folder is loaded into VSCode we need to initialize a .net skeleton - this will create a project definition file (.csproj) and the main file (.cs) into which we create our code. 

Click View->Terminal and type the following command

Dotnet new console 

As standard, you will get a “Hello World” example. You may also get prompted to download any other assets that are needed to run the program, select ‘Yes’.

Install the NuGet

For this project we need to install a third-party NuGet to help with JSON parsing, First, we need to install the NuGet package manager. Select the extensions tab then enter NuGet into the search box and then click install.

Now we have the NuGet package manager installed we can install our helper libs. Press ‘F1’ to bring up the VS Command pallet. Now we can type ‘NuGet and you will see the command “NuGet Package Manager Add Package” 

This will then prompt for a package name, we are going to use “Newtonsoft.Json” type this press enter to select the matching package and then the latest version.

Get your API key

The last thing you need for this program is your TraderMade API Key if you don’t have one you can register from signup page then you can copy it from your dashboard once you log in.

Ok, Let’s write some code.

First, we need to add some using statements, the first being the standard system the second System.Net.Http is for the call to the REST server and the 3rd Newtonsoft.Json is a helper lib for parsing the JSON data returned.

using System;
Using System.Net.Http;
Using Newtonsoft.Json;

Now we create an HttpClient for our call to the server and make a call to the REST service for live data.

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://marketdata.tradermade.com/api/v1/live?currency=EURUSD,GBPUSD&api_key=ENTER_YOUR_API_KEY");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();

The output from this code is a JSON string containing our data, now we can use Newtonsoft to parse this.

The data returned from the server contains request information and then an array of market data so we need 2 classes to parse the returned data.

The CurrencyDetails class

public class CurrencyDetails
{
       public string endpoint { get; set; }
       public quotes[] quotes { get; set; }
       public string requested_time { get; set; }
       public long timestamp { get; set; }
}

The quote class;

public class quotes
{
        public double ask { get; set; }
        public double bid { get; set; }
        public string base_currency { get; set; }
        public double mid { get; set; }
        public string quote_currency { get; set; }
}

       

Once we have these classes defined we can parse the data into an easy-to-use object. In the following code, we parse the data and iterate through the result, and output the data for the quotes.

var result = JsonConvert.DeserializeObject(responseBody);
foreach (var item in result.quotes)
{
         Console.WriteLine(" Result: " +  item.base_currency + "/" +  item.quote_currency + " " + item.mid);
}

and now we can put it all together

using System;
using System.Net.Http;
using Newtonsoft.Json;

namespace crest
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync("https://marketdata.tradermade.com/api/v1/live?currency=EURUSD,GBPUSD&api_key=ENTER_YOUR_API_KEY");
            response.EnsureSuccessStatusCode();
            var responseBody = await response.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject(responseBody);
            foreach (var item in result.quotes)
            {
                            Console.WriteLine(" Result: " +  item.base_currency + "/" +  item.quote_currency + " " + item.mid);

            }
        }

        public class CurrencyDetails
        {
                public string endpoint { get; set; }
                public quotes[] quotes { get; set; }
                public string requested_time { get; set; }
                public long timestamp { get; set; }

        }

        public class quotes
        {
            public double ask { get; set; }
            public double bid { get; set; }
            public string base_currency { get; set; }
            public double mid { get; set; }
            public string quote_currency { get; set; }
        }



    }
}

And that's it! you now have a c# program that can request live forex rates from the TraderMade REST service.

 

 

 

 

 

 

No comments:

Post a Comment