Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 412

 

Hello. Faced with an unpleasant situation. Help me out here.

I have an Expert Advisor. It works fine in the Strategy Tester, I have no claims. When I run it on a demo, the Expert Advisor cannot place stops on certain orders. There is an error that appears not always, but sometimes. I am desperate to find it on my own and hope to get your help. It should be noted the EA works flawlessly in all other aspects, just like in the tester, no complaints, except that the problem is that stops are not always set. The error appears at different brokers on different accounts. Here is the part of the code responsible for trade operations

ord_ticket=OrderSend(ASymb,ord_type,ord_lots,ord_openpr,20,0,0,"",ord_magic);
if(ord_ticket>0) {
  //---- обновление инфы
  OrderSelect(ord_ticket,SELECT_BY_TICKET);
  ord_openpr=OrderOpenPrice();
  ZigZagInfo[0][ZZ_TimeP]=t_cur;
  ZigZagInfo[k][ZZ_TryCount]++;
  //---- проверка стопов
  if(ND(a*(ord_tp-ord_openpr)-stops,Digits)<0) ord_tp=ND(ord_openpr+a*stops,Digits); 
  if(ND(a*(ord_openpr-ord_sl)-stops,Digits)<0) ord_sl=ND(ord_openpr-a*stops,Digits);
  //---- время удаления
  if(TimeDelete>0) td=TimeCurrent()+60*TimeDelete;
  else td=0;
  //----
  if(!OrderModify(ord_ticket,ord_openpr,ord_sl,ord_tp,td)) {
    Alert(Error(GetLastError()),"/nSL=",DoubleToStr(ord_sl,5)," TP=",DoubleToStr(ord_tp,5),"/nTimeDel=",TimeToStr(td),
          "OP=",DoubleToStr(ord_openpr,5));
  }
}

Here is the code of the Error(int er) function

string Error(int er) {
  switch(er) {
    case 0:   return("Нет ошибки");
    case 1:   return("Нет ошибки, но результат неизвестен");
    case 2:   return("Общая ошибка(сбой системы, глюк, и т.п.)");
    case 3:   return("Неправильные параметры");
    case 4:   return("Торговый сервер занят");
    case 6:   return("Нет связи с торговым сервером");
    case 7:   return("Недостаточно прав");
    case 8:   return("Слишком частые запросы");
    case 9:   return("Недопустимая операция нарушающая функционирование сервера");
    case 128: return("Истек срок ожидания совершения сделки");
    case 129: return("Неправильная цена");
    case 130: return("Неправильные стопы");
    case 131: return("Неправильный объем");
    case 133: return("Торговля запрещена");
    case 134: return("Недостаточно денег для совершения операции");
    case 135: return("Цена изменилась");
    case 137: return("Брокер занят");
    case 138: return("Новые цены");
    case 139: return("Ордер заблокирован и уже обрабатывается");
    case 140: return("Разрешена только покупка");
    case 141: return("Слишком много запросов");
    case 145: return("Модификация запрещена, так как ордер слишком близок к рынку");
    case 146: return("Подсистема торговли занята");
    case 147: return("Использование даты истечения ордера запрещено брокером");
    case 148: return("Количество открытых и отложенных ордеров достигло предела, установленного брокером");
    case 149: return("Попытка открыть противоположную позицию к уже существующей в случае, если хеджирование запрещено.");
    default:  return("Неизвестная ошибка "+DoubleToStr(er,0));
  }
}

So, when the EA fails to set stops, a message appears showing information about the error and parameters of the order it tried to modify. What he writes is the real mystery to me. As you can see from the pictures below, it constantly writes that the volume is wrong. This is strange. I should add that all order parameters are calculated correctly before modification, it can be seen in the messages. Otherwise the error would be different. The program was tested with a higher spread than the one in the demo.

Enigmaanother

 
_Vladimir_:

Hello. Faced with an unpleasant situation. Help me out here.

I have an Expert Advisor. It works fine in the Strategy Tester, I have no claims. However, when I run it on a demo, I see that the EA cannot place stops on certain orders. There is an error that appears not always, but sometimes. I am desperate to find it on my own and hope to get your help. It should be noted the EA works flawlessly in all other aspects, just like in the tester, no complaints, except that the problem is that stops are not always set. The error appears at different brokers on different accounts. Here is the part of the code responsible for trade operations

Here is the code of the Error(int er) function

So, when the EA fails to set stops, a message appears showing information about the error and parameters of the order it tried to modify. What he writes is the real mystery to me. As you can see from the pictures below, it constantly writes that the volume is wrong. This is strange. I should add that all order parameters are calculated correctly before modification, it can be seen in the messages. Otherwise the error would be different. The program was tested with a higher spread than the one in the demo.

Be careful with the values of your global variables. I can assume that ord_ticket is a global variable, which means that the previous value can be stored in it. And before calling GetLastError() to catch the error, you should reset the previous value by calling it at the beginning of the code.
 
TarasBY:
You should be very careful with values of your global variables. I may suggest that ord_ticket is a global variable and therefore it may store the previous value. And before calling GetLastError() to catch the error, you should reset the previous value by calling it at the beginning of the code.

ord_ticket is declared at local level. And then even if it is declared globally in the first line

ord_ticket=OrderSend(ASymb,ord_type,ord_lots,ord_openpr,20,0,0,"",ord_magic);
if(ord_ticket>0) {

its value will certainly change. It will be either order number in case of successful transaction, or -1 otherwise. So, if the order is not opened, we don't get to the block of setting stops.

It should also be noted that the OrderSend() function always changes the value of the last error(according to the documentation and logic), so resetting the previous reading in this case is not necessary and would result in a simple waste of time. That is, error 131 appears after entering the stop setting block and before the error message is displayed. Since the stops are not really placed, the OrderModify() function must be the last function to be called, which, as well as the previous one, always changes the value of the last error. But I cannot understand why it does not change the value of the last error. Where does it come from? Once again I will say that there were no problems in the tester.

I had an idea that the broker was cheating because the server would send error numbers to the terminal and the latter in its turn would send them to the Expert Advisor. I have abandoned this idea because only orders of one EA have errors, other EAs working in parallel do not have such errors.

 
_Vladimir_:

ord_ticket is declared at local level. And then even if it is declared globally in the first line

value is sure to change. It will be either order number in case of successful transaction, or -1 otherwise. So, if the order is not opened, we don't get to the block of setting stops.

It should also be noted that the OrderSend() function always changes the value of the last error (according to the documentation and logic), so resetting the previous reading in this case is not necessary and would result in a simple waste of time. That is, error 131 appears after entering the stop setting block and before the error message is displayed. Since the stops are not really placed, the OrderModify() function must be the last function to be called, which, as well as the previous one, always changes the value of the last error. But I cannot understand why it does not change the value of the last error. Where does it come from? Once again I will say that there were no problems in the tester.

I had an idea that the broker was cheating because the server would send error numbers to the terminal and the latter in its turn would send them to the Expert Advisor. I have quickly abandoned this idea because only orders of one EA have errors, other EAs working in parallel do not have such errors.


I'll add. The code of the parallel working EA is exactly the same, it is responsible for setting stops. This EA has never had a situation when stops were not set for orders.

It appears that there is an error in calculation of parameters somewhere above but if only one parameter is wrong, another error should appear. For example, the well-known 130

 
_Vladimir_:

ord_ticket is declared at local level. And then even if it is declared globally in the first line

value is sure to change. It will be either order number in case of successful transaction, or -1 otherwise. So, if the order is not opened, we don't get to the block of setting stops.

It should also be noted that the OrderSend() function always changes the value of the last error (according to the documentation and logic), so resetting the previous reading in this case is not necessary and would result in a simple waste of time. That is, error 131 appears after entering the stop setting block and before the error message is displayed. Since the stops are not really placed, the OrderModify() function must be the last function to be called, which, as well as the previous one, always changes the value of the last error. But I cannot understand why it does not change the value of the last error. Where does it come from? Once again I will say that there were no problems in the tester.

I had an idea that the broker was cheating because the server would send error numbers to the terminal and the latter in its turn would send them to the Expert Advisor. I have quickly abandoned this idea because only orders of one EA have errors, other EAs working in parallel do not have such errors.

Thought is racing! But experience shows that what we think (as it should be) and what is actually there are very often DIFFERENT things. What can be advised: "Preprint the whole sequence of your code execution", - that's the fastest way to find an error (or make sure you're right). :)
 
yan720:

You wrote a three-point response. In the first one you made a mistake (my entry is quite correct), in the second one you also made a mistake (although this message leveled it out :) The third point sounded as if you suggested to move the cursor to the end after the entry, not before it (which was taken as a mistake again). In the face of such a picture, I preferred to make a clarification to the answering multi-skilled moderator.

Nevertheless, thank you indeed for your response. And happy New Year! :)



:D ok, happy new year to you too :)
 
Going back to what was written on page 411 ... anyone have any idea how to combine that code and entry/exit conditions for crossing two MAs? or are pending orders the only option?
 
petya33r:
Going back to what was written on page 411 ... does anyone have an idea how to combine that code and entry/exit conditions for crossing two MAs? or are pending orders the only option?

After opening a deal on a mooving signal, start to monitor the number of orders or this order specifically, if the number of orders to decrease or as the second option is closed specifically this order, then find out how it was closed, if a stop, then opens just the opposite order at the current price, that's all
 
Ekburg:

After opening a deal on a moving signals start to monitor the number of orders or this order specifically, if the number of orders to decrease or as the second option is closed specifically this order, then find out how it is closed, if the stop, then just open the opposite order at the current price, that's all

I understand that, but I can't write it down. The Expert Advisor either trades only on muwings signals and does not open a reverse position in case of a loss, or simply crashes the terminal when testing starts. So I wrote something that cannot be processed at all. I am not very good at writing. I need help in the form of written code.

//нет открытых ордеров - ищем в истории закрытых ордеров последний закрытый именно этим советником ордер 
  for ( trade = OrdersHistoryTotal() - 1; trade >= 0; trade-- ) 
  {
     if ( OrderSelect(trade, SELECT_BY_POS, MODE_HISTORY) && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol() )
     {
         old_order_type = OrderType();
         if ( OrderProfit()<0 ) //последний закрытый советником ордер был убыточным, значит, следующий ордер открываем в направлении, противоположном закрытому с убытком
         {
                break; //прекращаем поиск
         }
     }
  }
  //если раньше покупали, то теперь продаем
  if ( old_order_type == OP_BUY )
  {
      ticket = OrderSend(Symbol(), OP_SELL, Lot,  NormalizeDouble(Bid, Digits), slip, NormalizeDouble(Ask+stoploss*Point, Digits), NormalizeDouble(Ask-takeprofit*Point, Digits), "Martingale-Sell", MagicNumber, 0, Red);
      Sleep (2000); //задержка в 2 секунды для обработки запроса торговым сервером брокера
      return (0);  
  }

If OrderProfit()<0, it will open opposite order.But it does not work together with signals from moving aids. Can you write a single code to provide both muwings signals and conditions for opening an opposite position?

 
petya33r:

I understand that, but I can't write it down. The Expert Advisor either trades only on muwings signals and does not open a reverse position in case of a loss, or simply crashes the terminal when testing starts. So I wrote something that cannot be processed at all. I am not very good at writing. I need help in the form of written code.

If OrderProfit()<0, it will open opposite order.But it does not work together with signals from moving aids. Can you write a single code that contains both muwings signals and conditions for opening an opposite position?


I have no time and possibility to write you a ready code, as I am at work)).

You do not search by history, but by current positions, here is a logical chain, on the basis of which you can try to write the code:

[block of working with muwings and placing an order]

1 remember the ticket and the magic number of the placed order

2 monitor the number of orders and if there are no orders in the market (it means that our order has been closed), then go to point3 or monitor this specific order until its close time is more than zero, in which case we exclude points 3 and 4

3 find our order

4 find out if it is closed

5 find out how it was closed

6 if it was closed through a stop, set another order different from it in the direction