📋 期货持仓查询
PositionQuery.mq5
MQL5
/*
该例子演示EA如何获得持仓(即文华和快期界面中的"持仓")
*/
#property copyright "www.wewin28.com 1145412@qq.com"
#property link "http://www.wewin28.com"
#property version "1.00"
//引用mt5ctp.dll头文件,该DLL封装了全部CTP接口,EA通过该DLL调用CTP接口交易期货合约
#include <mt5ctp.mqh>
//引用CTP仓位回调类头文件
#include <CThostFtdcInvestorPositionField.mqh>
//逗号
ushort splitCommma=StringGetCharacter(",",0);
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//收到交易所推送的逐笔行情不断触发OnTick事件
void OnTick()
{
//检查是否已经连接交易所
if(getIsConnectCTP()==true && getIsLoginCTP()==true && getIsConfirmSettlementInfoCTP()==true)
{
//getPositionCTP()函数查询仓位,
//不同于外汇,期货交易中查询合约仓位后交易所不是马上返回数据,需要等待交易所异步返回数据
int res=getPositionCTP();
//返回值res=0 代表报单成功
//-1 表示网络连接失败
//-2,表示未处理请求超过许可数
//-3,表示每秒发送请求数超过许可数
//如果返回错误就打印
if(res!=0)
{
printf("getPositionCTP 错误 %s", res);
}
//交易所对我们有流量控制,规定我们在1秒钟内,最多只能发起几次查询请求(比如2-3次)
//如果我们查询请求得太快、太频繁超出了流量控制,交易所会拒绝我们的查询请求
//所以需要暂停1秒
Sleep(1000);
}
}
//不同于外汇,期货交易中查询仓位后交易所不是马上返回数据,需要等待交易所异步返回数据
//OnChartEvent函数是MQL中的一个预定义事件处理函数,当用户在图表上进行操作(如点击、按键、移动鼠标等)会触发该函数
//本软件可以通过 OnChartEvent函数得到交易所回调,这些回调代号的id都是3000,
//根据该代号可以区分哪些是交易所回调而非用户在图表上进行操作产生的事件
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
if(id==3000) //只处理MT5 CTP的事件 process MT5 CTP event only
{
//处理回调
string event = processChartEventMsg(sparam);
//printf(event);
string chartEvents[];
//按逗号将交易所回调字符串拆成数组chartEvents
int n=StringSplit(event,splitCommma,chartEvents);
if(n>0)
{
//数组第一个元素是回调类型,共有以下这几种回调:
//报单回调 OnRtnOrder
//成交回调 OnRtnTrade
//报单错误回调 OnErrRtnOrderInsert
//撤单错误回调 OnErrRtnOrderAction
//查询仓位回调 OnRspQryInvestorPosition
//查询资金回调 OnRspQryTradingAccount
//查询合约手续费回调 OnRspQryInstrumentCommissionRate
//查询合约保证金回调 OnRspQryInstrumentMarginRate
//查询仓位回调 OnRspQryInvestorPosition
string eventType=chartEvents[0];
//查询仓位后会收到OnRspQryInvestorPosition回调
if(eventType=="OnRspQryInvestorPosition")
{
CThostFtdcInvestorPositionField cThostFtdcInvestorPositionField(event);
//仓位合约
string symbol = cThostFtdcInvestorPositionField.getInstrumentID();
//是否最后1个仓位
bool isLast=cThostFtdcInvestorPositionField.getIsLast();
//仓位
int position=cThostFtdcInvestorPositionField.getPosition();
//多空
string direction=cThostFtdcInvestorPositionField.getPosiDirection();
//交易所
string exchange=cThostFtdcInvestorPositionField.getExchangeID();
//本次结算价
double settlementPrice=cThostFtdcInvestorPositionField.getSettlementPrice();
//持仓成本
double positionCost=cThostFtdcInvestorPositionField.getPositionCost();
//开仓成本
double openCost=cThostFtdcInvestorPositionField.getOpenCost();
//保证金
double margin=cThostFtdcInvestorPositionField.getUseMargin();
if(symbol != "")
{
positionData pos;
if(position > 0 || isLast == true)
{
string posName = symbol + "." + direction;
int positionIndex = findPosDict(posName);
if(positionIndex >= 0)
{
pos = posDict[positionIndex].data;
}
else
{
pos.symbol = symbol;
pos.direction = direction;
pos.exchange = exchange;
pos.position = 0;
pos.ydPosition = 0;
pos.price = 0;
pos.positionProfit = 0;
pos.frozen = 0;
pos.openPrice = 0;
pos.pnl = 0;
pos.margin = 0;
}
//昨仓
int ydPosition = cThostFtdcInvestorPositionField.getYdPosition();
//今仓
int todayPosition = cThostFtdcInvestorPositionField.getTodayPosition();
//今日持仓
int position = cThostFtdcInvestorPositionField.getPosition();
//交易所
string exchange = cThostFtdcInvestorPositionField.getExchangeID();
//处理昨仓
if(exchange == "SHFE")
{
if(ydPosition > 0 && todayPosition == 0)
{
pos.ydPosition = position;
}
}
else
{
pos.ydPosition = position - todayPosition;
}
//通过SYMBOL_TRADE_CONTRACT_SIZE属性获得合约每手乘数
double size=SymbolInfoDouble(symbol, SYMBOL_TRADE_CONTRACT_SIZE);
if(size >= 0)
{
//计算开仓价格
double openPrice = 0;
if(position > 0 && size > 0)
{
openPrice = openCost / (position * size);
}
openPrice = NormalizeDouble(openPrice, 4);
pos.openPrice = openPrice;
//计算逐笔浮盈
if(pos.direction == "2") //计算多仓
{
double pnl = (settlementPrice - openPrice) * position * size;
pos.pnl = NormalizeDouble(pnl, 0);
}
else //计算空仓
{
double pnl = (openPrice - settlementPrice) * position * size;
pos.pnl = NormalizeDouble(pnl, 0);
}
pos.position = position;
//盯市浮盈
pos.positionProfit = cThostFtdcInvestorPositionField.getPositionProfit();
//仓位保证金
pos.margin = margin;
double cost = pos.price * pos.position * size;
//计算持仓均价
if(pos.position > 0 && size > 0)
{
pos.price = (cost + positionCost) / (pos.position * size);
}
//冻结
if(pos.direction == "2") // 多头
{
pos.frozen += cThostFtdcInvestorPositionField.getShortFrozen();
}
else // 空头
{
pos.frozen += cThostFtdcInvestorPositionField.getLongFrozen();
}
//今仓
pos.todayPosition = todayPosition;
//如果有持仓
if((pos.todayPosition + pos.ydPosition) > 0)
{
//查找持仓数组中是否已经有该持仓
int i = findPosDict(posName);
//如果持仓数组中已有该仓位就进行更新
if(i >= 0)
{
double iterCost = posDict[i].data.price * posDict[i].data.position * size;
double iterOpenCost = posDict[i].data.openPrice * posDict[i].data.position * size;
double openPriceCalc = 0;
if(position > 0 && size > 0)
openPriceCalc = openCost / (position * size);
openPriceCalc = NormalizeDouble(openPriceCalc, 4);
double pnlCalc;
if(pos.direction == "2")
pnlCalc = (settlementPrice - openPriceCalc) * position * size;
else
pnlCalc = (settlementPrice - openPriceCalc) * position * size * (-1);
// 更新持仓数据
posDict[i].data.position += pos.position;
posDict[i].data.todayPosition += pos.todayPosition;
if(posDict[i].data.position > 0 && size > 0)
{
posDict[i].data.price = (iterCost + positionCost) / (posDict[i].data.position * size);
posDict[i].data.price = NormalizeDouble(posDict[i].data.price, 1);
posDict[i].data.openPrice = (iterOpenCost + openCost) / (posDict[i].data.position * size);
posDict[i].data.openPrice = NormalizeDouble(posDict[i].data.openPrice, 1);
}
posDict[i].data.pnl += pnlCalc;
posDict[i].data.positionProfit += cThostFtdcInvestorPositionField.getPositionProfit();
posDict[i].data.margin += margin;
}
else //如果没有该仓位就新增持仓数组
{
insertOrUpdatePosDict(posName, pos);
}
}
//处理完最后1个仓位输出仓位信息
if(isLast==true)
{
for(int i = 0; i < posDictCount; i++)
{
positionData data = posDict[i].data;
int ydPosition = data.position - data.todayPosition;
string buySell;
if(data.direction=="2")
{
buySell="多仓";
}
else
{
buySell="空仓";
}
printf("交易所:%s 合约:%s %s 昨仓:%d 今仓:%d 持仓:%d 持仓价格:%.2f 盯市浮盈:%.2f 开仓均价:%.2f 逐笔浮盈:%.2f 保证金:%.2f",
data.exchange, data.symbol,buySell, ydPosition,data.todayPosition,data.position,
data.price,data.positionProfit,data.openPrice,data.pnl,data.margin);
}
// 清空持仓数组
ArrayResize(posDict, 0);
posDictCount = 0;
}
}
else
{
printf("%s 没有每手乘数", symbol);
}
}
}
}
}
}
}
//定义仓位结构体
struct positionData
{
string symbol; //合约
string direction; //方向
string exchange; //交易所
int position; //持仓
int ydPosition; //昨仓
int todayPosition;//今仓
double price; //持仓价格
double positionProfit; //盯市浮盈
int frozen;
double openPrice; //开仓均价
double pnl; //逐笔浮盈
double margin; //保证金
};
struct positionItem
{
string key;
positionData data;
};
//仓位数组
positionItem posDict[];
int posDictCount = 0;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int findPosDict(string key)
{
for(int i = 0; i < posDictCount; i++)
{
if(posDict[i].key == key)
return i;
}
return -1;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void insertOrUpdatePosDict(string key, positionData &pos)
{
int index = findPosDict(key);
if(index >= 0)
{
posDict[index].data = pos;
}
else
{
ArrayResize(posDict, posDictCount + 1);
posDict[posDictCount].key = key;
posDict[posDictCount].data = pos;
posDictCount++;
}
}
//+------------------------------------------------------------------+