MQL5 CloseTradeFunction

 
//_____________________________________________________________________________________________________________________________
bool CloseMarginals(double fSpot){//
//=============================================================================================================================
MqlTradeRequest request;
MqlTradeResult result;

bool fCloseOK = false;

   PosTotal=PositionsTotal();
   for(cnt=0 ;cnt < PosTotal; cnt++)
     {  
      if((ticket = PositionGetTicket(cnt)) > 0  &&  PositionGetString(POSITION_SYMBOL) == _Symbol){
         PosMagic = PositionGetInteger(POSITION_MAGIC);
         if(MagicToSpot(PosMagic) == fSpot && MagicXX(PosMagic) != 1) {

         ZeroMemory(request);
         ZeroMemory(result);

         request.position  = ticket;        
         request.action    = DEAL_TYPE_BUY_CANCELED; // << === HOW TO DELETE HERE ???
      
         fCloseOK = OrderSend(request,result);
        
         //--- output information about the closure by opposite position
         PrintFormat("Close #%I64d %s %s by #%I64d",ticket,_Symbol,request.position_by);
         //--- send the request
         if(!fCloseOK)
            PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, output the error code
            
         //--- information about the operation  
         PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);      

         }                
      }
   }
return(fCloseOK);//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}//CloseMarginals()

I am working on a close all with this MagicNumber Routine but i can not close the Positions. I am confused how i close the Position.
I am also confused by TRADE_ACTION_CLOSE_BY  8-\

fSpot is the actual price that will be transformed in a MagicNummer 1.052 ==> 0010520xx and the xx ar the MarginalCycles on
that price level (Just additional info's).

As a workaround i tried to use the cTrade class bud was not able to include it properly ?!

#include <Trade\Trade.mqh>
class CTrade : public CObject;

I prefer the first method, then i learn more how it realy works in details, but cTrade could also work.

Hope this is clear so far - thank you


 

 
You should read the documentation, there is a full example below "Example of the TRADE_ACTION_DEAL trade operation for closing positions:"

request.action    = DEAL_TYPE_BUY_CANCELED; // << === HOW TO DELETE HERE ???

Action is a trade action, not a deal type. You need to check your position direction and use opposite direction to close.

 
Thank you Alain, I googled for hours and could not find this section. I think i understand it wath i sea. Ill work on it tomorrow, and come back - thanx so far.
 

Things are so much easyse when u can RTFM!

There u go:

ulong          ticket;
ulong          PosMagic;

//_____________________________________________________________________________________________________________________________
bool CloseMarginals(double fSpot){//
//=============================================================================================================================

bool fCloseOK = false;
bool fCloseFAIL = false;

MqlTradeRequest request;
MqlTradeResult result;

PosTotal=PositionsTotal();  
for(cnt=PosTotal-1; cnt >=0; cnt--){
  
   ticket   = PositionGetTicket(cnt);      
   PosMagic = PositionGetInteger(POSITION_MAGIC);                          

      if(MagicToSpot(PosMagic) == fSpot && MagicXX(PosMagic) != 1 && _Symbol == PositionGetString(POSITION_SYMBOL)){ //ENTER CONDITION HERE...
              
         ZeroMemory(request);
         ZeroMemory(result);
        
         request.action    = TRADE_ACTION_DEAL;
         request.position  = ticket;
         request.symbol    = PositionGetString(POSITION_SYMBOL);
         request.volume    = PositionGetDouble(POSITION_VOLUME);
         request.deviation = 5;
         request.magic     = PosMagic;
        
         if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY){
            request.price=SymbolInfoDouble(_Symbol,SYMBOL_BID);
            request.type =ORDER_TYPE_SELL;
         }
         else{
            request.price=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
            request.type =ORDER_TYPE_BUY;
         }

      fCloseOK = OrderSend(request,result);        
      if(!fCloseOK)PrintFormat("OrderSend error %d",GetLastError());
      
      if(!fCloseFAIL) fCloseFAIL = !fCloseOK;
      }                
   }
return(fCloseFAIL);//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}//CloseMarginals()

This leads to a question about deviation. Has anyone experience on MT5 is 5 ok?

 
Zar88:
...

This leads to a question about deviation. Has anyone experience on MT5 is 5 ok?

Nothing directly related to MT5, it's allowed slippage, it works the same as with MT4/mql4.
 
I know - in MT4 i used 2 Pips - on my Broker this is 20 Points. This is why i ask will 5 (Like it is on dokumantation)
work on average ?? I thin ill program it variable then i can test it on real account and change value.

Any experience 5,10,20 - Shure not more then 20 right ?
 
Zar88:
I know - in MT4 i used 2 Pips - on my Broker this is 20 Points. This is why i ask will 5 (Like it is on dokumantation)
work on average ?? I thin ill program it variable then i can test it on real account and change value.

Any experience 5,10,20 - Shure not more then 20 right ?
Use deviation = ULONG_MAX
 

Hello,

 

i use this function, its working in my EA.

at first i close all open trades, and then i close all pending order, use MT5 with hedging

 

void CloseAll()
  {

   MqlTradeRequest request={0};
   MqlTradeResult  result={0};

   int total=PositionsTotal(); // number of open positions  
//--- iterate over all open positions

   for(int i=total-1; i>=0; i--)
     {
      //--- parameters of the order
      ulong  position_ticket=PositionGetTicket(i);                                      // ticket of the position
      string position_symbol=PositionGetString(POSITION_SYMBOL);                        // symbol
      int    digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS);              // number of decimal places
      ulong  Magic=PositionGetInteger(POSITION_MAGIC);                                  // MagicNumber of the position
      double volume=PositionGetDouble(POSITION_VOLUME);                                 // volume of the position
      ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);    // type of the position
      //--- output information about the position
      PrintFormat("#%I64u %s  %s  %.2f  %s [%I64d]",
                  position_ticket,
                  position_symbol,
                  EnumToString(type),
                  volume,
                  DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
                  Magic);

      if(Magic==MN)
        {
         //--- zeroing the request and result values
         ZeroMemory(request);
         ZeroMemory(result);
         //--- setting the operation parameters
         request.action   =TRADE_ACTION_DEAL;        // type of trade operation
         request.position =position_ticket;          // ticket of the position
         request.symbol   =position_symbol;          // symbol
         request.volume   =volume;                   // volume of the position
         request.deviation=Slip;                        // allowed deviation from the price
         request.magic=MN;             // MagicNumber of the position
         //--- set the price and order type depending on the position type

         if(type==POSITION_TYPE_BUY)
           {
            request.price=SymbolInfoDouble(position_symbol,SYMBOL_BID);
            request.type =ORDER_TYPE_SELL;
           }
         else
           {
            request.price=SymbolInfoDouble(position_symbol,SYMBOL_ASK);
            request.type =ORDER_TYPE_BUY;
           }
         //--- output information about the closure
         PrintFormat("Close #%I64d %s %s",position_ticket,position_symbol,EnumToString(type));
         //--- send the request
         if(!OrderSend(request,result))
            PrintFormat("OrderSend error %d",GetLastError());  // if unable to send the request, output the error code
         //--- information about the operation  
         PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
         //---

        }
     }

   ClosePending();
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ClosePending()
  {

   MqlTradeRequest request={0};
   MqlTradeResult  result={0};
   int total=OrdersTotal(); // Anzahl platzierter Pending Orders
//--- in allen platzierten Pending Orders suchen
   for(int i=total-1; i>=0; i--)
     {
      ulong  order_ticket=OrderGetTicket(i);                   // das Ticket der Order
      ulong  magic=OrderGetInteger(ORDER_MAGIC);               // MagicNumber der Order
      //--- wenn die MagicNumber übereinstimmt
      if(magic==MN)
        {
         //--- die Werte der Anfrage und des Ergebnisses auf Null setzen
         ZeroMemory(request);
         ZeroMemory(result);
         //--- Parameter der Transaktion setzen    
         request.action=TRADE_ACTION_REMOVE;                   // Typ der Transaktion
         request.order = order_ticket;                         // das Ticket der Order
         //--- Anfrage senden
         if(!OrderSend(request,result))
            PrintFormat("OrderSend error %d",GetLastError());  // wenn die Anfrage konnte nicht gesendet werden, den Fehlercode anzeigen
         //--- Details zur Transaktion  
         PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
        }
     }

  }
//+--------------------------------------


 amando

Reason: