通过遍历所有持仓单进行条件过滤下单
查询指定订单是否存在
// 查询指定订单是否存在
bool selectTicket(const string symbol, const int type, const string comment, const ulong magic)
{
string m_sym = "";
if(symbol == NULL || symbol == "") m_sym = _Symbol;
else m_sym = symbol;
// 获得持仓单总数
int len = PositionsTotal();
printf(len);
for(int i=0; i<len;i++)
{
// 根据序号返回交易订单号
ulong pos_ticket = PositionGetTicket(i);
// 判断持仓单号信息是否可以成功获取
if(PositionSelectByTicket(pos_ticket))
{
datetime pos_dt = (datetime)PositionGetInteger(POSITION_TIME);
string pos_sym = PositionGetString(POSITION_SYMBOL);
string pos_com = (string)PositionGetString(POSITION_COMMENT);
ulong pos_magic = PositionGetInteger(POSITION_MAGIC);
int pos_type = (int)PositionGetInteger(POSITION_TYPE);
//printf("交易品种: %s, 注释: %s, magic: %llu, 开仓时间: %s",pos_sym,pos_com,pos_magic,(string)pos_dt);
//printf("pos_com: %s, comment: %s",pos_com,comment);
if(pos_com == comment)printf("ok");
if(pos_magic == magic && pos_com == comment && pos_type == type)
{
//printf("该定单已经存在,交易品种: %s, 注释: %s, magic: %llu, 开仓时间: %s",
// pos_sym,pos_com,pos_magic,(string)pos_dt);
return true;
}
}
}
// 如果 magic, 注释, 方向都相等就不用在开单了
return false;
}
// buy方向下单函数组件
bool BuyAdd( const string symbol=NULL, // 交易品种 1
const double volume=0.01, // 定单手数 3
const int sl=0, // 止损价 4
const int tp=0, // 止盈价 5
const int deviation=5, // 滑点 6
const string comment="", // 定单注释 7
const ulong magic=8199231 // EA识别码 8
)
{
bool is_ticket = selectTicket(symbol,0, comment,magic);
if(!is_ticket)
return PositionSend(symbol, 0,volume,sl,tp,deviation,comment,magic);
else return false;
}
// sell方向下单函数组件
bool SellAdd( const string symbol=NULL, // 交易品种 1
const double volume=0.01, // 定单手数 3
const int sl=0, // 止损价 4
const int tp=0, // 止盈价 5
const int deviation=5, // 滑点 6
const string comment="", // 定单注释 7
const ulong magic=8199231 // EA识别码 8
)
{
bool is_ticket = selectTicket(symbol,1, comment,magic);
if(!is_ticket)
return PositionSend(symbol, 1,volume,sl,tp,deviation,comment,magic);
else return false;
}
调用层
#property copyright "Copyright 2022, Author:阿龙."
#property link "https://www.guapit.com"
#property description "MT5智能交易编程课程"
#property description "QQ: 8199231"
#property version "1.00"
// #include <Guapit/Symbols.mqh>
#include <Guapit/Trade.mqh>
void OnStart()
{
//selectTicket(NULL,0,"",8199231);
string symbol = "GBPUSD";
string com = symbol + " " + "Buy" + " " + (string)2;
//BuyAdd(symbol, 0.1,100,0,5,com,8199231);
string symbol2 = _Symbol;
string com2 = symbol2 + " " + "Sell" + " " + (string)3;
SellAdd(symbol2, 0.8,100,0,5,com2,8199231);
}