English Русский Español Deutsch 日本語 Português
preview
在 MQL5 中构建 AI 驱动的交易系统(第一部分):实现 AI API 交互所需的 JSON 处理

在 MQL5 中构建 AI 驱动的交易系统(第一部分):实现 AI API 交互所需的 JSON 处理

MetaTrader 5 — 交易系统 |
18 2
Allan Munene Mutiiria
Allan Munene Mutiiria

引言

在本系列文章中,我们将介绍如何借助 MetaQuotes Language 5(MQL5)将AI集成至交易系统中。本篇作为系列开篇,我们将开发一个稳健的 JSON(JavaScript 对象表示法)解析框架,用于处理与 ChatGPT 等 AI 服务的API交互时的数据交换。我们致力于构建处理 JSON 结构的基础框架,以便未来交易应用能够与 AI 服务实现无缝通信。本文将依次探讨以下主题:

  1. 了解 JSON 及其在 AI 集成中的作用
  2. 在 MQL5 中的实现
  3. 测试 JSON 解析器
  4. 结论

阅读完本文,您将打下处理 JSON 数据的坚实基础,为构建 AI 驱动的交易系统做好准备——让我们开始吧!


了解 JSON 及其在 AI 集成中的作用

JSON(JavaScript 对象表示法)是一种轻量级的、基于文本的数据交换格式,因其简单、易读且在各种编程语言间具有兼容性,而被广泛用于系统间数据的结构化处理和传输,特别是在基于 Web 的 API 中。在我们计划构建的 AI 驱动的交易系统中,JSON 是与 OpenAI 的 ChatGPT 等 AI 服务的 API 交换数据的标准格式,使 MQL5 应用程序能够发送与交易相关的提示词,并接收用于决策的结构化响应。本文的方法侧重于构建一个用于处理这些 API 交互的 JSON 解析框架,为将 AI 生成的分析结果整合到自动化交易策略中奠定基础。

什么是 JSON 以及它为何重要

JSON 将数据表示为键值对、数组和嵌套对象,因此非常适合将市场数据、交易信号或 AI 响应等复杂信息编码为一种既可供人类阅读又可供机器解析的格式。例如,一个 JSON 对象可能如下所示:

{
  "model": "gpt-3.5-turbo",
  "messages": [
    {"role": "user", "content": "Analyze EURUSD trend"},
    {"role": "assistant", "content": "EURUSD shows a bullish trend"}
  ],
  "max_tokens": 500
}

该结构包含字符串、数字、数组和嵌套对象,MQL5 智能交易系统(EA)必须对其进行解析,以提取相关信息,例如 AI 对交易查询的响应。JSON 在 AI 集成中的作用至关重要,因为 API 返回的响应采用 JSON 格式,这要求程序对输入进行序列化(将数据转换为 JSON)并对输出进行反序列化(将 JSON 解析为可用数据),从而支持动态交易决策。如果您觉得这听起来像是一堆专业术语,下面就简单直观地说明一下数据序列化和反序列化是什么意思。

序列化与反序列化

实现路线图

我们的实现计划是创建一个支持以下功能的 JSON 处理类:

  • 数据表示:一个用于存储 JSON 值的类,该类包含类型、键和值(例如字符串、数字或布尔值)等属性,并包含一个用于存储子元素的数组,以处理嵌套结构。
  • 解析逻辑:将 JSON 字符串反序列化为对象的方法,通过处理字符来识别对象、数组和基本类型等结构,同时处理空白字符和转义序列。
  • 序列化逻辑:将内部数据转换回 JSON 字符串的方法,确保 API 请求的格式正确,包括对特殊字符进行转义。
  • 错误处理:对无效的 JSON、类型不匹配以及越界访问进行严格的检查,以防止 API 通信过程中发生崩溃。
  • 用户界面准备:为未来集成用户界面奠定基础,以便输入提示词并显示 AI 响应,这些功能将依赖解析后的 JSON 数据。

我们将对该框架进行测试,以确保它能够解析典型的 AI API 响应(例如来自 OpenAI 的响应),并准确地序列化与交易相关的提示词,如下所示。

MQL5 AI 回复

通过掌握本文介绍的 JSON 解析技术,我们可以确保未来由 AI 驱动的程序能够处理复杂的数据结构,从而为融合价格行为、图表形态和 AI 生成的分析结果的精细化交易策略铺平道路。让我们开始实现吧!


在 MQL5 中的实现

为了实现集成,我们将首先创建一个功能全面的解析类,用于处理初始提示词并满足今后的应用需求。以下是我们的实现方法。

//+------------------------------------------------------------------+
//|                                            a. JSON Code File.mq5 |
//|                           Copyright 2025, Allan Munene Mutiiria. |
//|                                   https://t.me/Forex_Algo_Trader |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Allan Munene Mutiiria."
#property link "https://t.me/Forex_Algo_Trader"
#property version "1.00"
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(){return(INIT_SUCCEEDED);}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason){}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(){}
//+------------------------------------------------------------------+
//| JSON (JavaScript Object Notation)                                |
//+------------------------------------------------------------------+
#define DEBUG_PRINT false
//+------------------------------------------------------------------+
//| Enumeration of JSON value types                                  |
//+------------------------------------------------------------------+
enum JsonValueType {JsonUndefined,JsonNull,JsonBoolean,JsonInteger,JsonDouble,JsonString,JsonArray,JsonObject};
//+------------------------------------------------------------------+
//| Class representing a JSON value                                  |
//+------------------------------------------------------------------+
class JsonValue{
   public:
      // CONSTRUCTOR
      virtual void Reset(){
         m_parent=NULL;                                         //--- Set parent pointer to NULL
         m_key="";                                              //--- Clear the key string
         m_type=JsonUndefined;                                  //--- Set type to undefined
         m_booleanValue=false;                                  //--- Set boolean value to false
         m_integerValue=0;                                      //--- Set integer value to zero
         m_doubleValue=0;                                       //--- Set double value to zero
         m_stringValue="";                                      //--- Clear the string value
         ArrayResize(m_children,0);                             //--- Resize children array to zero
      }
      virtual bool CopyFrom(const JsonValue &source){
         m_key=source.m_key;                                    //--- Copy the key from source
         CopyDataFrom(source);                                  //--- Copy data from source
         return true;                                           //--- Return success
      }
      virtual void CopyDataFrom(const JsonValue &source){
         m_type=source.m_type;                                  //--- Copy the type from source
         m_booleanValue=source.m_booleanValue;                  //--- Copy the boolean value from source
         m_integerValue=source.m_integerValue;                  //--- Copy the integer value from source
         m_doubleValue=source.m_doubleValue;                    //--- Copy the double value from source
         m_stringValue=source.m_stringValue;                    //--- Copy the string value from source
         CopyChildrenFrom(source);                              //--- Copy children from source
      }
      virtual void CopyChildrenFrom(const JsonValue &source){
         int numChildren=ArrayResize(m_children,ArraySize(source.m_children)); //--- Resize children array to match source size
         for(int index=0; index<numChildren; index++){          //--- Loop through each child
            m_children[index]=source.m_children[index];         //--- Copy child from source
            m_children[index].m_parent=GetPointer(this);        //--- Set parent of child to current object
         }
      }
   public:
      JsonValue m_children[];                                   //--- Array to hold child JSON values
      string m_key;                                             //--- Key for this JSON value
      string m_temporaryKey;                                    //--- Temporary key used during parsing
      JsonValue *m_parent;                                      //--- Pointer to parent JSON value
      JsonValueType m_type;                                     //--- Type of this JSON value
      bool m_booleanValue;                                      //--- Boolean value storage
      long m_integerValue;                                      //--- Integer value storage
      double m_doubleValue;                                     //--- Double value storage
      string m_stringValue;                                     //--- String value storage
      static int encodingCodePage;                              //--- Static code page for encoding
   public:
      JsonValue(){
         Reset();                                               //--- Call reset to initialize
      }
      JsonValue(JsonValue *parent,JsonValueType type){
         Reset();                                               //--- Call reset to initialize
         m_type=type;                                           //--- Set the type
         m_parent=parent;                                       //--- Set the parent
      }
      JsonValue(JsonValueType type,string value){
         Reset();                                               //--- Call reset to initialize
         SetFromString(type,value);                             //--- Set value from string based on type
      }
      JsonValue(const int integerValue){
         Reset();                                               //--- Call reset to initialize
         m_type=JsonInteger;                                    //--- Set type to integer
         m_integerValue=integerValue;                           //--- Set integer value
         m_doubleValue=(double)m_integerValue;                  //--- Convert to double
         m_stringValue=IntegerToString(m_integerValue);         //--- Convert to string
         m_booleanValue=m_integerValue!=0;                      //--- Set boolean based on integer
      }
      JsonValue(const long longValue){
         Reset();                                               //--- Call reset to initialize
         m_type=JsonInteger;                                    //--- Set type to integer
         m_integerValue=longValue;                              //--- Set integer value
         m_doubleValue=(double)m_integerValue;                  //--- Convert to double
         m_stringValue=IntegerToString(m_integerValue);         //--- Convert to string
         m_booleanValue=m_integerValue!=0;                      //--- Set boolean based on integer
      }
      JsonValue(const double doubleValue){
         Reset();                                               //--- Call reset to initialize
         m_type=JsonDouble;                                     //--- Set type to double
         m_doubleValue=doubleValue;                             //--- Set double value
         m_integerValue=(long)m_doubleValue;                    //--- Convert to integer
         m_stringValue=DoubleToString(m_doubleValue);           //--- Convert to string
         m_booleanValue=m_integerValue!=0;                      //--- Set boolean based on integer
      }
      JsonValue(const bool booleanValue){
         Reset();                                               //--- Call reset to initialize
         m_type=JsonBoolean;                                    //--- Set type to boolean
         m_booleanValue=booleanValue;                           //--- Set boolean value
         m_integerValue=m_booleanValue;                         //--- Convert to integer
         m_doubleValue=m_booleanValue;                          //--- Convert to double
         m_stringValue=IntegerToString(m_integerValue);         //--- Convert to string
      }
      JsonValue(const JsonValue &other){
         Reset();                                               //--- Call reset to initialize
         CopyFrom(other);                                       //--- Copy from other object
      }
      // DECONSTRUCTOR
      ~JsonValue(){
         Reset();                                               //--- Call reset to clean up
      }
}

我们开始实现JSON 解析框架,重点构建基础 "JsonValue" 类,以处理 AI API 集成所需的 JSON 数据。首先,我们定义一个宏 "DEBUG_PRINT",将其设置为 false,以控制调试输出,在生产环境中避免多余的调试日志。然后,我们定义一个名为 "JsonValueType" 的枚举,其取值为(JsonUndefined、JsonNull、JsonBoolean、JsonInteger、JsonDouble、JsonString、JsonArray、JsonObject),用于对 JSON 数据类型进行分类,使该类能够处理 API 返回的各类结构。

接下来,我们实现 "JsonValue" 类,其公共成员包括:用于存储嵌套 JSON 元素的数组 "m_children";用于在解析过程中存储键的字符串 "m_key" 和 "m_temporaryKey";用于表示层次关系的指针 "m_parent";用于表示数据类型的 "JsonValueType" 类型变量 "m_type";用于存储相应数据的变量 "m_booleanValue"、"m_integerValue"、"m_doubleValue" 和 "m_stringValue";以及用于字符编码的静态变量 "encodingCodePage"。我们提供多种构造函数来初始化 "JsonValue" 对象:调用 "Reset" 的默认构造函数、接受父节点和类型的构造函数、接受类型和字符串值的构造函数,以及分别接受整数、长整数、双精度浮点数和布尔值的构造函数,外加拷贝构造函数,从而灵活地创建 JSON 元素。

"Reset" 方法将所有成员重置为默认值(例如:父节点指针为 null、字符串为空、类型未定义、数值清零、子元素数组为空),而 "CopyFrom"、"CopyDataFrom" 和 "CopyChildrenFrom" 方法则支持对 JSON 结构(包括子元素)进行深拷贝,并正确地重新设置父节点。这一基础实现构建了用于解析和处理 JSON 数据的架构,这对未来与 AI API 的交互至关重要。接下来,为了完善该类,我们可以继续实现一些纯虚函数,这些函数仍位于 public 访问说明符下。我们使用 virtual 来赋予系统灵活性和多态性。

public:
   virtual bool IsNumericValue(){
      return (m_type==JsonDouble || m_type==JsonInteger);    //--- Check if type is double or integer
   }
   virtual JsonValue *FindChildByKey(string key){
      for(int index=ArraySize(m_children)-1; index>=0; --index){ //--- Loop backwards through children
         if(m_children[index].m_key==key){                   //--- Check if key matches
            return GetPointer(m_children[index]);            //--- Return pointer to matching child
         }
      }
      return NULL;                                           //--- Return NULL if no match
   }
   virtual JsonValue *HasChildWithKey(string key,JsonValueType type=JsonUndefined);
   virtual JsonValue *operator[](string key);
   virtual JsonValue *operator[](int index);
   void operator=(const JsonValue &value){
      CopyFrom(value);                                       //--- Copy from value
   }
   void operator=(const int integerValue){
      m_type=JsonInteger;                                    //--- Set type to integer
      m_integerValue=integerValue;                           //--- Set integer value
      m_doubleValue=(double)m_integerValue;                  //--- Convert to double
      m_booleanValue=m_integerValue!=0;                      //--- Set boolean based on integer
   }
   void operator=(const long longValue){
      m_type=JsonInteger;                                    //--- Set type to integer
      m_integerValue=longValue;                              //--- Set integer value
      m_doubleValue=(double)m_integerValue;                  //--- Convert to double
      m_booleanValue=m_integerValue!=0;                      //--- Set boolean based on integer
   }
   void operator=(const double doubleValue){
      m_type=JsonDouble;                                     //--- Set type to double
      m_doubleValue=doubleValue;                             //--- Set double value
      m_integerValue=(long)m_doubleValue;                    //--- Convert to integer
      m_booleanValue=m_integerValue!=0;                      //--- Set boolean based on integer
   }
   void operator=(const bool booleanValue){
      m_type=JsonBoolean;                                    //--- Set type to boolean
      m_booleanValue=booleanValue;                           //--- Set boolean value
      m_integerValue=(long)m_booleanValue;                   //--- Convert to integer
      m_doubleValue=(double)m_booleanValue;                  //--- Convert to double
   }
   void operator=(string stringValue){
      m_type=(stringValue!=NULL)?JsonString:JsonNull;        //--- Set type to string or null
      m_stringValue=stringValue;                             //--- Set string value
      m_integerValue=StringToInteger(m_stringValue);         //--- Convert to integer
      m_doubleValue=StringToDouble(m_stringValue);           //--- Convert to double
      m_booleanValue=stringValue!=NULL;                      //--- Set boolean based on string presence
   }

   bool operator==(const int integerValue){return m_integerValue==integerValue;}  //--- Compare integer value
   bool operator==(const long longValue){return m_integerValue==longValue;}       //--- Compare long value
   bool operator==(const double doubleValue){return m_doubleValue==doubleValue;}  //--- Compare double value
   bool operator==(const bool booleanValue){return m_booleanValue==booleanValue;} //--- Compare boolean value
   bool operator==(string stringValue){return m_stringValue==stringValue;}        //--- Compare string value
  
   bool operator!=(const int integerValue){return m_integerValue!=integerValue;}  //--- Check inequality for integer
   bool operator!=(const long longValue){return m_integerValue!=longValue;}       //--- Check inequality for long
   bool operator!=(const double doubleValue){return m_doubleValue!=doubleValue;}  //--- Check inequality for double
   bool operator!=(const bool booleanValue){return m_booleanValue!=booleanValue;} //--- Check inequality for boolean
   bool operator!=(string stringValue){return m_stringValue!=stringValue;}        //--- Check inequality for string

   long ToInteger() const{return m_integerValue;}            //--- Return integer value
   double ToDouble() const{return m_doubleValue;}            //--- Return double value
   bool ToBoolean() const{return m_booleanValue;}            //--- Return boolean value
   string ToString(){return m_stringValue;}                  //--- Return string value

   virtual void SetFromString(JsonValueType type,string stringValue){
      m_type=type;                                           //--- Set the type
      switch(m_type){                                        //--- Handle based on type
      case JsonBoolean:
         m_booleanValue=(StringToInteger(stringValue)!=0);   //--- Convert string to boolean
         m_integerValue=(long)m_booleanValue;                //--- Set integer from boolean
         m_doubleValue=(double)m_booleanValue;               //--- Set double from boolean
         m_stringValue=stringValue;                          //--- Set string value
         break;                                              //--- Exit case
      case JsonInteger:
         m_integerValue=StringToInteger(stringValue);        //--- Convert string to integer
         m_doubleValue=(double)m_integerValue;               //--- Set double from integer
         m_stringValue=stringValue;                          //--- Set string value
         m_booleanValue=m_integerValue!=0;                   //--- Set boolean from integer
         break;                                              //--- Exit case
      case JsonDouble:
         m_doubleValue=StringToDouble(stringValue);          //--- Convert string to double
         m_integerValue=(long)m_doubleValue;                 //--- Set integer from double
         m_stringValue=stringValue;                          //--- Set string value
         m_booleanValue=m_integerValue!=0;                   //--- Set boolean from integer
         break;                                              //--- Exit case
      case JsonString:
         m_stringValue=UnescapeString(stringValue);          //--- Unescape the string
         m_type=(m_stringValue!=NULL)?JsonString:JsonNull;   //--- Set type based on string presence
         m_integerValue=StringToInteger(m_stringValue);      //--- Convert to integer
         m_doubleValue=StringToDouble(m_stringValue);        //--- Convert to double
         m_booleanValue=m_stringValue!=NULL;                 //--- Set boolean based on string
         break;                                              //--- Exit case
      }
   }
   virtual string GetSubstringFromArray(char &jsonCharacterArray[],int startPosition,int substringLength){
      #ifdef __MQL4__
            if(substringLength<=0) return "";                //--- Return empty if length invalid in MQL4
      #endif
      char temporaryArray[];                                 //--- Declare temporary array
      ArrayCopy(temporaryArray,jsonCharacterArray,0,startPosition,substringLength); //--- Copy substring to temporary array
      return CharArrayToString(temporaryArray, 0, WHOLE_ARRAY, JsonValue::encodingCodePage); //--- Convert to string using code page
   }
   virtual void SetValue(const JsonValue &value){
      if(m_type==JsonUndefined) {m_type=JsonObject;}         //--- Set type to object if undefined
      CopyDataFrom(value);                                   //--- Copy data from value
   }
   virtual void SetArrayValues(const JsonValue &list[]);
   virtual JsonValue *AddChild(const JsonValue &item){
      if(m_type==JsonUndefined){m_type=JsonArray;}           //--- Set type to array if undefined
      return AddChildInternal(item);                         //--- Call internal add child
   }
   virtual JsonValue *AddChild(const int integerValue){
      JsonValue item(integerValue);                          //--- Create item from integer
      return AddChild(item);                                 //--- Add the item
   }
   virtual JsonValue *AddChild(const long longValue){
      JsonValue item(longValue);                             //--- Create item from long
      return AddChild(item);                                 //--- Add the item
   }
   virtual JsonValue *AddChild(const double doubleValue){
      JsonValue item(doubleValue);                           //--- Create item from double
      return AddChild(item);                                 //--- Add the item
   }
   virtual JsonValue *AddChild(const bool booleanValue){
      JsonValue item(booleanValue);                          //--- Create item from boolean
      return AddChild(item);                                 //--- Add the item
   }
   virtual JsonValue *AddChild(string stringValue){
      JsonValue item(JsonString,stringValue);                //--- Create item from string
      return AddChild(item);                                 //--- Add the item
   }
   virtual JsonValue *AddChildInternal(const JsonValue &item){
      int currentSize=ArraySize(m_children);                 //--- Get current children size
      ArrayResize(m_children,currentSize+1);                 //--- Resize array to add one more
      m_children[currentSize]=item;                          //--- Add the item
      m_children[currentSize].m_parent=GetPointer(this);     //--- Set parent to current object
      return GetPointer(m_children[currentSize]);            //--- Return pointer to added child
   }
   virtual JsonValue *CreateNewChild(){
      if(m_type==JsonUndefined) {m_type=JsonArray;}          //--- Set type to array if undefined
      return CreateNewChildInternal();                       //--- Call internal create new child
   }
   virtual JsonValue *CreateNewChildInternal(){
      int currentSize=ArraySize(m_children);                 //--- Get current children size
      ArrayResize(m_children,currentSize+1);                 //--- Resize array to add one more
      return GetPointer(m_children[currentSize]);            //--- Return pointer to new child
   }

   virtual string EscapeString(string value);
   virtual string UnescapeString(string value);

仍在 public 访问说明符下,我们实现 "IsNumericValue" 方法,用于检查 JSON 值是否为数值:如果 "m_type" 为 "JsonDouble" 或 "JsonInteger",则返回 true,从而支持根据数据类型对数值进行相应处理。接下来,我们实现 "FindChildByKey" 方法,该方法反向遍历 "m_children" 数组,查找键匹配的子元素;如果找到则返回指向该子元素的指针,否则返回 NULL,该方法便于访问嵌套对象中的元素。

接下来,我们为 "JsonValue"、整数、长整数、双精度浮点数、布尔值和字符串类型定义重载赋值运算符("operator="),更新 "m_type" 及相应的值字段("m_integerValue"、"m_doubleValue"、"m_stringValue"、"m_booleanValue"),如赋整数时同步刷新双精度与字符串表示,并根据需要进行类型转换。我们还为整数、长整数、双精度浮点数、布尔型和字符串类型实现了比较运算符("operator=="和"operator!="),从而可以与相应的字段进行直接的值比较。

此外,我们还提供了"ToInteger"、"ToDouble"、"ToBoolean"和"ToString"这几种转换方法,用于以相应的格式获取值。"SetFromString" 方法根据指定的 "JsonValueType" 设置 JSON 值,通过转换输入字符串并更新相关字段来处理布尔型、整数型、双精度浮点型和字符串类型,其中字符串值通过 "UnescapeString" 进行反转义。"GetSubstringFromArray" 方法从字符数组中提取子字符串:先复制指定部分,再使用 "CharArrayToString" 按照已定义的 "encodingCodePage" 将其转换为字符串。

最后,我们实现用于管理子元素的方法:"AddChild"(适用于 "JsonValue"、整数、长整数、双精度浮点数、布尔值和字符串)将新的子元素添加到 "m_children" 中,并根据需要设置父节点和类型;"CreateNewChild" 和 "CreateNewChildInternal" 创建空子元素;"SetValue" 则从另一个 "JsonValue" 中复制数据,从而确保该类能够构建、操作和访问 JSON 结构。最后,我们可以添加用于序列化、反序列化以及对响应和提示词中的字符进行编码的方法,完成该类的实现。

public:
   virtual void SerializeToString(string &jsonString,bool includeKey=false,bool includeComma=false);
   virtual string SerializeToString(){
      string jsonString;                                     //--- Declare json string
      SerializeToString(jsonString);                         //--- Call serialize with default params
      return jsonString;                                     //--- Return the serialized string
   }
   virtual bool DeserializeFromArray(char &jsonCharacterArray[],int arrayLength,int &currentIndex);
   virtual bool ExtractStringFromArray(char &jsonCharacterArray[],int arrayLength,int &currentIndex);
   virtual bool DeserializeFromString(string jsonString,int encoding=CP_ACP){
      int currentIndex=0;                                    //--- Initialize current index
      Reset();                                               //--- Reset the object
      JsonValue::encodingCodePage=encoding;                  //--- Set encoding code page
      char characterArray[];                                 //--- Declare character array
      int arrayLength=StringToCharArray(jsonString,characterArray,0,WHOLE_ARRAY,JsonValue::encodingCodePage); //--- Convert string to char array
      return DeserializeFromArray(characterArray,arrayLength,currentIndex); //--- Call deserialize from array
   }
   virtual bool DeserializeFromArray(char &jsonCharacterArray[],int encoding=CP_ACP){
      int currentIndex=0;                                    //--- Initialize current index
      Reset();                                               //--- Reset the object
      JsonValue::encodingCodePage=encoding;                  //--- Set encoding code page
      return DeserializeFromArray(jsonCharacterArray,ArraySize(jsonCharacterArray),currentIndex); //--- Call deserialize with size
   }

这里,我们实现 "SerializeToString" 方法,其参数包括一个字符串引用、"includeKey" 和 "includeComma",用于将 JSON 结构转换为字符串。当 "includeComma" 为 true 时,该方法添加逗号;当 "includeKey" 为 true 时,包含键。该方法还会处理不同类型:将 "JsonNull" 表示为 "null",将 "JsonBoolean" 表示为 "true" 或 "false",将 "JsonInteger" 和 "JsonDouble" 转换为字符串,对 "JsonString" 的值进行转义,用方括号括起 "JsonArray" 的子元素,并为 "JsonObject" 的子元素包含键;对于嵌套结构,则递归序列化其子元素。"SerializeToString" 的便捷重载会生成一个字符串,调用带参数的版本,并返回结果。

接下来,我们实现 "DeserializeFromString" 方法,该方法接受一个 JSON 字符串和编码(默认为 CP_ACP),重置对象,设置 "encodingCodePage",使用 StringToCharArray 将字符串转换为字符数组,然后交由 "DeserializeFromArray" 进行处理。带编码参数的 "DeserializeFromArray" 重载会初始化索引、重置对象、设置 "encodingCodePage",并调用主 "DeserializeFromArray" 方法。该方法通过遍历字符来解析字符数组,处理空白字符、数组(从 "[" 到 "]")、对象(从 "{" 到 "}")、布尔值("true" 或 "false")、空值("null")、数字(根据有效字符判断是整数还是双精度浮点数)以及字符串(含转义处理),并根据需要创建子元素,通过 "m_parent" 和 "m_temporaryKey" 管理层级关系。

最后,"ExtractStringFromArray" 会解析数组中的字符串,处理转义字符(例如 "\n"、"\t" 和 Unicode 转义序列 "\uXXXX"),直到遇到结束引号,从而确保准确提取字符串,也能应对我们可能使用表情符号等 Unicode 字符的情况。下图展示了这些 Unicode 字符的示例。

Unicode 示例

现在我们可以定义这些方法,以便它们能准确地完成预期的任务。

int JsonValue::encodingCodePage=CP_ACP;                      //--- Initialize static code page
//+------------------------------------------------------------------+
//| Checks if child with specific key and optional type exists       |
//+------------------------------------------------------------------+
JsonValue *JsonValue::HasChildWithKey(string key,JsonValueType type){
   for(int index=0; index<ArraySize(m_children); index++) if(m_children[index].m_key==key){ //--- Loop through children
      if(type==JsonUndefined || type==m_children[index].m_type){ //--- Check type condition
         return GetPointer(m_children[index]);               //--- Return matching child
      }
      break;                                                 //--- Exit loop
   }
   return NULL;                                              //--- Return NULL if no match
}
//+------------------------------------------------------------------+
//| Accessor for object key, creates if not exists                   |
//+------------------------------------------------------------------+
JsonValue *JsonValue::operator[](string key){
   if(m_type==JsonUndefined){m_type=JsonObject;}             //--- Set type to object if undefined
   JsonValue *value=FindChildByKey(key);                     //--- Find child by key
   if(value){return value;}                                  //--- Return if found
   JsonValue newValue(GetPointer(this),JsonUndefined);       //--- Create new undefined value
   newValue.m_key=key;                                       //--- Set key for new value
   value=AddChild(newValue);                                 //--- Add new value as child
   return value;                                             //--- Return the new value
}
//+------------------------------------------------------------------+
//| Accessor for array index, expands if necessary                   |
//+------------------------------------------------------------------+
JsonValue *JsonValue::operator[](int index){
   if(m_type==JsonUndefined) m_type=JsonArray;               //--- Set type to array if undefined
   while(index>=ArraySize(m_children)){                      //--- Loop to expand array if needed
      JsonValue newElement(GetPointer(this),JsonUndefined);  //--- Create new undefined element
      if(CheckPointer(AddChild(newElement))==POINTER_INVALID){return NULL;} //--- Add and check pointer
   }
   return GetPointer(m_children[index]);                     //--- Return pointer to element at index
}
//+------------------------------------------------------------------+
//| Sets array values from list                                      |
//+------------------------------------------------------------------+
void JsonValue::SetArrayValues(const JsonValue &list[]){
   if(m_type==JsonUndefined){m_type=JsonArray;}              //--- Set type to array if undefined
   int numChildren=ArrayResize(m_children,ArraySize(list));  //--- Resize children to list size
   for(int index=0; index<numChildren; ++index){             //--- Loop through list
      m_children[index]=list[index];                         //--- Copy from list
      m_children[index].m_parent=GetPointer(this);           //--- Set parent to current
   }
}

要在类体外部定义类方法,我们需要使用作用域解析运算符。我们也可以在类体内部定义这些方法,但在外部定义能使代码更具模块性。我们将静态成员 "encodingCodePage" 初始化为 CP_ACP(活动代码页),以设置字符串转换的默认字符编码,确保与 AI API 返回的 JSON 数据兼容。接下来,我们实现 "HasChildWithKey" 方法。该方法正向遍历 "m_children" 数组,查找键匹配的子元素,也可要求其类型与指定的 "JsonValueType" 匹配(默认为 "JsonUndefined",表示忽略类型),并返回指向匹配子元素的指针;若未找到,则返回 NULL。该方法可提前结束搜索,并支持针对特定类型的检查,因此比 "FindChildByKey" 更高效。

接下来,我们实现重载的 "operator" 方法。该方法在 "m_type" 为未定义类型时将其设置为 "JsonObject",然后使用 "FindChildByKey" 查找具有给定键的子元素;若未找到,则使用该键创建一个新的 "JsonValue",并通过 "AddChild" 将其添加到 "m_children" 中。最后,返回指向现有或新建子元素的指针,以实现无缝的对象访问。类似地,另一个 "operator" 方法在 "m_type" 为未定义类型时将其设置为 "JsonArray";如果索引超出 "m_children" 数组的大小,则使用 "AddChild" 添加未定义类型的元素以扩展数组,最后返回指向指定索引处元素的指针,确保安全访问数组。

最后,我们实现 "SetArrayValues" 方法。该方法在 "m_type" 为未定义类型时将其设置为 "JsonArray",将 "m_children" 的大小调整为与输入列表一致,将列表中的每个 "JsonValue" 复制到 "m_children" 中,并将每个子元素的父节点设置为当前对象,从而实现数组值的批量赋值。对于其他方法,我们将采用类似的格式。让我们先从字符串的序列化和反序列化方法开始。

//+------------------------------------------------------------------+
//| Serializes the JSON value to string                              |
//+------------------------------------------------------------------+
void JsonValue::SerializeToString(string &jsonString,bool includeKey,bool includeComma){
   if(m_type==JsonUndefined){return;}                        //--- Return if undefined
   if(includeComma){jsonString+=",";}                        //--- Add comma if needed
   if(includeKey){jsonString+=StringFormat("\"%s\":", m_key);} //--- Add key if needed
   int numChildren=ArraySize(m_children);                    //--- Get number of children
   switch(m_type){                                           //--- Handle based on type
   case JsonNull:
      jsonString+="null";                                    //--- Append null
      break;                                                 //--- Exit case
   case JsonBoolean:
      jsonString+=(m_booleanValue?"true":"false");           //--- Append true or false
      break;                                                 //--- Exit case
   case JsonInteger:
      jsonString+=IntegerToString(m_integerValue);           //--- Append integer as string
      break;                                                 //--- Exit case
   case JsonDouble:
      jsonString+=DoubleToString(m_doubleValue);             //--- Append double as string
      break;                                                 //--- Exit case
   case JsonString:
   {
      string value=EscapeString(m_stringValue);              //--- Escape the string
      if(StringLen(value)>0){jsonString+=StringFormat("\"%s\"",value);} //--- Append escaped string if not empty
      else{jsonString+="null";}                              //--- Append null if empty
   }
   break;                                                    //--- Exit case
   case JsonArray:
      jsonString+="[";                                       //--- Start array
      for(int index=0; index<numChildren; index++){m_children[index].SerializeToString(jsonString,false,index>0);} //--- Serialize each child
      jsonString+="]";                                       //--- End array
      break;                                                 //--- Exit case
   case JsonObject:
      jsonString+="{";                                       //--- Start object
      for(int index=0; index<numChildren; index++){m_children[index].SerializeToString(jsonString,true,index>0);} //--- Serialize each child with key
      jsonString+="}";                                       //--- End object
      break;                                                 //--- Exit case
   }
}
//+------------------------------------------------------------------+
//| Deserializes from character array                                |
//+------------------------------------------------------------------+
bool JsonValue::DeserializeFromArray(char &jsonCharacterArray[],int arrayLength,int &currentIndex){
   string validNumericCharacters="0123456789+-.eE";          //--- Define valid number characters
   int startPosition=currentIndex;                           //--- Set start position
   for(; currentIndex<arrayLength; currentIndex++){          //--- Loop through array
      char currentCharacter=jsonCharacterArray[currentIndex]; //--- Get current character
      if(currentCharacter==0){break;}                        //--- Break if null character
      switch(currentCharacter){                              //--- Handle based on character
      case '\t':
      case '\r':
      case '\n':
      case ' ':                                              //--- Skip whitespace
         startPosition=currentIndex+1;                       //--- Update start position
         break;                                              //--- Exit case
      case '[':                                              //--- Start of array
      {
         startPosition=currentIndex+1;                       //--- Update start position
         if(m_type!=JsonUndefined){                          //--- Check if type is undefined
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug if error
            return false;                                    //--- Return false on error
         }
         m_type=JsonArray;                                   //--- Set type to array
         currentIndex++;                                     //--- Increment index
         JsonValue childValue(GetPointer(this),JsonUndefined); //--- Create child value
         while(childValue.DeserializeFromArray(jsonCharacterArray,arrayLength,currentIndex)){ //--- Deserialize children
            if(childValue.m_type!=JsonUndefined){AddChild(childValue);} //--- Add if not undefined
            if(childValue.m_type==JsonInteger || childValue.m_type==JsonDouble || childValue.m_type==JsonArray){currentIndex++;} //--- Increment if certain types
            childValue.Reset();                              //--- Reset child
            childValue.m_parent=GetPointer(this);            //--- Set parent
            if(jsonCharacterArray[currentIndex]==']'){break;} //--- Break if end of array
            currentIndex++;                                  //--- Increment index
            if(currentIndex>=arrayLength){                   //--- Check bounds
               if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
               return false;                                 //--- Return false
            }
         }
         return (jsonCharacterArray[currentIndex]==']' || jsonCharacterArray[currentIndex]==0); //--- Return true if properly ended
      }
      break;                                                 //--- Exit case
      case ']':                                              //--- End of array
         if(!m_parent){return false;}                        //--- Return false if no parent
         return (m_parent.m_type==JsonArray);                //--- Check parent is array
      case ':':                                              //--- Key-value separator
      {
         if(m_temporaryKey==""){                             //--- Check temporary key
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
            return false;                                    //--- Return false
         }
         JsonValue childValue(GetPointer(this),JsonUndefined); //--- Create child
         JsonValue *addedChild=AddChild(childValue);           //--- Add child
         addedChild.m_key=m_temporaryKey;                      //--- Set key
         m_temporaryKey="";                                    //--- Clear temporary key
         currentIndex++;                                       //--- Increment index
         if(!addedChild.DeserializeFromArray(jsonCharacterArray,arrayLength,currentIndex)){ //--- Deserialize child
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
            return false;                                    //--- Return false
         }
         break;                                              //--- Exit case
      }
      case ',':                                              //--- Value separator
         startPosition=currentIndex+1;                       //--- Update start
         if(!m_parent && m_type!=JsonObject){                //--- Check conditions
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
            return false;                                    //--- Return false
         }
         else if(m_parent){                                  //--- If has parent
            if(m_parent.m_type!=JsonArray && m_parent.m_type!=JsonObject){ //--- Check parent type
               if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
               return false;                                //--- Return false
            }
            if(m_parent.m_type==JsonArray && m_type==JsonUndefined){return true;} //--- Return true for undefined in array
         }
         break;                                              //--- Exit case
      case '{':                                              //--- Start of object
         startPosition=currentIndex+1;                       //--- Update start
         if(m_type!=JsonUndefined){                          //--- Check type
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
            return false;                                    //--- Return false
         }
         m_type=JsonObject;                                  //--- Set type to object
         currentIndex++;                                     //--- Increment index
         if(!DeserializeFromArray(jsonCharacterArray,arrayLength,currentIndex)){ //--- Recurse deserialize
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
            return false;                                    //--- Return false
         }
         return (jsonCharacterArray[currentIndex]=='}' || jsonCharacterArray[currentIndex]==0); //--- Check end
         break;                                              //--- Exit case
      case '}':                                              //--- End of object
         return (m_type==JsonObject);                        //--- Check type is object
      case 't':
      case 'T':                                              //--- Start of true
      case 'f':
      case 'F':                                              //--- Start of false
         if(m_type!=JsonUndefined){                          //--- Check type
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
            return false;                                    //--- Return false
         }
         m_type=JsonBoolean;                                 //--- Set type to boolean
         if(currentIndex+3<arrayLength){                     //--- Check for true
            if(StringCompare(GetSubstringFromArray(jsonCharacterArray, currentIndex, 4), "true", false)==0){ //--- Compare substring
               m_booleanValue=true;                          //--- Set to true
               currentIndex+=3;                              //--- Advance index
               return true;                                  //--- Return true
            }
         }
         if(currentIndex+4<arrayLength){                     //--- Check for false
            if(StringCompare(GetSubstringFromArray(jsonCharacterArray, currentIndex, 5), "false", false)==0){ //--- Compare substring
               m_booleanValue=false;                         //--- Set to false
               currentIndex+=4;                              //--- Advance index
               return true;                                  //--- Return true
            }
         }
         if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
         return false;                                       //--- Return false
         break;                                              //--- Exit case
      case 'n':
      case 'N':                                              //--- Start of null
         if(m_type!=JsonUndefined){                          //--- Check type
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
            return false;                                    //--- Return false
         }
         m_type=JsonNull;                                    //--- Set type to null
         if(currentIndex+3<arrayLength){                     //--- Check bounds
            if(StringCompare(GetSubstringFromArray(jsonCharacterArray,currentIndex,4),"null",false)==0){ //--- Compare substring
               currentIndex+=3;                              //--- Advance index
               return true;                                  //--- Return true
            }
         }
         if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
         return false;                                       //--- Return false
         break;                                              //--- Exit case
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
      case '-':
      case '+':
      case '.':                                              //--- Start of number
      {
         if(m_type!=JsonUndefined){                          //--- Check type
            if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
            return false;                                    //--- Return false
         }
         bool isDouble=false;                                //--- Initialize double flag
         int startOfNumber=currentIndex;                     //--- Set start of number
         while(jsonCharacterArray[currentIndex]!=0 && currentIndex<arrayLength){ //--- Loop to parse number
            currentIndex++;                                  //--- Increment index
            if(StringFind(validNumericCharacters,GetSubstringFromArray(jsonCharacterArray,currentIndex,1))<0){break;} //--- Break if invalid char
            if(!isDouble){isDouble=(jsonCharacterArray[currentIndex]=='.' || jsonCharacterArray[currentIndex]=='e' || jsonCharacterArray[currentIndex]=='E');} //--- Set double flag
         }
         m_stringValue=GetSubstringFromArray(jsonCharacterArray,startOfNumber,currentIndex-startOfNumber); //--- Get number string
         if(isDouble){                                       //--- If double
            m_type=JsonDouble;                               //--- Set type to double
            m_doubleValue=StringToDouble(m_stringValue);     //--- Convert to double
            m_integerValue=(long)m_doubleValue;              //--- Convert to integer
            m_booleanValue=m_integerValue!=0;                //--- Set boolean
         }
         else{                                               //--- Else integer
            m_type=JsonInteger;                              //--- Set type to integer
            m_integerValue=StringToInteger(m_stringValue);   //--- Convert to integer
            m_doubleValue=(double)m_integerValue;            //--- Convert to double
            m_booleanValue=m_integerValue!=0;                //--- Set boolean
         }
         currentIndex--;                                     //--- Decrement index
         return true;                                        //--- Return true
         break;                                              //--- Exit case
      }
      case '\"':                                             //--- Start of string or key
         if(m_type==JsonObject){                             //--- If object type
            currentIndex++;                                  //--- Increment index
            int startOfString=currentIndex;                  //--- Set start of string
            if(!ExtractStringFromArray(jsonCharacterArray,arrayLength,currentIndex)){ //--- Extract string
               if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
               return false;                                 //--- Return false
            }
            m_temporaryKey=GetSubstringFromArray(jsonCharacterArray,startOfString,currentIndex-startOfString); //--- Set temporary key
         }
         else{                                               //--- Else value string
            if(m_type!=JsonUndefined){                       //--- Check type
               if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
               return false;                                 //--- Return false
            }
            m_type=JsonString;                               //--- Set type to string
            currentIndex++;                                  //--- Increment index
            int startOfString=currentIndex;                  //--- Set start of string
            if(!ExtractStringFromArray(jsonCharacterArray,arrayLength,currentIndex)){ //--- Extract string
               if(DEBUG_PRINT){Print(m_key+" "+string(__LINE__));} //--- Print debug
               return false;                                 //--- Return false
            }
            SetFromString(JsonString,GetSubstringFromArray(jsonCharacterArray,startOfString,currentIndex-startOfString)); //--- Set from extracted string
            return true;                                     //--- Return true
         }
         break;                                              //--- Exit case
      }
   }
   return true;                                           
      //--- Return true at end
}

我们继续实现解析框架,重点关注关键的序列化和反序列化方法。

首先,我们定义 "SerializeToString" 方法,将 JSON 结构转换为字符串。该方法会跳过未定义的类型;如果 "includeComma" 为 true,则追加逗号;如果 "includeKey" 为 true,则使用 StringFormat 追加键。随后根据 "m_type" 的值分别处理:"JsonNull" 追加 "null";"JsonBoolean" 根据 "m_booleanValue" 追加 "true" 或 "false";"JsonInteger" 使用 IntegerToString 转换 "m_integerValue";"JsonDouble" 使用 DoubleToString 转换 "m_doubleValue";"JsonString" 使用 "EscapeString" 对 "m_stringValue" 进行转义并用引号括起来(若为空则追加 "null");"JsonArray" 递归调用 "SerializeToString" 序列化子元素,并将它们括在方括号内(不包含键,在非首个元素前添加逗号);"JsonObject" 则将子元素括在大括号内,并包含键。"SerializeToString" 的一个便捷重载会创建一个字符串,使用默认实参调用带参数的版本,并返回结果。

接下来,我们实现 "DeserializeFromArray" 方法,通过解析字符数组来构建 JSON 结构。该方法使用包含有效数字字符的字符串("0123456789+-.eE"),并遍历字符数组:跳过空白字符;遇到数组起始符("[")时,将 "m_type" 设置为 "JsonArray",递归反序列化子元素,直到遇到右方括号,并验证数组是否正确闭合;处理键值分隔符(":")时,将 "m_temporaryKey" 赋给新建的子元素;处理值分隔符(",");遇到对象起始符("{")时,将 "m_type" 设置为 "JsonObject",反序列化子元素,直到遇到右大括号,并验证对象是否正确闭合;解析布尔值("true" 或 "false")时,设置 "m_booleanValue";解析空值("null")时,将 "m_type" 设置为 "JsonNull";解析数字时,检测是否包含小数点或使用指数表示法,据此将 "m_type" 设置为 "JsonDouble" 或 "JsonInteger";解析带引号的字符串时,使用 "ExtractStringFromArray" 处理转义字符。

"DeserializeFromArray" 方法确保父节点与子节点的关系正确,并通过 "DEBUG_PRINT" 日志对无效结构进行错误处理,从而能够稳健地解析响应。最后,我们可以定义转义方法了。

//+------------------------------------------------------------------+
//| Extracts string from array handling escapes                      |
//+------------------------------------------------------------------+
bool JsonValue::ExtractStringFromArray(char &jsonCharacterArray[],int arrayLength,int &currentIndex){
   for(; jsonCharacterArray[currentIndex]!=0 && currentIndex<arrayLength; currentIndex++){ //--- Loop through string
      char currentCharacter=jsonCharacterArray[currentIndex]; //--- Get current char
      if(currentCharacter=='\"') break;                      //--- Break on closing quote
      if(currentCharacter=='\\' && currentIndex+1<arrayLength){ //--- Handle escape
         currentIndex++;                                     //--- Increment for escaped char
         currentCharacter=jsonCharacterArray[currentIndex];  //--- Get escaped char
         switch(currentCharacter){                           //--- Handle escaped type
         case '/':
         case '\\':
         case '\"':
         case 'b':
         case 'f':
         case 'r':
         case 'n':
         case 't':
            break;                                           //--- Allowed escapes
         case 'u':                                           //--- Unicode escape
         {
            currentIndex++;                                  //--- Increment
            for(int hexDigitIndex=0; hexDigitIndex<4 && currentIndex<arrayLength && jsonCharacterArray[currentIndex]!=0; hexDigitIndex++,currentIndex++){ //--- Loop hex digits
               if(!((jsonCharacterArray[currentIndex]>='0' && jsonCharacterArray[currentIndex]<='9') || (jsonCharacterArray[currentIndex]>='A' && jsonCharacterArray[currentIndex]<='F') || (jsonCharacterArray[currentIndex]>='a' && jsonCharacterArray[currentIndex]<='f'))){ //--- Check hex
                  if(DEBUG_PRINT){Print(m_key+" "+CharToString(jsonCharacterArray[currentIndex])+" "+string(__LINE__));} //--- Print debug
                  return false;                                 //--- Return false on invalid hex
               }
            }
            currentIndex--;                                  //--- Decrement after loop
            break;                                           //--- Exit case
         }
         default:
            break;                                           //--- Handle other (commented return false)
         }
      }
   }
   return true;                                              //--- Return true
}
//+------------------------------------------------------------------+
//| Escapes special characters in string                             |
//+------------------------------------------------------------------+
string JsonValue::EscapeString(string stringValue){
   ushort inputCharacters[], escapedCharacters[];               //--- Declare arrays
   int inputLength=StringToShortArray(stringValue, inputCharacters); //--- Convert string to short array
   if(ArrayResize(escapedCharacters, 2*inputLength)!=2*inputLength){return NULL;} //--- Resize escaped array, return NULL on fail
   int escapedIndex=0;                                          //--- Initialize escaped index
   for(int inputIndex=0; inputIndex<inputLength; inputIndex++){ //--- Loop through input
      switch(inputCharacters[inputIndex]){                      //--- Handle special chars
      case '\\':
         escapedCharacters[escapedIndex]='\\';                  //--- Add escape
         escapedIndex++;                                        //--- Increment
         escapedCharacters[escapedIndex]='\\';                  //--- Add backslash
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      case '"':
         escapedCharacters[escapedIndex]='\\';                  //--- Add escape
         escapedIndex++;                                        //--- Increment
         escapedCharacters[escapedIndex]='"';                   //--- Add quote
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      case '/':
         escapedCharacters[escapedIndex]='\\';                  //--- Add escape
         escapedIndex++;                                        //--- Increment
         escapedCharacters[escapedIndex]='/';                   //--- Add slash
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      case 8:
         escapedCharacters[escapedIndex]='\\';                  //--- Add escape
         escapedIndex++;                                        //--- Increment
         escapedCharacters[escapedIndex]='b';                   //--- Add backspace
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      case 12:
         escapedCharacters[escapedIndex]='\\';                  //--- Add escape
         escapedIndex++;                                        //--- Increment
         escapedCharacters[escapedIndex]='f';                   //--- Add form feed
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      case '\n':
         escapedCharacters[escapedIndex]='\\';                  //--- Add escape
         escapedIndex++;                                        //--- Increment
         escapedCharacters[escapedIndex]='n';                   //--- Add newline
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      case '\r':
         escapedCharacters[escapedIndex]='\\';                  //--- Add escape
         escapedIndex++;                                        //--- Increment
         escapedCharacters[escapedIndex]='r';                   //--- Add carriage return
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      case '\t':
         escapedCharacters[escapedIndex]='\\';                  //--- Add escape
         escapedIndex++;                                        //--- Increment
         escapedCharacters[escapedIndex]='t';                   //--- Add tab
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      default:
         escapedCharacters[escapedIndex]=inputCharacters[inputIndex]; //--- Copy normal char
         escapedIndex++;                                        //--- Increment
         break;                                                 //--- Exit case
      }
   }
   stringValue=ShortArrayToString(escapedCharacters,0,escapedIndex); //--- Convert back to string
   return stringValue;                                          //--- Return escaped string
}
//+------------------------------------------------------------------+
//| Unescapes special characters in string                           |
//+------------------------------------------------------------------+
string JsonValue::UnescapeString(string stringValue){
   ushort inputCharacters[], unescapedCharacters[];             //--- Declare arrays
   int inputLength=StringToShortArray(stringValue, inputCharacters); //--- Convert to short array
   if(ArrayResize(unescapedCharacters, inputLength)!=inputLength){return NULL;} //--- Resize, return NULL on fail
   int outputIndex=0,inputIndex=0;                              //--- Initialize indices
   while(inputIndex<inputLength){                               //--- Loop through input
      ushort currentCharacter=inputCharacters[inputIndex];      //--- Get current char
      if(currentCharacter=='\\' && inputIndex<inputLength-1){   //--- Handle escape
         switch(inputCharacters[inputIndex+1]){                 //--- Handle escaped type
         case '\\':
            currentCharacter='\\';                              //--- Set to backslash
            inputIndex++;                                       //--- Increment
            break;                                              //--- Exit case
         case '"':
            currentCharacter='"';                               //--- Set to quote
            inputIndex++;                                       //--- Increment
            break;                                              //--- Exit case
         case '/':
            currentCharacter='/';                               //--- Set to slash
            inputIndex++;                                       //--- Increment
            break;                                              //--- Exit case
         case 'b':
            currentCharacter=8;                                 //--- Set to backspace
            inputIndex++;                                       //--- Increment
            break;                                              //--- Exit case
         case 'f':
            currentCharacter=12;                                //--- Set to form feed
            inputIndex++;                                       //--- Increment
            break;                                              //--- Exit case
         case 'n':
            currentCharacter='\n';                              //--- Set to newline
            inputIndex++;                                       //--- Increment
            break;                                              //--- Exit case
         case 'r':
            currentCharacter='\r';                              //--- Set to carriage return
            inputIndex++;                                       //--- Increment
            break;                                              //--- Exit case
         case 't':
            currentCharacter='\t';                              //--- Set to tab
            inputIndex++;                                       //--- Increment
            break;                                              //--- Exit case
         }
      }
      unescapedCharacters[outputIndex]=currentCharacter;        //--- Copy to output
      outputIndex++;                                            //--- Increment output
      inputIndex++;                                             //--- Increment input
   }
   stringValue=ShortArrayToString(unescapedCharacters,0,outputIndex); //--- Convert back to string
   return stringValue;                                          //--- Return unescaped string
}

我们最后实现字符串处理方法,完成整个类的实现。首先,我们实现 "ExtractStringFromArray" 方法。该方法遍历字符数组,直到遇到结束引号或数组末尾,从中解析出字符串;它会处理转义序列(例如 "\\"、"\""、"/"、"\b"、"\f"、"\n"、"\r"、"\t"),并通过验证Unicode转义序列("\uXXXX")中的四位十六进制数字来处理此类序列。如果遇到无效的十六进制数字或越界错误,则返回 false,并使用 "DEBUG_PRINT" 调试无效情况,从而确保在 JSON 解析过程中准确提取字符串。

接下来,我们实现 "EscapeString" 方法,将字符串转换为符合 JSON(JavaScript 对象表示法)规范的形式。该方法先使用 StringToShortArray 将字符串转换为短整型数组,再将输出数组的大小调整为输入长度的两倍,以容纳转义序列,然后遍历每个字符,处理特殊情况:反斜杠、引号、斜杠、退格符(8)、换页符(12)、换行符、回车符和制表符均以反斜杠开头的序列进行转义(例如,"\n" 表示换行符),其他字符则直接复制。最后,通过 ShortArrayToString 函数返回转义后的字符串。

最后,我们实现 "UnescapeString" 方法,执行转义的逆过程。该方法将输入字符串转换为短整型数组,将输出数组的大小调整为输入长度,然后遍历数组以处理转义序列:遇到反斜杠时,解析下一个字符(例如,将 "\n" 转换为换行符,将 "\t" 转换为制表符),并将反转义后的字符复制到输出数组中;非转义字符则直接复制。最后,通过 "ShortArrayToString" 返回反转义后的字符串;若调整数组大小失败,则返回 NULL。这些方法确保 "JsonValue" 类能够处理 JSON 字符串中的特殊字符,这对于正确格式化 API 请求以及可靠解析 AI 响应至关重要。下面的示例展示了这些特殊字符的用法,可以看到它们均被正确解析,使沟通更顺畅、理解更准确。

特殊字符的使用示例

类的实现已经完成,现在我们可以开始使用解析逻辑了。不过,让我们先测试一下解析器,确保一切正常。我们将在下一节中进行测试。


测试 JSON 解析器

为了确保 JSON 解析框架的可靠性,我们在 MQL5 中对 "JsonValue" 类进行严格测试,以验证其能否处理 AI API 集成所需的各种关键 JSON 结构。下文概述了测试方案,包括测试用例、预期结果以及在交易环境中验证解析器功能的方法。我们将定义一个函数,并在 OnInit 事件处理函数中调用它以打印输出。这里是第一段测试代码。我们仍沿用同一个源文件。首先,让我们像编写入门示例那样,输出 "Hello world"。

//+------------------------------------------------------------------+
//| Test Functions                                                   |
//+------------------------------------------------------------------+
void TestBasicSerialization(){
   Print("\n--- Testing Basic Serialization ---");
   
   JsonValue root;
   root["string"] = "hello world";
   root["number"] = 42;
   root["double"] = 3.14159;
   root["boolean"] = true;
   root["empty"] = "";
   
   string json = root.SerializeToString();
   Print("Serialized JSON: ", json);
   
   JsonValue parsed;
   if(parsed.DeserializeFromString(json)){
      Print("Deserialization successful");
      Print("String: ", parsed["string"].ToString());
      Print("Number: ", (int)parsed["number"].ToInteger());
      Print("Double: ", parsed["double"].ToDouble());
      Print("Boolean: ", parsed["boolean"].ToBoolean());
      Print("Empty: ", parsed["empty"].ToString());
   } else {
      Print("Deserialization failed!");
   }
}

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(){
   TestBasicSerialization();
return(INIT_SUCCEEDED);
}

我们创建一个 "TestBasicSerialization" 函数,再创建一个名为 "root" 的 "JsonValue" 对象,并使用 "operator[]" 为各字段赋值:将 "string" 设为 "hello world",将 "number" 设为 42,将 "double" 设为 3.14159,将 "boolean" 设为 true,将 "empty" 设为空字符串,涵盖主要的 JSON 数据类型(JsonString、JsonInteger、JsonDouble、JsonBoolean)。然后,我们对 "root" 调用 "SerializeToString" 生成 JSON 字符串,将其存储在 "json" 中,再将其输出到 MetaTrader 5 终端,使用的函数为 Print,以便验证。

接下来,我们创建一个名为 "parsed" 的新 "JsonValue" 对象,并以 "json" 字符串为参数调用 "DeserializeFromString" 来重建 JSON(JavaScript 对象表示法)结构,通过返回值判断反序列化是否成功;如果成功,则输出 "Deserialization successful",通过 "operator[]" 访问 "string"、"number"、"double"、"boolean" 和 "empty",并使用 "ToString"、"ToInteger"(将返回值强制转换为 int)、"ToDouble" 和 "ToBoolean" 获取并打印相应的值;如果失败,则输出 "Deserialization failed!"。最后,在 OnInit 中,我们调用 "TestBasicSerialization",在程序初始化时执行测试,并返回 "INIT_SUCCEEDED" 以表示初始化成功。以下是我们得到的输出结果。

初始基本序列化

从图片中可以看出,基本序列化已成功完成。现在让我们测试一下基本的反序列化,看看效果如何。

void TestBasicDeserialization(){
   Print("\n--- Testing Basic Deserialization ---");
   
   string testJson = "{\"name\":\"John\",\"age\":30,\"isStudent\":false,\"salary\":1500.75}";
   
   JsonValue parsed;
   if(parsed.DeserializeFromString(testJson)){
      Print("Parsed successfully:");
      Print("Name: ", parsed["name"].ToString());
      Print("Age: ", (int)parsed["age"].ToInteger());
      Print("Is Student: ", parsed["isStudent"].ToBoolean());
      Print("Salary: ", parsed["salary"].ToDouble());
   } else {
      Print("Failed to parse JSON");
   }
}

测试后,我们得到了以下结果。

初始基本反序列化

这项测试也成功了。现在让我们提高复杂度,看看会怎样。

void TestComplexObject(){
   Print("\n--- Testing Complex Object ---");
   
   JsonValue root;
   root["person"]["name"] = "Alice";
   root["person"]["age"] = 25;
   root["person"]["isActive"] = true;
   root["person"]["score"] = 95.5;
   root["person"]["address"]["street"] = "123 Main St";
   root["person"]["address"]["city"] = "New York";
   root["person"]["address"]["zipcode"] = "10001";
   
   root["person"]["hobbies"].AddChild("reading");
   root["person"]["hobbies"].AddChild("gaming");
   root["person"]["hobbies"].AddChild("coding");
   
   root["person"]["preferences"]["theme"] = "dark";
   root["person"]["preferences"]["notifications"] = true;
   
   string json = root.SerializeToString();
   Print("Complex JSON: ", json);
   
   JsonValue parsed;
   if(parsed.DeserializeFromString(json)){
      Print("Round-trip successful");
      Print("Name: ", parsed["person"]["name"].ToString());
      Print("Age: ", (int)parsed["person"]["age"].ToInteger());
      Print("City: ", parsed["person"]["address"]["city"].ToString());
      Print("Zipcode: ", parsed["person"]["address"]["zipcode"].ToString());
      Print("Theme: ", parsed["person"]["preferences"]["theme"].ToString());
      Print("Hobby count: ", ArraySize(parsed["person"]["hobbies"].m_children));
   }
}

void TestArrayHandling(){
   Print("\n--- Testing Array Handling ---");
   
   JsonValue root;
   
   // Array of numbers
   for(int i = 0; i < 5; i++){
      root["numbers"].AddChild(i * 10);
   }
   
   // Array of mixed types
   root["mixed"].AddChild("string");
   root["mixed"].AddChild(123);
   root["mixed"].AddChild(45.67);
   root["mixed"].AddChild(true);
   
   // Array of objects
   JsonValue item;
   item["id"] = 1;
   item["name"] = "Item 1";
   item["price"] = 19.99;
   root["items"].AddChild(item);
   
   item["id"] = 2;
   item["name"] = "Item 2";
   item["price"] = 29.99;
   root["items"].AddChild(item);
   
   // Nested arrays
   JsonValue nestedArray;
   nestedArray.AddChild("nested1");
   nestedArray.AddChild("nested2");
   root["nested"].AddChild(nestedArray);
   
   string json = root.SerializeToString();
   Print("Array JSON: ", json);
   
   JsonValue parsed;
   if(parsed.DeserializeFromString(json)){
      Print("Numbers array length: ", ArraySize(parsed["numbers"].m_children));
      Print("Mixed array length: ", ArraySize(parsed["mixed"].m_children));
      Print("Items array length: ", ArraySize(parsed["items"].m_children));
      Print("First item name: ", parsed["items"][0]["name"].ToString());
      Print("Second item price: ", parsed["items"][1]["price"].ToDouble());
   }
}

void TestErrorHandling(){
   Print("\n--- Testing Error Handling ---");
   
   JsonValue parsed;
   
   // Test invalid JSON
   string invalidJson = "{\"name\": \"test\", \"age\": }";
   if(!parsed.DeserializeFromString(invalidJson)){
      Print("✓ Correctly rejected invalid JSON");
   }
   
   // Test malformed JSON
   string malformedJson = "{\"name\": \"test\" \"age\": 30}"; // Missing comma
   if(!parsed.DeserializeFromString(malformedJson)){
      Print("✓ Correctly rejected malformed JSON");
   }
   
   // Test empty string
   if(!parsed.DeserializeFromString("")){
      Print("✓ Correctly handled empty string");
   }
   
   // Test incomplete object
   string incompleteJson = "{\"name\": \"test\"";
   if(!parsed.DeserializeFromString(incompleteJson)){
      Print("✓ Correctly rejected incomplete JSON");
   }
}

我们进行了测试,并得到了以下结果。

复杂测试

现在,让我们来测试性能、嵌套结构和数据类型。

void TestPerformance(){
   Print("\n--- Testing Performance ---");
   
   int startTime = GetTickCount();
   int iterations = 100;
   int successCount = 0;
   
   for(int i = 0; i < iterations; i++){
      JsonValue root;
      root["test_id"] = i;
      root["name"] = "Test Item " + IntegerToString(i);
      root["value"] = i * 1.5;
      root["active"] = (i % 2 == 0);
      
      // Add array
      for(int j = 0; j < 5; j++){
         root["tags"].AddChild("tag" + IntegerToString(j));
      }
      
      string json = root.SerializeToString();
      
      JsonValue parsed;
      if(parsed.DeserializeFromString(json)){
         successCount++;
      }
   }
   
   int endTime = GetTickCount();
   Print("Performance: ", iterations, " iterations in ", endTime - startTime, "ms");
   Print("Success rate: ", successCount, "/", iterations, " (", DoubleToString(successCount*100.0/iterations, 1), "%)");
}

void TestNestedStructures(){
   Print("\n--- Testing Nested Structures ---");
   
   JsonValue root;
   
   // Deep nesting
   root["level1"]["level2"]["level3"]["level4"]["value"] = "deep_nested";
   root["level1"]["level2"]["level3"]["level4"]["number"] = 999;
   
   // Array of objects with nesting
   JsonValue user;
   user["name"] = "John";
   user["profile"]["age"] = 30;
   user["profile"]["settings"]["theme"] = "dark";
   user["profile"]["settings"]["notifications"] = true;
   root["users"].AddChild(user);
   
   user["name"] = "Jane";
   user["profile"]["age"] = 25;
   user["profile"]["settings"]["theme"] = "light";
   user["profile"]["settings"]["notifications"] = false;
   root["users"].AddChild(user);
   
   string json = root.SerializeToString();
   Print("Nested JSON: ", json);
   
   JsonValue parsed;
   if(parsed.DeserializeFromString(json)){
      Print("✓ Nested structures parsed successfully");
      Print("Deep value: ", parsed["level1"]["level2"]["level3"]["level4"]["value"].ToString());
      Print("User count: ", ArraySize(parsed["users"].m_children));
      Print("First user theme: ", parsed["users"][0]["profile"]["settings"]["theme"].ToString());
      Print("Second user age: ", (int)parsed["users"][1]["profile"]["age"].ToInteger());
   }
}

void TestDataTypes(){
   Print("\n--- Testing Data Types ---");
   
   JsonValue root;
   
   // All supported data types
   root["string_type"] = "hello world";
   root["int_type"] = 42;
   root["long_type"] = 1234567890123;
   root["double_type"] = 3.14159265358979;
   root["bool_true"] = true;
   root["bool_false"] = false;
   root["empty_string"] = "";
   
   // Scientific notation
   root["scientific_positive"] = 1.23e+10;
   root["scientific_negative"] = 1.23e-10;
   
   string json = root.SerializeToString();
   Print("Data Types JSON: ", json);
   
   JsonValue parsed;
   if(parsed.DeserializeFromString(json)){
      Print("✓ All data types parsed successfully");
      Print("String: ", parsed["string_type"].ToString());
      Print("Integer: ", (int)parsed["int_type"].ToInteger());
      Print("Long: ", parsed["long_type"].ToInteger());
      Print("Double: ", parsed["double_type"].ToDouble());
      Print("Bool True: ", parsed["bool_true"].ToBoolean());
      Print("Bool False: ", parsed["bool_false"].ToBoolean());
      Print("Scientific Positive: ", parsed["scientific_positive"].ToDouble());
      Print("Scientific Negative: ", parsed["scientific_negative"].ToDouble());
   }
}

以下是输出结果。

性能、嵌套结构与数据类型测试

测试成功了。现在让我们来测试一下转义字符。

void TestEscapeCharacters(){
   Print("\n--- Testing Escape Characters ---");
   
   JsonValue root;
   
   // Various escape sequences - using only MQL5 supported escapes
   root["backslash"] = "\\\\"; // Double backslash for single backslash
   root["quote"] = "\\\"";     // Escaped quote
   root["newline"] = "\\n";    // Escaped newline
   root["tab"] = "\\t";        // Escaped tab
   root["carriage_return"] = "\\r"; // Escaped carriage return
   
   // For form feed and backspace, we need to use their actual ASCII codes
   // since MQL5 doesn't support \f and \b escape sequences
   root["form_feed"] = "\\u000C"; // Unicode escape for form feed
   root["backspace"] = "\\u0008"; // Unicode escape for backspace
   
   root["mixed_escapes"] = "Line1\\nLine2\\tTabbed\\\"Quoted\\\"\\\\Backslash";
   
   string json = root.SerializeToString();
   Print("Escape Chars JSON: ", json);
   
   JsonValue parsed;
   if(parsed.DeserializeFromString(json)){
      Print("✓ Escape characters parsed successfully");
      Print("Backslash: '", parsed["backslash"].ToString(), "'");
      Print("Quote: '", parsed["quote"].ToString(), "'");
      Print("Newline: '", parsed["newline"].ToString(), "'");
      Print("Tab: '", parsed["tab"].ToString(), "'");
      Print("Carriage Return: '", parsed["carriage_return"].ToString(), "'");
      Print("Form Feed: '", parsed["form_feed"].ToString(), "'");
      Print("Backspace: '", parsed["backspace"].ToString(), "'");
      Print("Mixed: '", parsed["mixed_escapes"].ToString(), "'");
   } else {
      Print("✗ Escape characters parsing failed");
   }
}

我们得到以下结果。

转义字符

测试成功了。既然我们已经确认 JSON 实现方案可行,那么在今后开发的项目中,我们就可以利用它来构建 AI 集成功能。


结论

总而言之,我们使用 MQL5 开发了一个 JSON(JavaScript 对象表示法)解析框架,并实现了"JsonValue"类,用于对 API(应用程序编程接口)交互中至关重要的 JSON 数据进行序列化和反序列化。通过"SerializeToString"、"DeserializeFromArray"和"EscapeString"等方法,以及借助"TestBasicSerialization"等函数进行测试,我们确保了对各种 JSON 结构的可靠处理,为未来的 AI 驱动的交易系统奠定了坚实的基础。在本系列的后续文章中,我们将把 AI 集成到交易应用程序中,并与之进行交互。敬请期待。

本文由MetaQuotes Ltd译自英文
原文地址: /en/articles/19562

附加的文件 |
最近评论 | 前往讨论 (2)
Peter Wlliams
Peter Wlliams | 23 9月 2025 在 23:44

看起来很棒。该从哪里开始呢?

下载的文件是 a._JSON_Code_File.mq5 和 EA 吗?

我将 A_JSON_Code_File.mq5 重命名为(看起来更熟悉一些),然后进行了编译。没有报错

不过我在平台上没有看到它被列为“专家”策略——也就是说,我无法加载并运行。

只需“摸索”一下,尝试理解发生了什么以及原因。


非常感谢您分享这个看似绝佳的利用人工智能的机会

Allan Munene Mutiiria
Allan Munene Mutiiria | 24 9月 2025 在 11:44
Peter Wlliams #:

看起来太棒了。从哪里开始呢?

下载文件是 a._JSON_Code_File.mq5 和 EA 吗?

我把 A_JSON_Code_File.mq5 重命名为 a._JSON_Code_File.mq5(这样看起来更眼熟),然后进行了编译。没有报错。

不过,我在平台上没有看到它被列为 EXPERT 策略——也就是说,我无法加载并运行它。

只需“摸索”一下,尝试理解发生了什么以及原因。


非常感谢您分享这一看似绝佳的利用人工智能的机会

感谢您的反馈。看来您确实需要仔细阅读这篇文章。文章主要介绍了如何通过JSON实现未来版本中AI的集成。
交易策略 交易策略
各种交易策略的分类都是任意的,下面这种分类强调从交易的基本概念上分类。
基于机器学习的多线程交易机器人:从概念到实现 基于机器学习的多线程交易机器人:从概念到实现
本文展示了如何使用 Python 和 MetaTrader 5 逐步开发一个基于机器学习的多线程交易机器人。探讨了系统架构,涵盖从数据采集、技术指标生成到 XGBoost 模型训练,并结合投资组合风险管理的全过程。并且详细介绍了数据增强、基于高斯混合模型的特征聚类,以及用于多个货币对并行交易的线程协调机制的实现。
新手在交易中的10个基本错误 新手在交易中的10个基本错误
新手在交易中会犯的10个基本错误: 在市场刚开始时交易, 获利时不适当地仓促, 在损失的时候追加投资, 从最好的仓位开始平仓, 翻本心理, 最优越的仓位, 用永远买进的规则进行交易, 在第一天就平掉获利的仓位,当发出建一个相反的仓位警示时平仓, 犹豫。
市场模拟:MQL5 中 SQL 的入门(三) 市场模拟:MQL5 中 SQL 的入门(三)
在上一篇文章中,我们通过一个示例,介绍了如何在 MQL5 中实现一个类以提供基本支持。其具体目的是为了将 SQL 代码存储在单独的脚本文件中。如此一来,我们便无需在 MQL5 源代码中将相同的 SQL 语句作为字符串字面量编写。尽管该方案切实可行,但我们仍可且应当对其若干方面加以改进。