Questions from Beginners MQL4 MT4 MetaTrader 4 - page 128

 
Anatoliy Ryzhakov:

Sell order closes at Ask price

I'm a little confused! Point the finger where the bug is in the code!!!(log says ORDER CLOSE ERROR 4108) Thanks in advance!

 

Good afternoon Connoisseurs! Have you exhausted the hardest day of the year? Can we get down to business? ;=).

I drew an EA, everything is good, but MQL as I understand it works in MT4 environment. I want it to work with software that works directly with the exchange. Are there any other MQL compilers? If not, what language should I use to rewrite MQL?

 
STARIJ:

You have a break and you need to continue.

I do not have a break. What is the reason why the EA may not "see" its orders? I have different server and computer times, maybe because of this?

 
Anatoliy Ryzhakov: I don't have a break. What is the reason why the EA cannot "see" its orders? My server time and my computer time are different.

Everyone's time is different. Start without rushing from afar. 1. Check what the OrdersTotal function gives you. Its value depends on history settings: Today, last 3 days, last week, ... Adjust it as you prefer. 2. Then create a cycle and output all orders with Alert. This is called debugging - it is a very important part of a programmer's work. More important than writing code.

 
Please advise how to fix invalid lots amount error for FreeMarginCheck function in EA, when accidentally setting negative volume (lot) value. To have a message about wrong lot, without error message, in the tester .

 
STARIJ:

Everyone's time is different. Start without rushing from afar. 1. Check what the OrdersTotal function gives you. Its value depends on the history settings: Today, last 3 days, last week, ... Adjust it as you want. 2. Then create a cycle and output all orders using Alert. This is called debugging - it is a very important part of a programmer's work. More important than writing code.

Thank you !

 

Can you guys tell me how to write in the code of the Expert Advisor to open 3 trades at once with the ability to set SL?

Here is my condition

if(MA_1>MA_2)
ticket=OrderSend(_Symbol,OP_BUY,Lots,Ask,0,Ask-SL*Point,Bid+TP*Point,NULL,0,0,clrGreen);
if(MA_1<MA_2)
ticket=OrderSend(_Symbol,OP_SELL,Lots,Bid,0,Bid+SL*Point,Ask-TP*Point,NULL,0,0,clrRed);

I was advised to use (OrdersTotal()) function, but it does not fit in my case. I have it like this

void OnTick()
  {
//---
   double MA_1;
   MA_1=iMA(_Symbol,0,1,0,1,0,0);
   double MA_2;
   MA_2=iMA(_Symbol,0,6,0,1,0,0);
   int ticket=0;
   if(OrdersTotal()<=3)
     {
      if(MA_1>MA_2)
         ticket=OrderSend(_Symbol,OP_BUY,Lots,Ask,0,Ask-SL*Point,Bid+TP*Point,NULL,0,0,clrGreen);
      if(MA_1<MA_2)
         ticket=OrderSend(_Symbol,OP_SELL,Lots,Bid,0,Bid+SL*Point,Ask-TP*Point,NULL,0,0,clrRed);
     }
//---
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }

It compiles well, no errors, but it is not appropriate for my case.

I found the following code

#property copyright "Влад Сергеев для mmgp" 
#property version   "1.00" 
#property strict 
#property script_show_inputs 

input int      orders = 4;      //всего ордеров в серии 
input bool     buy = true;      //флаг разрешающий/запрещающий покупки 
input bool     sell = false;    //флаг разрешающий/запрещающий продажи 
input int      magic = 100500;  //уникальный номер для ордеров, открываемых этим скриптом 
input double   lot = 0.01;      //объем каждого ордера серии 
input int      tp = 100;        //тейк профит, в пунктах 
input int      sl = 100;        //стоп лосс, в пунктах 
input int      slip = 2;        //допустимое проскальзывание на открытии, в пунктах (для ECN, где открытие по рынку - игнор) 
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnStart()
  {
   int i=0;  // для чего эта переменная
   int ticket=0;
   if(buy) 
     {
      while(i<orders) // здесь эта переменная используется чтобы сравнивать ордера или для чего
        {
         RefreshRates(); // если убрать эту функцию коду хуже не становится
         ticket=OrderSend(Symbol(),OP_BUY,lot,NormalizeDouble(Ask,Digits),slip,0,0,"",magic,0,clrBlue); //здесь понятно
         if(ticket!=-1) // эта строчка тоже не понятна
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))  // функция для выбора ордера это логично но тоже не понятно как ей пользоваться
              {
               OrderModify(ticket,OrderOpenPrice(),NormalizeDouble(OrderOpenPrice()-sl*Point,Digits),NormalizeDouble(OrderOpenPrice()+tp*Point,Digits),0,clrBlue);
               // эту строчку тоже хотел бы чтобы объяснили
              }
           }
         i++; // что увеличивается на оду единицу это относится к магическому номеру ордера чтобы программа понимала что у неё есть ордера
        }
     }
   i=0;
   if(sell) // прошлая запись была для покупак эта для продаж 
     {
      while(i<orders) 
        {
         RefreshRates();
         ticket=OrderSend(Symbol(),OP_SELL,lot,NormalizeDouble(Bid,Digits),slip,0,0,"",magic,0,clrRed);
         if(ticket!=-1) 
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))  
              {
               OrderModify(ticket,OrderOpenPrice(),NormalizeDouble(OrderOpenPrice()+sl*Point,Digits),NormalizeDouble(OrderOpenPrice()-tp*Point,Digits),0,clrRed);
              }
           }
         i++;
        }
     }
  }  
//+------------------------------------------------------------------+

Maybe it can be used, but I don't understand the meaning of strings. May this code be used when rewritten to fit my condition?

 
Seric29:

Can you guys tell me how to write in the code of the Expert Advisor to open 3 trades at once with the ability to set SL?

Here is my condition

I was advised to use (OrdersTotal()) function, but it does not fit in my case. I have it like this

It compiles well, no errors, but it is not appropriate for my case.

I found the following code

Maybe it can be used, but I don't understand the meaning of strings. Can I use this code if I rewrite it to fit my condition?

Try it this way

pos=0; //order counter

for(int i=OrdersTotal()-1;i>=0;i--) //read market orders

{

if (!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))continue;//select from the market orders

{

if (OrderSymbol()!=Symbol()&&OrderMagicNumber()!=Magic) continue;//select only EA orders (if there is Magic and it trades on any currency pair)

pos++; //if we have selected, then increase pos by one

}

}

 if(MA_1>MA_2&&pos<3)
 OrderSend(_Symbol(),OP_BUY,Lots,Ask,0,Ask-SL*Point,Ask+TP*Point,NULL,Magic,0,clrGreen);
 if(MA_1<MA_2&&pos<3)
 OrderSend(_Symbol(),OP_SELL,Lots,Bid,0,Bid+SL*Point,Bid-TP*Point,NULL,Magic,0,clrRed);

 
Quite an interesting forum. lots of enlightening stuff!)
 
Seric29:

Can you guys tell me how to write in the code of the EA to open 3 trades at once with the ability to set SL?

if(MA_1>MA_2)
     for(int i=0; i<3; i++)
          tiket = OrderSend(_Symbol,OP_BUY,Lots,Ask,0,Ask-(i==0?SL_1:i==1?SL_2:SL_3)*Point,Bid+TP*Point,NULL,0,0,clrGreen);
if(MA_1<MA_2)
     for(int i=0; i<3; i++)
          tiket = OrderSend(_Symbol,OP_SELL,Lots,Bid,0,Bid+(i==0?SL_1:i==1?SL_2:SL_3)*Point,Ask-TP*Point,NULL,0,0,clrRed);
Reason: