How to Work with WebSockets in cTrader Algo¶
The cTrader Algo API allows traders and developers to access various web services and resources through a WebSocket connection. The WebSocket protocol is more efficient than HTTP for network access because it is faster and supports real-time data transfer.
In this article and its corresponding video, you will learn how to send and receive messages through WebSockets.
Create a cBot¶
In our example, we intend to connect to a TraderMade feed and then print the incoming information in our cBot log.
First, we head to the 'Algo' app to create a new cBot.
In the 'cBots' tab, click the 'New' button. Type in a name for the cBot, such as 'Web Sockets Example', and then click the 'Create' button.
We can now modify the cBot code for our purposes. Let’s start by defining a new WebSocketClient
.
1 |
|
Then we initialise our endpoint Uri
, which is the location we will connect to.
1 |
|
We need to edit the OnStart()
method, use Uri
to connect to the streaming service and subscribe to the TextReceived
event. This event is raised whenever text reaches our application through the connection.
1 2 3 4 5 |
|
We want to print the received message in TextReceived
.
1 2 3 4 |
|
You can copy the full code below:
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 |
|
Click the 'Build' button or use the Ctrl+B shortcut to build the cBot.
Click the 'Add instance' button for the cBot. Select the 'Locally' option, choose a symbol and account, and then click the 'Add instance' button.
Navigate to the 'Logs' tab. You should see some cBot messages that confirm the connection.
Subscribe to a Symbol Price Feed¶
Let’s return to the code editor for our Web Sockets Example cBot in the 'Algo' app. Here, we want to subscribe to a symbol price feed using the service that we have recently connected to.
Write the code to send a subscription message to the service in our OnStart()
method.
1 2 3 |
|
Note
We obtained the code sample and token from TraderMade website.
Modify the Print
command to replace brackets, which cannot be used in the API Print()
method.
1 |
|
Finally, close the connection in the OnStop()
method.
1 |
|
You can copy the full code below:
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 |
|
Rebuild the cBot and then start it again.
Navigate to the 'Logs' tab as you did before. Now, you should see the symbol price streamed in real time.
This article showed you how to use WebSockets to send and receive information or messages in cTrader. To learn more about the cTrader Algo API, see our documentation or post a question on our forum.