Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1113

 

Greetings. I've watched the competent video "From MQL4 to MQL5 - how to rewrite EAs for Metatrader 5".
Many thanks to the author. I have decided to try it myself. I decided to try it myself. The idea is as follows:
1. I set dtriger = 1 in the inputs - Buy opens.
2. I set dtriger = -1 - Sell opens.
3. I set dtriger = 0 - all open ones are closed.
I read in the MT5 manuals that it is not possible to hold opposite positions,
and I have them.
Question: How can I correctly prescribe the closing of an open position
The question is: How to correctly register the closure of an existing position at opening a reverse one?
Many thanks.

#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\OrderInfo.mqh>

CPositionInfo   o_position;
CTrade        o_trade;
CSymbolInfo        o_symbol;
COrderInfo         o_order;

input int          triger            = 0;
input double    StartLot             = 0.01;
input double    lpos_volume       = 1.0;
input int          Step         = 10;
input int          MagicNumber    = 12345;      //      Magic   nuaber
input int          Slippage          = 30;         //   slippage

int dtriger;
int dStep;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   dStep = Step ;
   dtriger = triger ;

   if (!o_symbol.Name(Symbol()))
     return(INIT_FAILED);
   
   RefreshRates();
   
   o_trade.SetExpertMagicNumber(MagicNumber) ;

   if (IsFillingTypeAllowed(o_symbol.Name(), SYMBOL_FILLING_FOK))
   { 
      o_trade.SetTypeFilling(ORDER_FILLING_FOK);
   }
   else if (IsFillingTypeAllowed(o_symbol.Name(), SYMBOL_FILLING_IOC))
   { 
      o_trade.SetTypeFilling(ORDER_FILLING_IOC);
   }
   else 
   {
      o_trade.SetTypeFilling(ORDER_FILLING_RETURN);
   }
      o_trade.SetDeviationInPoints(Slippage);
   
   if (o_symbol.Digits() == 3 || o_symbol.Digits() == 5 )
   {
      dStep = 10 ;
   }
   
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
      datetime              lpos_time          =        0;
      double                lpos_price_open    =        0.0;
      ENUM_POSITION_TYPE   lpos_type           =        -1;
      int                      pos_count               =        0;
      double                sum_profit         = 0;
 
   for (int i = PositionsTotal() - 1; i>=0; i--)
   {
      if (o_position.SelectByIndex(i))
      {
         if (o_position.Symbol() == o_symbol.Name() && o_position.Magic() == MagicNumber)
         {
            if (o_position.Time() > lpos_time)
            {  
               lpos_time       = o_position.Time();            //OrderOpenTime();
               lpos_price_open = o_position.PriceOpen();       //OrderOpenPrice();
               lpos_type       = o_position.PositionType() ;   //OrderTipe();
             }  
            
            pos_count++;
            sum_profit = sum_profit + o_position.Commission() + o_position.Swap() + o_position.Profit() ;
          }     
       }     
    }          

   // Считаем кол-во отложенных ордеров
  int stop_count=0;

   for (int i=OrdersTotal()-1; i >=0; i--) 
   {
      if (o_order.SelectByIndex(i)) 
      {
         if (o_order.Symbol() == o_symbol.Name() && o_order.Magic() == MagicNumber) 
           stop_count++;
      }
   }

   if (!RefreshRates())
     return ;
     
   if(dtriger == 0 )
   {
      CloseAll();
      return;               
   } 
   
  // + -----    Откраваем Первый ордер   ++++++++++
 if (pos_count == 0  && stop_count == 0    )
   {
      if ( dtriger == -1 &&  lpos_type != POSITION_TYPE_SELL)
      {
         o_trade.Sell(StartLot * lpos_volume , o_symbol.Name());  //   S E L L   11111
      }
      
      if ( dtriger == 1 &&  lpos_type != POSITION_TYPE_BUY )
      {
         o_trade.Buy(StartLot * lpos_volume , o_symbol.Name());   //   B U Y    11111
      }
   }
                          

// +  -----   Переворот    ++++++++++++++++++++++++++++   

if (pos_count>0)
   {
      if(lpos_type == POSITION_TYPE_BUY )
      {
         if ( dtriger == -1 )
         {
         o_trade.Sell(StartLot * lpos_volume , o_symbol.Name());   //   S E L L   +++++
         }
      }

      if (lpos_type==POSITION_TYPE_SELL )
      {
         if ( dtriger == 1 )
         {
         o_trade.Buy(StartLot * lpos_volume , o_symbol.Name());       //   B U Y    +++++
         }
      }
   }


   if(pos_count>0 && stop_count>0) 
     DeleteStopOrders() ;
  
} 
//-----------------------------------------------------------
bool RefreshRates()
{
   if (!o_symbol.RefreshRates())
     return(false) ;
     
    if (o_symbol.Ask() == 0 || o_symbol.Bid() == 0)
      return(false);
      
    return(true);
}  
//---  --------------------------------------------------------- 
 bool IsFillingTypeAllowed (string symbol, int fill_type)
{ 
   int filling = (int)SymbolInfoInteger(symbol, SYMBOL_FILLING_MODE); 
 
   return((filling && fill_type) == fill_type) ;
} 
 
 //  -------------------------------------------------- 
   void CloseAll()
{
   for (int index = PositionsTotal()-1; index >=0; index--)
   {
      if (o_position.SelectByIndex(index))
      {
         if (o_position.Symbol() == o_symbol.Name() && o_position.Magic() == MagicNumber)
         {
            o_trade.PositionClose(o_position.Ticket());
         }
      }  
    } 
 } 
  
 //----------------------------------------------------------- 
 // Delete all pending orders
 //-------------------------------------
 void DeleteStopOrders()
 {
    for (int i = OrdersTotal() - 1; i >= 0; i-- ) 
   {
      if (o_order.SelectByIndex(i))
         if(o_order.Symbol() == o_symbol.Name() && o_order.Magic() == MagicNumber)
            o_trade.OrderDelete(o_order.Ticket());
   }
 } 
 
//+------------------------------------------------------------------+
 
procom:

Greetings. I have watched the helpful clip "From MQL4 to MQL5 - how to rewrite EAs for Metatrader 5".
I would like to congratulate the author. I have decided to try it myself. I wrote it. My idea is the following:
1. I set dtriger = 1 - opens Buy.
2. I set dtriger = -1 - Sell opens.
3. I set dtriger = 0 - all open ones are closed.
I read in the MT5 manuals that it is not possible to hold opposite positions,
and I have them.
Question: how to correctly prescribe the closing of an existing position
The question is: How to correctly register the closure of an existing position at opening a reverse one?
Many thanks.

You must have been very inattentive when reading the fact sheet.

Reference:General principles - Trading operations.

Bottom line: MetaTrader 5 has bothNetting and Hedgingsystems .

Общие принципы - Торговые операции - MetaTrader 5
Общие принципы - Торговые операции - MetaTrader 5
  • www.metatrader5.com
Перед тем как приступить к изучению торговых функций платформы, необходимо создать четкое представление об основных терминах: ордер, сделка и позиция. — это распоряжение брокерской компании купить или продать финансовый инструмент. Различают два основных типа ордеров: рыночный и отложенный. Помимо них существуют специальные ордера Тейк Профит...
 

I would formulate your task differently:

1. dtriger = 1 - Buy opens.
2. dtriger = -1 - Sell opens.
3. dtriger = 0 - all open ones are closed.

The Expert Advisor should do the following:

  • if you need to open BUY - you should first close SELL (issue a command to close SELL positions - it does not matter whether they are there or not)
  • if you need to open SELL - then first you need to close BUY (a command for closing BUY positions will be issued, no matter whether they are there or not)
  • if the client needs to close all - then just close all positions (no matter whether they BUY or SELL)

Two algorithms are needed for implementation (the magic number also contributes here) - it can be disabled.

//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions(const ENUM_POSITION_TYPE pos_type)
  {
   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of current positions
      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
            if(m_position.PositionType()==pos_type) // gets the position type
               m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
  }

и

//+------------------------------------------------------------------+
//| Close all positions                                              |
//+------------------------------------------------------------------+
void CloseAllPositions(void)
  {
   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of current positions
      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
            m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
  }


The general idea is to loop around all positions fromPositionsTotal()-1 to 0. It's from PositionsTotal()-1 to 0, not from zero to PositionsTotal()-1. This is important.

 
Also a word of advice: when working in MetaTrader 5, an order is a REMOVED ORDER. Therefore it is highly recommended that you do not even bring up the word "order" at this initial stage, so as not to create confusion in your mind.
 
Vladimir Karputov:
Also a word of advice: when working in MetaTrader 5, an order is a REMOVED ORDER. Therefore it is highly recommended that you do not even remember the word "order" at this initial stage, so as not to create confusion in your mind.

There are also market orders Buy and Sell, as well as CloseBy orders.

 

Thank you very much, just like music.

 
procom:

Thank you very much, just like music.

If you need an explanation of my codes, please ask.
 

Well, if you would be so kind, more then.
I've put in the entries and prescribed a pre-close, but again the orders are hanging there and there.

// +  -----   Переворот    ++++++++++++++++++++++++++++   

if (pos_count>0)
   {
      if(lpos_type == POSITION_TYPE_BUY )
      {
         if ( dtriger == -1 )
         {
         o_trade.PositionClose(o_symbol.Name());
         }
         {
         o_trade.Sell(StartLot * lpos_volume , o_symbol.Name());   //   S E L L   +++++
         }
      }

      if (lpos_type==POSITION_TYPE_SELL )
      {
         if ( dtriger == 1 )
         {
         o_trade.PositionClose(o_symbol.Name());
         }
         {
         o_trade.Buy(StartLot * lpos_volume , o_symbol.Name());       //   B U Y    +++++
         }
      }
   }
 
procom:

Well, if you would be so kind, more then.
I have inserted the entries and prescribed a pre-close, but again there are hanging orders here and there.

The closing and opening operations need to be separated, i.e. not to perform these operations in a heap.
A sample plan: OnTick() checks three flags first: ExtNeedCloseBuy, ExtNeedCloseSell and ExtNeedCloseAll.
And only then we check two flags: ExtNeedOpenBuy and ExtNeedOpenSell.
In this way everything will run in a strict order.
And yes, there are no orders: there are open positions.
 
procom:

Thank you very much, just like the notes.

What is the signal to open? Because the code is not complete - only closing positions, but I also need to open positions...


Trade command.mq5
#property version "1.000"

So far it only performs three actions:

  • Close All Buy's
  • Close All Sell's
  • Close All Buy's and Sell's
Take Profit, Stop Loss and Trailing are already built in. The only thing missing is the description of signals to open positions.
Совершение сделок - Торговые операции - MetaTrader 5
Совершение сделок - Торговые операции - MetaTrader 5
  • www.metatrader5.com
Торговая деятельность в платформе связана с формированием и отсылкой рыночных и отложенных ордеров для исполнения брокером, а также с управлением текущими позициями путем их модификации или закрытия. Платформа позволяет удобно просматривать торговую историю на счете, настраивать оповещения о событиях на рынке и многое другое. Открытие позиций...
Files:
Reason: