How to close a position programatically in MT5 Hedge

Ask your basic questions confidently here. Flaming is not allowed. Sympathetic help is the order of the day.
Post Reply
User avatar
Popov
Trader
Posts: 36
Joined: Sun May 19, 2013 3:14 am

How to close a position programatically in MT5 Hedge

Post by Popov »

Hello Traders,

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

Code: Select all

void SendOrder(int command,double lots,double stopLoss,double takeProfit)
  {
   ResetLastError();
   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 : tick.bid;
   request.type_filling = orderFillingType;
   request.deviation    = 10;
   request.sl           = stopLoss;
   request.tp           = takeProfit;
   request.magic        = Magic_Number;

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

   if(isOrderCheck)
      isOrderSend=OrderSend(request,result);
  }
Open Long 0.1 lots.

Code: Select all

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:

Code: Select all

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 ?
User avatar
Popov
Trader
Posts: 36
Joined: Sun May 19, 2013 3:14 am

How to close a position programatically in MT5 Hedge

Post by Popov »

I think I managed to make it working.

It was necessary to find the position ticket:

Code: Select all

   int posTotal=PositionsTotal();
   for(int posIndex=0;posIndex<posTotal;posIndex++)
     {
      ulong ticket=PositionGetTicket(posIndex);
      if(PositionSelectByTicket(ticket) &&
         PositionGetString(POSITION_SYMBOL)==_Symbol &&
         PositionGetInteger(POSITION_MAGIC)==Magic_Number)
        {
         posType   = PositionGetInteger(POSITION_TYPE);
         posLots   = PositionGetDouble(POSITION_VOLUME);
         posTicket = ticket;
         break;
        }
     }
And then to set it in the opposite request:

Code: Select all

         request.position     = ticket;
Post Reply

Return to “EA's for Dummies.”