Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1679

 
Maxim Kuznetsov #:

is this a joke?

You have it in black and white for(;;)

Well, yes, but there's a way out of it: when magic doesn't equal order magic.
 
Nerd Trader #:
Well yes, only there is a way out of it: when magic does not equal order magic.

Try this

int GetMagic(Order &order)
{
  int magic = 0;
  if(order.cmd == OP_SELLSTOP || order.cmd == OP_BUYSTOP)
  for(int i = OrdersTotal(); i > 0 ; i --)
   {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
       if(OrderType()==OP_SELLSTOP || OrderType()==OP_BUYSTOP)
         {
          if(magic == OrderMagicNumber()) magic+=1;
          else magic=0;
         }
      }
   }
  return (magic);
}
 
EVGENII SHELIPOV selected order.

What if there is a grid of orders?

Does anyone have a function to calculate the sum of all swaps of a grid of orders for a magic order and a financial instrument.

Thanks for the help!!!

What do you need it for?
 
MakarFX #:
What do you need it for?

When closing a large grid of orders with a long grid life, order swaps eat into profits and distort the result very much.

I want to compensate for the loss on swaps with this function.

 
EVGENII SHELIPOV #:

When closing a large grid of orders with a long grid life, order swaps eat into profits and distort the result very much.

I want to compensate for the loss on swaps with this function.

Is the grid closed at profit or breakeven?
 
MakarFX #:

Try this

int GetMagic(Order &order)
{
  int magic = 0;
  if(order.cmd == OP_SELLSTOP || order.cmd == OP_BUYSTOP)
  for(int i = OrdersTotal(); i > 0 ; i --)
   {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
       if(OrderType()==OP_SELLSTOP || OrderType()==OP_BUYSTOP)
         {
          if(magic == OrderMagicNumber()) magic+=1;
          else magic=0;
         }
      }
   }
  return (magic);
}
That fixed it, I had if (order.cmd == OP_SELLSTOP || OP_BUYSTOP) only the problem was not solved.
But I need it to pass through all orders. The mage itself is set at the moment of creation only to the stopper. We can't understand that the stopper is created by OrderType() because it hasn't been there yet; we have a preliminary record of order type in order.cmd for that. And here we need two loops: one nested in the other, so that one iteration of the variable magic is checked with all orders from OrdersTotal(). I have it all implemented, only there is an endless loop, I don't know why ...
 
MakarFX #:
Is the grid closed at profit or at breakeven?

Yes, at a certain level of drawdown, there is a loss to zero and to no loss there is an ugly loss due to swaps

 
Nerd Trader #:
This is fine, I had if (order.cmd == OP_SELLSTOP || OP_BUYSTOP)
But I need all orders to be passed. The mage itself is set when only the stopper is created. We can't know that the stopper is created by OrderType() since it hasn't been there yet, we need to write the order type in order.cmd beforehand. And here we need two loops: one nested in the other, so that one iteration of the magic variable is checked with all orders from OrdersTotal()
Show me where you use GetMagic(...)
 
void OpenOrder(int db = -1){

  if(db == -1){
    Print("'db' должен иметь корректное значение");
    return;
  }

  Order order;

  //Если бид в границах ДБ (его хай/лоу) то инициализируем ордер для селстопа или байстопа
  if(Bid > db_last.low && Bid < db_last.hight){
    if(db == BEAR) order.InitForSell(SELLSTOP);
    if(db == BULL) order.InitForBuy(BUYSTOP);
  }

 ...

  if(order.is_init == true)
  {
    int order_send = OrderSend(Symbol(), order.cmd, 0.01, order.open_price, 10, 
    order.sl_price, order.tp_price, "", GetMagic(order), 0, order.arrow_color);

    if(order_send == -1){
      Print(order.error_text," | ",GetLastError()," db_last.third ",db_last.third,
        " | db_last.size_open_to_low ",db_last.size_open_to_low," | order.sl_price: ",
        order.sl_price," | order.cmd ",order.cmd);
      ResetLastError();
      return;
    }
  }
}

...

int GetMagic(Order &order)
{
  int magic = 0;
  //Если должен быть открыт стопордер и если есть уже открытые или отложенные 
  //ордера, то возможно некоторые с маджиком, это надо проверить и сгенерировать 
  //для нашего ордера уникальный маджик и отправить его на запись в массив
  if(order.cmd == OP_SELLSTOP || OP_BUYSTOP)
    if(OrdersTotal() >= 1)
      for(;;){
        magic++;
        for(int i = OrdersTotal(); i > 0 ; i --)
          if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) != false)
            if(magic != OrderMagicNumber())
              return magic;
            
      }
    //Если нет открытых или отложенных ордеров то увеличиваем значение 
    //маджика, чтобы он равнялся единице и отправляем на запись в массив
    else if (OrdersTotal() == 0)
      return (magic + 1);
  return magic;
}


It says in the commentary that it sends the majic to the write array, so don't be misled by this, as long as the majic goes back to the retorn.
 
EVGENII SHELIPOV #:

Yes, at a certain level of drawdown, there is a loss to zero and to no loss there is an ugly loss due to swaps

   double GetOrderSwap()
     {
      double order_swap = 0;
      for(int i = OrdersTotal()-1; i>=0; i--)
        {
         if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
           {
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
              {
               if (OrderType() == OP_BUY)
                 {
                  order_swap += OrderSwap();
                 }
              }
           }
        }
      return(order_swap);
     }
Reason: