How to Use Network Access¶
Accessing the Internet is a common use case for plugins, cBots, and indicators. Previously, algos had to request special permissions to perform any network-related operations, which could raise some concerns from users, especially if these algos were distributed without any source code. Fortunately, cTrader now allows all algos to access web resources without having elevated access rights.
In this video and its corresponding article, we will demonstrate how to retrieve news from a free API that uses JSON for serialisation and deserialisation.
Consuming an API Endpoint¶
In our example, we will use our cBot to read news information from an external source and print it to the log. For this purpose, we will use a free API offered by NewsData.
To check how the API looks like in a browser, we can simply access this link.
https://newsdata.io/api/1/news?apikey=pub_32606381862bbdf07962c72ae7bc6135d6332&&language=en
As we can see, the endpoint provides a sequence of key value pairs that we can easily consume using a cBot. We will begin by adding the namespaces containing several classes and methods for deserialising and reading JSON-formatted data.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
We can then declare a simple HttpClient()
that will access the Internet.
1 |
|
Afterward, we will be able to read data in the OnStart()
method.
1 2 3 4 |
|
The request will return a raw response in JSON format. We can see how it looks like using a MessageBox
.
1 2 3 |
|
Deserialising JSON Data¶
To deserialise our JSON data, we will use the JsonSerialiser
ckass. Before we can do this, however, we will have to define a couple of classes necessary for deserialisation.
NewsItem
. This class will represent a single news article.News
. This class will contain a collection ofNewsItem
objects.
1 2 3 4 5 6 7 8 9 |
|
If you want to avoid writing this 'boilerplate' code, you can also use an online converter from JSON into C#.
Using the converter, we have defined our classes as follows.
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 |
|
We can now write our deserialisation code.
1 |
|
In addition, we can add the following code to print news titles in the log.
1 2 3 4 5 6 7 |
|
If we build and run our cBot, we will see an exception being thrown in the log. However, if we change the access rights of the cBot to AccessRights.FullAccess
, we will see that our bot works as intended.
Accessing the Internet Without Elevated Access Rights¶
To avoid having a situation where our cBot needs to request elevated access rights, we can modify our OnStart()
method to the following.
1 2 3 4 |
|
If we set access rights to AccessRights.None
and rebuild our cBot, we should see the news titles being printed in the log without any problems. With some more effort, our cBot can be transformed into a fancy news reader available right inside any cTrader chart!
To learn more about the cTrader Algo API, see our documentation or post a question on our forum.