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 article and its corresponding video, we will demonstrate how to retrieve news from a free API that uses JSON for serialisation and deserialisation.
Consume 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 see how the API looks 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 | |
Afterwards, 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 using a MessageBox.
1 2 3 | |
Deserialise JSON data
To deserialise our JSON data, we will use the JsonSerialiser class. However, before we can do this, we will have to define the classes required for deserialisation.
NewsItem- this class represents a single news article.News- this class contains a collection ofNewsItemobjects.
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 appears in the log. However, if we change the access rights of the cBot to AccessRights.FullAccess, we will see that our cBot works as intended.
Access 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!