DEV Community

Cover image for Forex REST JSON API with C#
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on • Edited on

Forex REST JSON API with C#

This tutorial shows you how to set up Visual Studio Code and create a program that will ask TraderMade for Live Forex data, parse it, and send it to the console. You can skip the first section of this lesson and go straight to the coding section if you already have Visual Studio configured. If not, you can get a copy of the code from our C# REST Example that has already been pre-filled with your API key. With a few minor tweaks, this tutorial, which focuses on the live endpoint, may be modified to work for any other endpoint.

Initially, The environment needs to be prepared.
Install Visual Studio Code after downloading and installing the.NET Core SDK. For C# to function in Visual Studio Code, we must configure and install the extension. Open Visual Studio Code, go to View->Extensions, and type C# in the search bar. There are other extension possibilities, yet here we'll utilize the OmniSharp one. Select "Install" from the menu.

Image description

Begin your project.
Now that we have the project built, we can pull the live Forex data. Create a new directory in your preferred location in Windows Explorer. Any name will do for this. Since this is a C# REST example, we will call this "crest." Select the newly created folder by clicking the explorer tab in VSCode.

Image description

We must initialize a .net skeleton once this folder has been loaded into VSCode; doing so will produce a project specification file (.csproj) and the main file (.cs) into which we can enter our code.
Enter the following command after selecting View->Terminal:

Dotnet new console
Enter fullscreen mode Exit fullscreen mode

Image description

You will receive a "Hello World" sample as is customary. You might also be prompted to download any additional files required for the application to function. Choose "Yes."

Put in the NuGet

We must install a third-party NuGet to assist with JSON parsing for this project. Installing the NuGet package management is the first step. Enter NuGet in the search box on the extensions tab, then click install.

Image description

The NuGet package manager is now installed. Our auxiliary libraries can be installed. To see the VS Command Palette, press "F1". When we type NuGet now, the "NuGet Package Manager Add Package" command appears.

Image description

Following that, a package name prompt will appear. We will use "Newtonsoft.Json." Type this package name, click enter to select the appropriate package, and then the latest version.

Image description

Obtain your API key
Your TraderMade API Key is the final component of this software that you require. Register on our signup page if you don't already have an account. Once you log in, you can copy it from your dashboard.

Let's write some code now.
We must first add a few using statements:
The 'standard system' is the first,
while the second is the 'system.Net.HTTP.' It is for calling the REST server.
Newtonsoft.Json is the 3rd aspect, which is a helper lib. It parses the JSON data returned from the server.

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

Enter fullscreen mode Exit fullscreen mode

Now we call the REST API for live data using a HttpClient that we created for the server call.

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();

Enter fullscreen mode Exit fullscreen mode

This function produces a JSON string with our data as its output. Now we can parse this using Newtonsoft.

Information about the request is included in the data the server has returned, followed by various market statistics. To parse the returned data, we, therefore, require two classes.
The class CurrencyDetails

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; }
}

Enter fullscreen mode Exit fullscreen mode

After defining these classes, we may parse the data into a usable object. We parse the data, loop through the outcome, and output the data for the quotes in the following code.

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

Enter fullscreen mode Exit fullscreen mode

We can now put everything 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<CurrencyDetails>(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; }
        }



    }
}

Enter fullscreen mode Exit fullscreen mode

That's all, then! You now have a C# program that can ask the TraderMade REST service for live currency rates.

TraderMade provides reliable and accurate Forex data via Forex API. You can sign up for a free API key and start exploring real-time and historical data at your fingertips.

If you are curious about retrieving real-time forex rates via WebSockets with C#, the following tutorial will help you:
Real-Time Market Data via WebSocket with C#

Along with that, here are tutorials to fetch market data via REST API with other popular programming languages:

  1. C++ REST API Client

  2. Forex REST JSON with Java

  3. Forex REST JSON API with PHP

Top comments (0)