Appearance
成交信息类方法
类与对象
历史成交类定义在MT5CTP命名空间,需要显性调用,定义历史成交类的操作对象:
MQL5
// 类可理解为自定义类型,使用自定义类型定义了一个变量(对象) this_deal
MT5CTP::CDealInfo this_deal;
// 调用对象方法 : 使用序号选定成交,成交序号从1开始
for(int i = this_deal.Total(); i > 0; i--) {
if(!this_deal.SelectByIndex(i))
continue;
// do...
}MQL支持动态指针,但需要自己管理指针的生命周期,如果不是必须,不建议使用:
MQL5
// 类可理解为自定义类型,使用自定义类型定义了一个变量(对象) this_deal
MT5CTP::CDealInfo *this_deal= new MT5CTP::CDealInfo();
if(CheckPointer(this_deal)==POINTER_DYNAMIC) {
// 调用对象方法 : 使用序号选定成交,成交序号从1开始
for(int i = this_deal.Total(); i > 0; i--) {
if(!this_deal.SelectByIndex(i))
continue;
// do...
}
// 销毁动态指针
delete(this_deal);
}扩展类功能
如果类的方法无法满足应用场景,可以使用继承的方式扩展类功能,在新的类中定义新方法,实现新功能(注意继承中使用的命名空间)。
MQL5
// 定义名为'NewDeal'的新类,继承自 MT5CTP::CDealInfo
class NewDeal:public MT5CTP::CDealInfo {
// do...
}完整的例子
三步走完成输出历史成交数据到日志的脚本代码:
MQL5
#property copyright "Copyright 2026, MT5CTP项目组"
#property link "mt5ctp@qq.com"
#property version "1.00"
#property description "MT5CTP功能Demo|仅用于量化投资爱好者测试、研究"
#property description "基于MT5CTP类库[API 2.00 build 0030]"
//+------------------------------------------------------------------+
//| Include & Define |
//+------------------------------------------------------------------+
// 第一步:导入MT5CTP类库
#include <mt5ctp\DealInfo.mqh>
// 第二步:定义历史成交对象 _self_deal,注意调用命名空间 MT5CTP
MT5CTP::CDealInfo _self_deal;
// 自定义结构体
struct OuterDeal {
string symbol; // 合约代码
string direction; // 买卖
string type; // 开平
long volume; // 成交数量
double price; // 成交价格
datetime time; // 成交日期时间
double profit; // 盯市平仓盈亏
double commission; // 成交手续费
string comment; // [MT5持仓]注释
};
// 定义结构体数组
OuterDeal outer[];
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart() {
// 输出信息准备,结构体数组初始化
int total = _self_deal.Total();
ArrayResize(outer,total);
// 第三步:历史成交对象循环遍历,提取数据
// 务必注意成交序号是从1开始,不是从0开始
int outer_index = WRONG_VALUE;
for(int i = 1; i <= total; i++) {
if(!_self_deal.SelectByIndex(i))
continue;
// 提取成交数据,填充输出结构体数组
::ZeroMemory(outer[++outer_index]);
outer[outer_index].symbol = _self_deal.Symbol();
outer[outer_index].direction = _self_deal.DirectionDescription();
outer[outer_index].type = _self_deal.OffsetDescription();
outer[outer_index].volume = _self_deal.Volume();
outer[outer_index].price = _self_deal.Price();
outer[outer_index].time = _self_deal.Time();
outer[outer_index].profit = _self_deal.CloseProfitByDate();
outer[outer_index].commission = _self_deal.Commission();
outer[outer_index].comment = _self_deal.Comment();
}
// 输出成交信息
ArrayPrint(outer);
}
//+------------------------------------------------------------------+