BackWebsocket Client C Sharp

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

05 November 2021


This tutorial takes you through a series of steps:

  • Setting up a Visual Studio coding environment
  • Code a program in C#
  • Connecting to a WebSocket service (TraderMade’s forex data feed, in this example)
  • Obtain streaming Forex, CFD, and Crypto Data in real-time, and
  • Resolving the JSON output

If you are experienced in Visual Studio set-up, you can skip the initial steps and jump straight to the coding part of this tutorial. Also, download a version of code pre-populated with your API key from the C# WebSocket Example of the documentation page. 

Though this tutorial covers a few currencies, TraderMade offers WebSockets with over 1500 currency pairs.



Initiating the Development Environment

First, download and install Visual Studio code and .NET Core SDK from https://code.visualstudio.com/download. After this, we need to install an extension for C# that enables us to work in VS Code. For that, open Visual Studio Code and select View -> Extension. Then, in the search box, enter C#. We can see many extension options. We select the OmniSharp extension and click the “Install” button for this example. 

cshartinstall1


Establish the Project

Now, it’s time to put up the project to connect to the WebSocket. We need to create a new directory in Windows Explorer. You can name it as per your choice, yet for this example, we will call it “csWebSocket” as we are working on a C# WebSocket example. Then, open VSCode, select ‘File’ and open the folder we created. 

cshartinstall2


As the folder opens in VSCode, our first task will be to create the .NET framework. Ultimately, this will establish the project definition file (.csproj) and the main file (.cs). We will copy our code into this file. 

After that, click “View” -> “Terminal” and enter the following command:

Dotnet new console

The project is populated with a “Hello World” example by default. You may also be called forth to download other assets required to run the program. Select “Yes.” If you don’t get a prompt, press “CTRL+SHIFT+X.”

cshartinstall3


Installing NuGet

It is necessary to install NuGet via the package manager. To do that, we select the extension tab and enter “NuGet” into the search box. Then, we will click the “Install” button. NuGet library is essential to parse the JSON responses received over the WebSocket.

cshartinstall4

After installing the NuGet package library, we can install our helper libraries. Bring up the VS Command pallet by pressing ‘F1’ (or FN + F1 on Windows). Type “Nuget” and then click on the “NuGet Package Manager Add Package” command.

cshartinstall5

As we see another search bar prompt, we will write “Newtonsoft.JSON” and press Enter. We will choose the matching package and the latest version at the top. 

cshartinstall6

The next step is to install the WebSocket helper libraries. We will redo the above steps to load the NuGet Package Manager and type “WebSocket.Client” in the search bar. We will install the latest version. 

cshartinstall7


Obtain Your API Key

We have established the development environment. Now, let us obtain the TraderMade API Key. Don’t you have an account? Please sign up for a free API Key. It just takes a few seconds. You can copy your API key from the dashboard once you log in.

Now, the enjoyable part: Let’s write some code.

To begin with, we will write some 'import' statements. We will import two system-required libraries through the first two lines. Then comes the most essential element: the WebSocket.Client. We require it to get WebSocket helper libs and Newtonsoft.Json to help us parse JSON data.

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

Then, we will define the namespace “csWebSocket” and class “Program” within that namespace to avoid conflicting classes. Then, in the “Program” class, we will set a variable - “streaming_API-Key” at the top of the program inserting the API Key. You must add your own API Key here that you obtained after logging in. 

After this, we will set the Main method as “static void Main(string[] argos).” We use “void” if the method element doesn’t have a return type. As you can observe in the code below, we use 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();

        }

    }

}

As we are done with the basic framework, let us define our handler code within the Initialize method. We can easily understand the “exitEvent” and “url” variables. Once these are set, we will create a new WebSocket class and inject the “url.” 

We need to use the “using” statement to set one or multiple resources. The execution and release of resources are shown below. 

We initially set 30seconds ReconnectTimeout so that the socket connection messages are received via the MessageReceived function. WebSocket requires the user to log in. We will wait for a connected message, and as we get that, we will send back a JSON along with the user key and currency pair symbols we require through the client.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());
  }

We are giving the complete code below to connect to the WebSocket and subscribe to two symbols. You need to copy your API key into this 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();
        }


    }
}

Write the following code to run the program in VSCode:

dotnet run .csWebsocket.cs

And that’s it! You get lightning-fast prices retrieved 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}

Resolving the data

So, we are getting streaming prices. We can parse the data to extract the information we need. We need to create a quote class in a format similar to the messages we retrieved from the WebSocket. At the beginning of the program, copy-paste the following 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; }
        }

Then, we need to add the parsing code as an else statement in the program shown below. Here, we use the DeserializeObject to parse the data into the class. Then, we can reference the class attributes. For instance: result.symbol, result.bid, etc. 

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

As we run the program, we should get the raw data and parsed output similar to the following:

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

Thus, we have a running example of obtaining real-time forex data using C# WebSocket. Also, you can copy the complete code from our GitHub page

Contact us with your suggestions, technical queries or if you need assistance to get started. Our experts are always ready and happy to help you.