Real-Time Forex, CFD and Crypto WebSocket with C#

11/05/2021 at 09:58AM


In this tutorial, you will learn how to set up a Visual Studio Coding environment and code a program in C#. You will also learn how to connect to a WebSocket service (in this case Tradermade's Forex data feed) and get streaming data (Forex, CFD, and Crypto) in real-time and parse JSON output. If you have previous experience with Visual Studio setup you can jump straight to the coding bit of this tutorial. You can also download a version of the code pre-populated with your API key from the documentation section of the website C# WebSocket Example. This tutorial covers a small number of currencies but TraderMade offers WebSocket with more than 1500 currency pairs.


Let's set up the development environment

Download and install Visual studio code from https://code.visualstudio.com/download and .NET Core SDK. Then we need to install and set up the extension for C# to work in VS Code. Open Visual Studio Code and select View -> Extension in the search box enter C#. There are lots of extension options available but for this code, for example, select the OmniSharp one, Select the install button.


Setup the project

Now we need to build the project to connect to the WebSocket - In windows explorer, create a new directory, you can call this anything that you like but for this example, we are going to call it "csWebsocket" as this is a C# WebSocket example. Now open VSCode and select File -> Open Folder and select the folder you just created.


Now the folder is open in VSCode we need to create the .net skeleton - this will establish the project definition file (.csproj) and the main file (.cs) into which we will copy our code.

Click View -> Terminal and type the following command.

Dotnet new console

By default, the project will populate with a “Hello World” example. You may also get prompted to download any other assets that are needed to run the program, select ‘Yes’. If you did not get a prompt just press "CTRL+SHIFT+X".


Install the NuGet

We need to install the NuGet via the package manager, select the extension tab then enter the NuGet into the search box and click install. The NuGet library helps in parsing the JSON received over the WebSocket.

Once we have the NuGet package manager installed we can install our helper libs. Press ‘F1’ (or FN + F1 on Windows) to bring up the VS Command pallet. Now first type ‘NuGet and click on the command: “ NuGet Package Manager Add Package”.

This will then prompt another search box, we are going to write “Newtonsoft.JSON” in that box as shown below and then will press enter to select the matching package and then the latest version at the top.

Now let's install the WebSocket helper libs, repeat the steps above to load the NuGet package manager, and then type "Websocket.Client" in the search box and install the latest version.


Get your API key

Now the environment is set up let's get your TraderMade API Key, if you don’t have an account you can sign up here https://marketdata.tradermade.com/signup, it only takes seconds, then you can copy your key from your dashboard under https://marketdata.tradermade.com/myAccount


Now the fun bit let's write some code

At the top of the program, we will add some import statements, the first two are system-required libraries, the ones we have an interest in are the WebSocket.Client (this helps in getting WebSocket helper libs) and the Newtonsoft.Json (this will help us parse the JSON data).

using System;
using System.Threading;
using Websocket.Client;
using Newtonsoft.Json;

We then will first define the namespace "csWebsocket" and within this namespace, we will define class "Program", Namespace is set so we don't have conflicting classes. In the class Program, we will initialize a variable "streaming_API_Key" at the top of the program with our API key, don't forget to add your own. We will then set the Main method as "static void Main(string[] args)", "void" is used when the method doesn't have a return type and as you can see from the code below we are using it to start the second function "Initialize".

namespace csWebsocket

{
    class Program
    {

        private string streaming_API_Key = "your_api_key";

        static void Main(string[] args)

        {

            Program prg = new Program();

            prg.Initialize();

        }

        private void Initialize()

        {

            Console.CursorVisible = false;

            Console.ReadKey();

        }

    }

}

With the basic structure done we will define our handler code within the Initialize method. The "exitEvent" and "url" variables are easy to understand once there are set we will create a new WebSocket class and inject the "url". The "using" statement is used when we want to set one or more resources. The resources are executed and released as shown below. We first set 30seconds ReconnectTimeout then the socket connection messages will be received via the MessageReceived function, As the WebSocket requires the user to log in we listen for a connected message and then send back a JSON with the user key and the symbols we require using the clinet.Send() function.

try
  {
      var exitEvent = new ManualResetEvent(false);
      var url = new Uri("wss://marketdata.tradermade.com/feedadv");
     

      using (var client = new WebsocketClient(url))
      {
          client.ReconnectTimeout = TimeSpan.FromSeconds(30);

          client.ReconnectionHappened.Subscribe(info =>
          {
              Console.WriteLine("Reconnection happened, type: " + info.Type);
          });

          client.MessageReceived.Subscribe(msg =>
          {
              Console.WriteLine("Message received: " + msg);    

              if (msg.ToString().ToLower() == "connected")
                        {
                            string data = "{\"userKey\":\"" + streaming_API_Key + "\", \"symbol\":\"EURUSD,GBPUSD,USDJPY\"}";
                            client.Send(data);
                        }
          });

          client.Start();

          //Task.Run(() => client.Send("{ message }"));

          exitEvent.WaitOne();
      }
  }
catch (Exception ex)
  {
      Console.WriteLine("ERROR: " + ex.ToString());
  }

Below is the full code to connect to the WebSocket and subscribe to a couple of symbols, you will need to copy your API key into the below code.

using System;
using System.Threading;
using Websocket.Client;
using Newtonsoft.Json;

namespace TraderMadeWebSocketTest
{
    class Program
    {
        private string streaming_API_Key = "YOUR_USER_KEY";

        static void Main(string[] args)
        {
            Program prg = new Program();
            prg.Initialize();
        }


        private void Initialize()
        {
            Console.CursorVisible = false;


            try
            {
                var exitEvent = new ManualResetEvent(false);
                var url = new Uri("wss://marketdata.tradermade.com/feedadv");
                


                using (var client = new WebsocketClient(url))
                {
                    client.ReconnectTimeout = TimeSpan.FromSeconds(30);


                    client.ReconnectionHappened.Subscribe(info =>
                    {
                        Console.WriteLine("Reconnection happened, type: " + info.Type);
                    });


                    client.MessageReceived.Subscribe(msg =>
                    {
                        Console.WriteLine("Message received: " + msg);

                        if (msg.ToString().ToLower() == "connected")
                        {
                            string data = "{\"userKey\":\"" + streaming_API_Key + "\", \"symbol\":\"EURUSD,GBPUSD,USDJPY\"}";
                            client.Send(data);
                        }

                    });


                    client.Start();


                    //Task.Run(() => client.Send("{ message }"));


                    exitEvent.WaitOne();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.ToString());
            }


            Console.ReadKey();
        }


    }
}

Now you can run your code in VSCode by writing the following command:

dotnet run .\csWebsocket.cs

Voila! You have now got lightning fast prices coming through the Websocket into your terminal.

Message received: {"symbol":"EURUSD","ts":"1636114682174","bid":1.15371,"ask":1.15372,"mid":1.153715}
Message received: {"symbol":"EURUSD","ts":"1636114682202","bid":1.15371,"ask":1.15371,"mid":1.15371}
Message received: {"symbol":"USDJPY","ts":"1636114682278","bid":113.787,"ask":113.788,"mid":113.787506}
Message received: {"symbol":"USDJPY","ts":"1636114682363","bid":113.788,"ask":113.788,"mid":113.788}
Message received: {"symbol":"USDJPY","ts":"1636114682420","bid":113.788,"ask":113.789,"mid":113.7885}
Message received: {"symbol":"USDJPY","ts":"1636114682488","bid":113.789,"ask":113.789,"mid":113.789}
Message received: {"symbol":"USDJPY","ts":"1636114682632","bid":113.788,"ask":113.789,"mid":113.7885}
Message received: {"symbol":"EURUSD","ts":"1636114682635","bid":1.15371,"ask":1.15372,"mid":1.153715}
Message received: {"symbol":"EURUSD","ts":"1636114682643","bid":1.15372,"ask":1.15372,"mid":1.15372}
Message received: {"symbol":"EURUSD","ts":"1636114682682","bid":1.15373,"ask":1.15373,"mid":1.15373}
Message received: {"symbol":"EURUSD","ts":"1636114682768","bid":1.15372,"ask":1.15372,"mid":1.15372}
Message received: {"symbol":"USDJPY","ts":"1636114683727","bid":113.789,"ask":113.789,"mid":113.789}

Parsing the data

Now that we are getting the data we can parse it and pull out the information we need. We create a quote class that has the format of the messages that are coming in over the WebSocket. Copy paste at the top of the page after libraries and before the namespace.

public class quote
        {
            public string symbol { get; set; }
            public long ts { get; set; }
            public double bid { get; set; }
            public double ask { get; set; }
            public double mid { get; set; }
        }

We then add the parsing code into our program as an else statement as shown below, We use the DeserializeObject to parse the data into the class, and then we can reference the class attributes directly e.g. result.symbol, result.bid.

 client.MessageReceived.Subscribe(msg =>
                    {
                        Console.WriteLine("Message received: " + msg);
                        if (msg.ToString().ToLower() == "connected")
                        {
                            string data = "{\"userKey\":\"" + streaming_API_Key + "\", \"symbol\":\"EURUSD,GBPUSD,USDJPY\"}";
                            client.Send(data);
                        }
                        else {
                           string data = msg.Text;
                           var result = JsonConvert.DeserializeObject<quote>(data);
                           Console.WriteLine(result.symbol + " " + result.bid + " " + result.ask);
                        }
                     });                               

Now when we run the program you should get the raw data and the parsed output.

Message received: {"symbol":"USDJPY","ts":"1636117095648","bid":113.888,"ask":113.889,"mid":113.888504}
USDJPY 113.888 result 113.889
Message received: {"symbol":"USDJPY","ts":"1636117095653","bid":113.889,"ask":113.889,"mid":113.889}
USDJPY 113.889 result 113.889
Message received: {"symbol":"GBPUSD","ts":"1636117095658","bid":1.34458,"ask":1.3446,"mid":1.34459}
GBPUSD 1.34458 result 1.3446
Message received: {"symbol":"EURUSD","ts":"1636117095660","bid":1.15192,"ask":1.15192,"mid":1.15192}
EURUSD 1.15192 result 1.15192

and we are done you now have a running example FX real-time data using c# WebSocket. You can copy the full code from our Github page

Please contact us with your suggestion or if you need any help in getting started. We are always keen to hear from you and happy to help you.

Related Posts