Skip to content

WebSocket Client

The Algo API allows anyone to use various web services and resources using a websocket connection. Compared to the HTTP protocol which is used in the network access feature, the websocket procotol is faster and allows for receiving data in real time.

Here is a one-minute summary of how the websocket client works in cTrader algo.

WebSocket Client in One Minute!

  • The websocket protocol allows for receiving data from a service in real time instead of having to make an HTTP request each time. Use websocket to smoothly integrate your algos with web resources!
  • The WebSocketClient class contains all the methods and parameters necessary to use websocket connections.
  • When using websocket, you can send/receive strings and raw byte data. Work with different data structures and serialise them into bytes to use valuable third-party services!
  • Via event handlers, you can specify what your algo should do when the websocket client receives new data. This is essential for timely reactions to outside events!

Using the WebSocket Client

Using the websocket client is simple:

  1. Choose a service that exposes an endpoint for a websocket connection
  2. Initialise an object of the WebSocketClientOptions class and specify its parameters to configure your client.
  3. Initialise an object of the WebSocketClient class and pass the previously created options to the constructor.
  4. Use the Connect() method to connect to your chosen resource and send data via the Send() method.
  5. Use the TextReceived() and BinaryReceived() event handlers to set what your algo should do when the websocket client receives new data.

Below, we will create a simple cBot that connects to an imaginary economic news service via websocket. When a new piece of news is posted about the symbol to which the cBot is currently attached, the algo will shows a message box containing the news text.

Note

Note that the cBot is provided for example purposes only. While it can be built inside cTrader, it will not perform any actions when attached to a chart.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None)]
    public class ExampleWebSocketBot : Robot
    {

        private static WebSocketClientOptions _webSocketClientOptions = new WebSocketClientOptions 
        {
            KeepAliveInterval = new TimeSpan(0, 1, 30),
            UseDefaultCredentials = true,
        };
        private WebSocketClient _webSocketClient = new WebSocketClient(_webSocketClientOptions);
        private readonly Uri _targetUri = new Uri("ws://amazingnews.com:8000");

        protected override void OnStart()
        {
            _webSocketClient.Connect(_targetUri);
            _webSocketClient.Send("Hello");
            _webSocketClient.TextReceived += NewsReceived;
        }

        protected override void OnStop()
        {
            _webSocketClient.Close(WebSocketClientCloseStatus.NormalClosure);
        }

        private void NewsReceived(WebSocketClientTextReceivedEventArgs args) 
        {
            if (args.Text.Contains(SymbolName)) 
            {
                MessageBox.Show(args.Text, "News!", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
            }
        }
    }
}

As you can see, our code is pretty compact as we can simply handle the WebSocketClient.TextReceived event to show the message box. Note that our bot does not actively request information from the services. Instead, it dynamically reacts to new information being supplied to it.

Warning

When your websocket client disconnects for any reason (e.g., there is some sort of server-side error leading to the keep-alive interval being exceeded), you would need to call the WebSocketClient.Connect() method again. To handle such cases programmatically, use the WebSocketClient.Disconnected event.

Benefits of WebSocket

Because websocket allows for reactiing to new data from the web in real time, it is perfect for integrating with third-party services that can autonomously notify your algos about something. Here are a few examples of the web resources with which you can use the websocket client.

  • An economic news calendar. When a new piece of news is released, your algo can show a message box with key information.S
  • A generative AI service. When an AI service starts to supply a response to a prompt, you can show the result word-by-word rather than having to wait for the complete response.
  • A stream of prices for all symbols correlated with the one to which an algo is attached. When prices are updated, they are immediately and accurately shown to algo users.
  • A social media network focused on trading. When new messages are posted about a particular symbol, an algo can show their contents to users.

In general, websocket connections offer the following benefits compared to regular HTTPS.

  • Websocket connections are more efficient. Any HTTP request has to contain additional data such as headers. With websocket, your connection is established only once, after which there is no need to send redundant data.
  • Websocket connections offer improved concurrency. There is no need to halt algo operations until you await a response after sending an HTTP request. With websocket, you can send and receive data at any time and handle it asynchronously.

Summary

The websocket client allows all types of algos to dynamically interact with web resources; this interaction is faster and more efficient compared to using HTTP. Use the websocket client to build powerful algos integrated with third-party services!