Skip to content

Extracting Specific Data from JSON Responses in MetaTrader 5

    Extracting Specific Data from JSON Responses in MetaTrader 5

    When working with financial markets and automated trading systems, MetaTrader 5 (MT5) provides powerful tools to analyze data and perform various functions. However, as financial data often comes in JSON format (especially when interfacing with APIs), it’s essential to efficiently parse and extract specific information from JSON responses. Fortunately, MetaTrader 5 allows us to use libraries like CJAVal for JSON serialization and deserialization, making it easy to handle JSON objects.

    This article will walk you through extracting specific data from a JSON response using the CJAVal class in MetaTrader 5. Additionally, we will reference the JSON Serialization and Deserialization library for MetaTrader 5 , which helps simplify the process of working with JSON data in your trading scripts.

    What is JSON and Why Do You Need It?

    JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. Many web services, including APIs for trading platforms, often return data in JSON format. If you need to interact with such services, you must be able to parse JSON responses and extract specific values like trade information, market data, or account details.

    In MetaTrader 5, CJAVal is one of the powerful tools for handling JSON data. This class is part of the JSON library for MQL5, which can be downloaded from MQL5 codebase.

    Example JSON Structure

    Consider the following JSON response, which could be retrieved from a messaging service (e.g., Telegram API or similar):

    {
      "ok": true,
      "result": [
        {
          "update_id": 300493178,
          "message": {
            "message_id": 1,
            "from": {
              "id": 6648117243,
              "is_bot": false,
              "first_name": "Spack King",
              "username": "spack_king",
              "language_code": "en"
            },
            "chat": {
              "id": 6648117243,
              "first_name": "Spack King",
              "username": "spack_king",
              "type": "private"
            },
            "date": 1731754021,
            "text": "/start",
            "entities": [
              {
                "offset": 0,
                "length": 6,
                "type": "bot_command"
              }
            ]
          }
        },
        {
          "update_id": 300493179,
          "message": {
            "message_id": 2,
            "from": {
              "id": 6648117243,
              "is_bot": false,
              "first_name": "Spack King",
              "username": "spack_king",
              "language_code": "en"
            },
            "chat": {
              "id": 6648117243,
              "first_name": "Spack King",
              "username": "spack_king",
              "type": "private"
            },
            "date": 1731754023,
            "text": "Hey"
          }
        }
      ]
    }
    

    Goal:

    We want to extract the following data:

    1.  Message text from the first message (/start).
    2. update_id from the first message (300493178).
    3. The text and update_id from additional results in the array.

    Parsing JSON in MQL5 with CJAVal

    Step 1: Setting Up the Environment

    First, you need to download and include the JSON Serialization and Deserialization library in your MQL5 project. This library can be downloaded from the MQL5 codebase.

    Once the library is available, include it in your script:

    #include <JSON.mqh> 

    Step 2: Parsing the JSON String

    The following MQL5 code demonstrates how to deserialize the JSON string, extract the values, and handle potential errors.

    void OnStart()
    {
        
        string response_str = "{\"ok\":true, \"result\":[" +
                              "{\"update_id\":300493178, \"message\":{\"message_id\":1," +
                              "\"from\":{\"id\":6648117243,\"is_bot\":false,\"first_name\":\"Spack King\"," +
                              "\"username\":\"spack_king\",\"language_code\":\"en\"},\"chat\":{\"id\":6648117243," +
                              "\"first_name\":\"Spack King\",\"username\":\"spack_king\",\"type\":\"private\"}," +
                              "\"date\":1731754021,\"text\":\"/start\",\"entities\":[{\"offset\":0,\"length\":6," +
                              "\"type\":\"bot_command\"}]}}," +
                              "{\"update_id\":300493179, \"message\":{\"message_id\":2," +
                              "\"from\":{\"id\":6648117243,\"is_bot\":false,\"first_name\":\"Spack King\"," +
                              "\"username\":\"spack_king\",\"language_code\":\"en\"},\"chat\":{\"id\":6648117243," +
                              "\"first_name\":\"Spack King\",\"username\":\"spack_king\",\"type\":\"private\"}," +
                              "\"date\":1731754023,\"text\":\"Hey\"}}]}";
    
        
        CJAVal js(NULL, jtUNDEF);
        js.Clear();
    
        
        if (js.Deserialize(response_str) == 0)
        {
            Print("Failed to parse JSON.");
            return;
        }
    
        
        int resultSize = js["result"].Size();
        if (resultSize > 0)
        {
            
            string text1 = js["result"][0]["message"]["text"].ToStr();
            int update_id1 = js["result"][0]["update_id"].ToInteger();
    
            Print("First message text: ", text1);
            Print("First update_id: ", update_id1);
    
            
            if (resultSize > 1)
            {
                string text2 = js["result"][1]["message"]["text"].ToStr();
                int update_id2 = js["result"][1]["update_id"].ToInteger();
    
                Print("Second message text: ", text2);
                Print("Second update_id: ", update_id2);
            }
        }
        else
        {
            Print("No results found.");
        }
    }
    

    Step 3: Accessing Specific Data

    Here’s a breakdown of how the code works:

    Deserialization: The Deserialize method parses the JSON string into the CJAVal object (js).

    Navigating the JSON:

    You can navigate through the JSON hierarchy using the [] operator. For example:

    1. js[“result”][0][“message”][“text”] accesses the “text” field of the first message.
    2. js[“result”][0][“update_id”] accesses the update_id of the first message.

    Handling Multiple Results: The code checks the size of the “result” array to ensure there are more than one result. If more than one result exists, it extracts the corresponding data from the second message.

    Example Output:

    First message text: /start
    First update_id: 300493178
    Second message text: Hey
    Second update_id: 300493179

    Conclusion

    With the help of the CJAVal class and the JSON.mqh library, extracting specific data from JSON responses in MetaTrader 5 becomes a straightforward process. By deserializing JSON into a structured format, you can easily access nested fields like message content, IDs, and other values.

    For more detailed information, you can download the JSON Serialization and Deserialization (native MQL) library from the MQL5 codebase and start working with JSON data in your MT5 trading scripts. This approach significantly simplifies the process of handling JSON and is invaluable when interacting with external APIs in your automated trading strategies. You’re welcome 🙂

    www.mql5.com (Article Sourced Website)

    #Extracting #Specific #Data #JSON #Responses #MetaTrader