Questions from Beginners MQL5 MT5 MetaTrader 5 - page 712

 

Several EAs have to work in different windows on the same instrument.

Can we somehow make PositionsTotal() count only our own positions? But as soon as one EA opens a position, the others also consider that they are already in position.

I have set different MagicNumbers, it doesn't help.

 
dimnik:

Several EAs have to work in different windows on the same instrument.

Can we somehow make PositionsTotal() count only our own positions? But as soon as one EA opens a position, the others also consider that they are already in position.

I have set different MagicNumbers, it doesn't help.

There is no miracle. If the MagicNumbers are different, then the Expert Advisors should distinguish the positions. Will you have the code?
 
Vitalie Postolache:
There are no miracles. If the magicians are different, the Expert Advisors should distinguish the positions. Will there be a code?

The first one (a test one, just for a joint experiment):

#include <Trade\Trade.mqh>

CTrade  trade;

int OnInit()
  {
   trade.SetAsyncMode(true);
   trade.SetExpertMagicNumber(111);
   return(INIT_SUCCEEDED);
  }

void OnTick()
  {

   if (PositionsTotal()==0)
   {
      trade.Buy(1);
   }
  
  }

The second (the same one, with another magician):

#include <Trade\Trade.mqh>

CTrade  trade;

int OnInit()
  {
   trade.SetAsyncMode(true);
   trade.SetExpertMagicNumber(222);
   return(INIT_SUCCEEDED);
  }

void OnTick()
  {

   if (PositionsTotal()==0)
   {
      trade.Buy(1);
   }
  
  }

As soon as I close a position manually, EAs instantly see this and open new ones - at the same time. If one has opened while the other is not active, the second one does not open any more.

 
dimnik:

Several EAs have to work in different windows on the same instrument.

Can we somehow make PositionsTotal() count only our own positions? But as soon as one EA opens a position, the others also consider that they are already in position.

I have set different MagicNumbers, but that does not help.

Example EA that goes through all positions and closes only its own symbol and its Magic:

//+------------------------------------------------------------------+
//|                                                     CloseALL.mq5 |
//|                              Copyright © 2017, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2017, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.00"
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
CTrade         m_trade;                      // trading object
CPositionInfo  m_position;                   // trade position object
//--- input parameter
input ulong    m_magic=159753698;            // magic number
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   CloseAll();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

  }
//+------------------------------------------------------------------+
//| Close All                                                        |
//+------------------------------------------------------------------+
void CloseAll()
  {
   Print(__FUNCTION__);
   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic)
            m_trade.PositionClose(m_position.Ticket());
  }
//+------------------------------------------------------------------+


Added: I hope you are working on a hedge trading account???

 
dimnik:

And as soon as I close a position manually, the Expert Advisors instantly open a new one.

And, of course,PositionsTotal does not distinguish positions by magic number or anything else, it gives the total number of positions in the account. We should loop through the positions from 0 toPositionsTotal()-1, look at the magic number and count.

Oh, while I was writing, they already showed me exactly how to do it (:
 
dimnik:

Several EAs have to work in different windows on the same instrument.

Can we somehow make PositionsTotal() count only our own positions? But as soon as one EA opens a position, the others also consider that they are already in position.

I have set different MagicNumbers, it doesn't help.

PositionsTotal() does not filter by magic numbers. For this, we have to go through positions and calculate only "own" positions with our own function.
 


Добавлено: я надеюсь Вы работает на торговом счетё hedge???

No, not Hedge. So, PositionTotal() can't count only its own positions?

Can the CTrade class then consider its own positions separately from others?

 
dimnik:

No, not Hedge. So, PositionTotal() can't count only its own positions?

And the CTrade class will be able to consider its positions separately?

There can be NO MORE than ONE position for each symbol on the netting. The rule of thumb applies to Magic:

Forum on trading, automated trading systems and strategy testing

Magic number

Vladimir Karputov, 2016.12.25 12:38

On netting, who is last to know - i.e. magic number of position will be the same as it was on the last trade with this instrument...

Checking:

//+------------------------------------------------------------------+
//|                                             ReplacementMagic.mq5 |
//|                              Copyright © 2016, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2016, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.00"
#property description "Что происходит с magic на netting"
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   if(AccountInfoInteger(ACCOUNT_MARGIN_MODE)==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
     {
      Print("Этот пример только для netting!");
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   static int counter=-10;
   if(counter%300==0)
     {
      //--- генерируем Magic
      ulong m_magic=MathRand();
      Print("new Magic: ",IntegerToString(m_magic));
      //--- устанавливаем новый Magic
      m_trade.SetExpertMagicNumber(m_magic);
      //--- определим лот
      double lots=0.0;
      if(MathRand()%2==0)
         lots=0.01;
      else
         lots=0.02;

      //--- определяем, что открывать: Buy или Sell
      if(MathRand()%2==0) // значит Buy
        {
         m_trade.Buy(lots);
        }
      else // значит Sell
        {
         m_trade.Sell(lots);
        }
     }
   counter++;
  }
//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
//--- get transaction type as enumeration value
   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is result of addition of the transaction in history
   if(type==TRADE_TRANSACTION_DEAL_ADD)
     {
      for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
         if(m_position.SelectByIndex(i))
            if(m_position.Symbol()==Symbol())
              {
               //string text=ChartGetString(0,CHART_COMMENT)+"\n"+
               //            "Magic: "+IntegerToString(m_position.Magic());
               //Comment(text);
               Print("Обнаружена позиция с Magic: "+IntegerToString(m_position.Magic()));
              }
     }
  }
//+------------------------------------------------------------------+



Files:
 
Comments not related to this topic have been moved to "Questions from MQL4 MT4 MetaTrader 4 beginners".
 
Can you tell me how to find out the result of the last one or more trades?
Reason: