Download MetaTrader 5

How to close a position programatically in Hedging mode

To add comments, please log in or register
Miroslav Popov
Miroslav Popov 2016.07.25 09:29 

Let's open a position in a Hedge account with a given Magic_Number on the current _Symbol.

void SendOrder(int command,double lots,double stopLoss,double takeProfit)
   MqlTick             tick;    SymbolInfoTick(_Symbol,tick);
   MqlTradeRequest     request; ZeroMemory(request);
   MqlTradeResult      result;  ZeroMemory(result);
   MqlTradeCheckResult check;   ZeroMemory(check);

   request.action       = TRADE_ACTION_DEAL;
   request.symbol       = _Symbol;
   request.volume       = Entry_Amount;
   request.type         = command==OP_BUY ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   request.price        = command==OP_BUY ? tick.ask :;
   request.type_filling = orderFillingType;
   request.deviation    = 10;           = stopLoss;           = takeProfit;
   request.magic        = Magic_Number;

   bool isOrderCheck = OrderCheck(request,check);
   bool isOrderSend  = false;



Open Long 0.1 lots.

SendOrder(OP_BUY, 0.1, 0, 0);


How to find this position and close it?

I assume I have to first open an opposite one: 

SendOrder(OP_SELL, 0.1, 0, 0);

 Ok. Now I have one long and one short positions with the same magic number.

How to execute CloseBy ?

Stanislav Korotky
Stanislav Korotky 2016.07.25 15:06  
Send an order in reverse direction using position id obtained after the first order execution. Here is some code.
Nguyen Nga
Nguyen Nga 2016.07.25 19:28  

All function in Include\Trade\Trade.mqh

i think it is easy for coding.

Miroslav Popov
Miroslav Popov 2016.07.25 21:46  

Thank you.

I tried the Stanislav's recommendation and it works so far.

It was necessary simply to find the position ticket and to set it in the opposite order's request.


Find ticket:

   int posTotal=PositionsTotal();
   for(int posIndex=0;posIndex<posTotal;posIndex++)
      ulong ticket=PositionGetTicket(posIndex);
      if(PositionSelectByTicket(ticket) &&
         PositionGetString(POSITION_SYMBOL)==_Symbol &&
         posType   = PositionGetInteger(POSITION_TYPE);
         posLots   = PositionGetDouble(POSITION_VOLUME);
         posTicket = ticket;

  Set ticket in request:


         request.position     = ticket;
To add comments, please log in or register