Orderselect вернул ошибку 4051

Всем привет.

Помощь нужна.

Ордера на продажу переводит в без убыток нормально, а тралить начинает с ошибки 4051. Выдает 130. Но если условие соответствует, модифицирует.

void OrdersModifiStopLoss(int type){
   for(int omsl = OrdersTotal() - 1; omsl >= 0; omsl--){
      if(OrderSelect(omsl, SELECT_BY_POS, MODE_TRADES)){
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == type){
            if(type == OP_SELL){
               if(OrderStopLoss() <= 0){
                  if(OrderOpenPrice() - Bid >= SL){
                     stop = OrderOpenPrice();
                     if(OrderModify(OrderTicket(), OrderOpenPrice(), stop, OrderTakeProfit(), 0, clrWhite))
                        Print("Ордер OP_SELL за №", IntegerToString(OrderTicket()), ": модифицирован стоп лосс в безубыток");
                     else{
                        Print("Ордер OP_SELL за №", IntegerToString(OrderTicket()), ": модифицирован стоп лосс в безубыток не удалось. Ошибка №", GetLastError());
                     }
                  }
               }
               if(OrderStopLoss() <= OrderOpenPrice()){
                  if(OrderOpenPrice() - Bid >= SL){
                     stop = OrderStopLoss() - step;
                     if(OrderModify(OrderTicket(), OrderOpenPrice(), stop, OrderTakeProfit(), 0, clrWhite))
                        Print("Ордер OP_SELL за №", IntegerToString(OrderTicket()), ": модифицирован стоп лосс");
                     else{
                        Print("Ордер OP_SELL за №", IntegerToString(OrderTicket()), ": модифицирован стоп лосс не удалось. Ошибка №", GetLastError());
                     }
                  }
               }
            }
            if(type == OP_BUY){
               if(OrderStopLoss() <= 0){
                  if(Bid - OrderOpenPrice() >= SL){
                     stop = OrderOpenPrice();
                     if(OrderModify(OrderTicket(), OrderOpenPrice(), stop, OrderTakeProfit(), 0, clrWhite))
                        Print("Ордер OP_BUY за №", IntegerToString(OrderTicket()), ": модифицирован стоп лосс в безубыток");
                     else{
                        Print("Ордер OP_BUY за №", IntegerToString(OrderTicket()), ": модифицирован стоп лосс в безубыток не удалось. Ошибка №", GetLastError());
                     }
                  }
               }
               if(OrderStopLoss() >= OrderOpenPrice()){
                  if(Bid - OrderStopLoss() >= SL){
                     stop = OrderStopLoss() + step;
                     if(OrderModify(OrderTicket(), OrderOpenPrice(), stop, OrderTakeProfit(), 0, clrWhite))
                        Print("Ордер OP_BUY за №", IntegerToString(OrderTicket()), ": модифицирован стоп лосс");
                     else{
                        Print("Ордер OP_BUY за №", IntegerToString(OrderTicket()), ": модифицирован стоп лосс не удалось. Ошибка №", GetLastError());
                     }
                  }
               }
            }
         }
      }
   }
}

2021.04.15 21:18:45.263    2019.01.24 18:51:05  %WR EURUSD,M15: OrderModify error 130
2021.04.15 21:18:45.263    2019.01.24 18:51:05  %WR EURUSD,M15: Ордер OP_SELL за №33: модифицирован стоп лосс не удалось. Ошибка №130
2021.04.15 21:18:45.263    2019.01.24 18:51:05  %WR EURUSD,M15: OrderModify error 130
2021.04.15 21:18:45.263    2019.01.24 18:51:05  %WR EURUSD,M15: Ордер OP_SELL за №33: модифицирован стоп лосс
2021.04.15 21:18:45.263    2019.01.24 18:51:05  %WR EURUSD,M15: modify #33 sell 0.10 EURUSD at 1.13438 sl: 1.13398 tp: 0.00000 ok
2021.04.15 21:18:45.263    2019.01.24 18:51:04  %WR EURUSD,M15: Ордер OP_SELL за №33: модифицирован стоп лосс не удалось. Ошибка №130
2021.04.15 21:18:45.263    2019.01.24 18:51:04  %WR EURUSD,M15: OrderModify error 130
2021.04.15 21:18:45.263    2019.01.24 18:51:04  %WR EURUSD,M15: Ордер OP_SELL за №33: модифицирован стоп лосс не удалось. Ошибка №130
2021.04.15 21:18:45.263    2019.01.24 18:51:04  %WR EURUSD,M15: OrderModify error 130
2021.04.15 21:18:45.263    2019.01.24 18:51:04  %WR EURUSD,M15: Ордер OP_SELL за №33: модифицирован стоп лосс не удалось. Ошибка №130
2021.04.15 21:18:45.263    2019.01.24 18:51:04  %WR EURUSD,M15: OrderModify error 130
2021.04.15 21:18:45.263    2019.01.24 18:51:03  %WR EURUSD,M15: Ордер OP_SELL за №33: модифицирован стоп лосс
2021.04.15 21:18:45.263    2019.01.24 18:51:03  %WR EURUSD,M15: modify #33 sell 0.10 EURUSD at 1.13438 sl: 1.13418 tp: 0.00000 ok
2021.04.15 21:18:45.263    2019.01.24 18:51:03  %WR EURUSD,M15: Ордер OP_SELL за №33: модифицирован стоп лосс не удалось. Ошибка №4051
2021.04.15 21:18:45.263    2019.01.24 18:51:03  %WR EURUSD,M15: OrderModify error 4051
2021.04.15 21:18:45.263    2019.01.24 18:51:03  %WR EURUSD,M15: invalid stoploss for OrderModify function
2021.04.15 21:18:45.263    2019.01.24 18:51:03  %WR EURUSD,M15: Ордер OP_SELL за №33: модифицирован стоп лосс в безубыток
2021.04.15 21:18:45.263    2019.01.24 18:51:03  %WR EURUSD,M15: modify #33 sell 0.10 EURUSD at 1.13438 sl: 1.13438 tp: 0.00000 ok
2021.04.15 21:18:45.233    2019.01.24 18:15:00  %WR EURUSD,M15: Ордер OP_SELL открыт!

А  с ордерами на покупку все ОКей.

ПС. Нормализация не помогает. Да к тому же все нормализовано в OnInit…

What is MT4 error 4051?

The MT4 error 4051 is a MetaTrader OrderSend error suggesting the trading platform is denying an order due to an invalid trading lot amount.

Whenever an MT4 receives a trade request, it thoroughly examines the parameters of the order. When an EA sends an order request, the system automatically verifies the maximum and minimum limit of trading volumes allowed for the particular entry. At any point, the platform detects an order with a trading lot that you are not permitted to execute; it denies the order request showing ERR_INVALID_FUNCTION_PARAMETER_VALUE.

MT4 Error 4051

An OrderSend error 4051 doesn’t necessarily mean the system rejects all the trade requests or disables your trading bot permanently. The MT4 executes an order immediately when it comes with an appropriate amount of trading lot. On the other hand, the restriction over the trading volume prevents your account from suffering unexpected losses due to the wrong parameters of an EA.

Why does MT4 error 4051 happen?

You are exceeding your trading limit

The minimum order limit in MT4 is 0.01 lots, and the maximum limit is 200 lots. If your bot determines a trading lot less than 0.01 or greater than 200, the system will reject the order and show the OrderSend error 4051.

In some cases, your broker server might fail to read the lot amount correctly. For instance, you are trying to execute an order with 0.01 volume, but the minimum order limit of the broker is 0.1. So the server will define the volume as invalid since it turns lesser than the minimum order limit.

Conversely, if you ever try to place an order with more than 200 lots at a time, the MT4 will still refuse to activate the order because it exceeds the maximum trade volume limit.

Your EA is generating inappropriate order parameters

Such problems mainly occur due to an error in EA coding. A malfunction in the programming code may tempt your bot to produce unrealistic trading lot figures which are not recognized as valid parameters by MetaTrader or the broker server.

Apart from an invalid trading lot, your trade can be disallowed for the malfunction of other parameters. For instance, you cannot place a buy order with a stop-loss limit greater than your trade entry or take profit level. These types of problems may happen for two reasons:

  • An error in the EA coding
  • The EA is not compatible with the trading system

How to fix MT4 error 4051?

How to fix OrderSend error for invalid lot amount

  1. Use NormalizeDouble in your code

    When the system confirms an invalid function parameters value, you may consider using the NormalizeDouble function:

    MT4 NormalizeDouble function

    Parameters:
    value – determines a value with a floating point.
    digits – determines the accuracy formate such as the number of digits after the decimal point.
    Please note that you must normalize all the values calculated for stop-loss, take-profit, and pending order prices.

  2. Adjust the value of NormalizeDouble

    Sometimes a normalized number may become greater than the DoubleToString value like the following example:

    MT4 Doubletostring

  3. Make sure normalized figures are rounded

    Here is an example showing how to keep the normalized values round figured:

    MT4 Normalized Values

  4. Broker trading limitations for lot size

    f your system still shows the OrderSend error 4051, it might be an issue with your broker trading limitations. In that case, contact the broker and try to be more specific about their maximum and minimum limit of trading lots.

In my mql4 Expert Advisor, I’ve written this function to close all the buy trades at once. When I test it via the Strategy Tester, it closes some buy trades, but for a few other buy trades it returns the: OrderClose error 4051:invalid ticket for OrderClose function error.

void Close_All_Buy_Trdes(){
   for (int i=0;i<=OrdersTotal();i++){
      OrderSelect(i,SELECT_BY_POS);
      if(OrderType()==OP_BUY {
           OrderClose(OrderTicket(),OrderLots(),Bid,3);
      }
   }
}

What is the reason for this happening?

not2qubit's user avatar

not2qubit

14.2k8 gold badges93 silver badges131 bronze badges

asked Mar 3, 2018 at 9:15

0

Once you close one of the orders the position number will be different for the rest of them… so the loop is trying ro close orders that wont be available at that position anymore.

You could select by ticket number (these don’t change) instead of position, but that means having the ticket numbers stored.

If you prefer use position, this is a way of doing this:

void close_all()
{
    int get_out=0,hstTotal=OrdersHistoryTotal();
    if (hstTotal<1) get_out=1;
    while (get_out==0)
    {
        if(!OrderSelect(0,SELECT_BY_POS,MODE_TRADES)) get_out=1;
        else
        {
            //you can add here any specific if condition 
            OrderClose(OrderTicket(),OrderLots(),Bid,3);
        }
        hstTotal=OrdersHistoryTotal();
        if (hstTotal<1) get_out=1;
    }
}

The code always closes the first order(position=0) as many times as necessary while the number of open orders is >=1 (exit condition of the while is: hstTotal<1)

answered Mar 3, 2018 at 12:21

J_P's user avatar

J_PJ_P

7618 silver badges17 bronze badges

5

You just need to loop backward

for(int i = OrdersTotal() - 1; i >= 1; i--)
{
    OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
    OrderDelete(OrderTicket());
}

answered Apr 27 at 13:10

Viktor's user avatar

ViktorViktor

6652 gold badges7 silver badges11 bronze badges

Just for clarity, whilst the comment is valid by Viktor, the code is very poor. It should be as a bare minimum:

for(int i=OrdersTotal()-1; i>=0; i--)
{
   if(OrderSelect(Ticket, SELECT_BY_TICKET))
   {
      bool attempt; double price=0;
      if(OrderType()==OP_BUY) price=Bid; if(OrderType()==OP_SELL) price=Ask;
      if(OrderType()<=1) attempt=OrderClose(OrderTicket(), OrderLots(), price, 50);
      else attempt=OrderDelete(OrderTicket());
      if(!attempt) Print("Order Closeure failed with error #",GetLastError());
   }
}

answered Apr 28 at 9:02

PaulB's user avatar

PaulBPaulB

1,1871 gold badge6 silver badges16 bronze badges

use this code:

void Close_All_Buy_Trdes(){
   for(int i = OrdersTotal() - 1; i >= 0; i--){
      OrderSelect(i, SELECT_BY_POS);
      if(OrderType() == OP_BUY){
         OrderClose(OrderTicket(), OrderLots(), Bid, 3);
        }
     }
  }

answered May 4 at 22:46

Jalal Nouri's user avatar

GetLastError() — функция, возвращающая коды ошибок. Кодовые константы ошибок определены
в файле stderror.mqh. Для вывода текстовых сообщений следует использовать функцию
ErrorDescription(), определенную в файле stdlib.mqh.

Константа Значение Описание
ERR_NO_ERROR 0 Нет ошибки
ERR_NO_RESULT 1 Нет ошибки, но результат неизвестен
ERR_COMMON_ERROR 2 Общая ошибка
ERR_INVALID_TRADE_PARAMETERS 3 Неправильные параметры
ERR_SERVER_BUSY 4 Торговый сервер занят
ERR_OLD_VERSION 5 Старая версия клиентского терминала
ERR_NO_CONNECTION 6 Нет связи с торговым сервером
ERR_NOT_ENOUGH_RIGHTS 7 Недостаточно прав
ERR_TOO_FREQUENT_REQUESTS 8 Слишком частые запросы
ERR_MALFUNCTIONAL_TRADE 9 Недопустимая операция нарушающая функционирование сервера
ERR_ACCOUNT_DISABLED 64 Счет заблокирован
ERR_INVALID_ACCOUNT 65 Неправильный номер счета
ERR_TRADE_TIMEOUT 128 Истек срок ожидания совершения сделки
ERR_INVALID_PRICE 129 Неправильная цена
ERR_INVALID_STOPS 130 Неправильные стопы
ERR_INVALID_TRADE_VOLUME 131 Неправильный объем
ERR_MARKET_CLOSED 132 Рынок закрыт
ERR_TRADE_DISABLED 133 Торговля запрещена
ERR_NOT_ENOUGH_MONEY 134 Недостаточно денег для совершения операции
ERR_PRICE_CHANGED 135 Цена изменилась
ERR_OFF_QUOTES 136 Нет цен
ERR_BROKER_BUSY 137 Брокер занят
ERR_REQUOTE 138 Новые цены
ERR_ORDER_LOCKED 139 Ордер заблокирован и уже обрабатывается
ERR_LONG_POSITIONS_ONLY_ALLOWED 140 Разрешена только покупка
ERR_TOO_MANY_REQUESTS 141 Слишком много запросов
ERR_TRADE_MODIFY_DENIED 145 Модификация запрещена, так как ордер слишком близок к рынку
ERR_TRADE_CONTEXT_BUSY 146 Подсистема торговли занята
ERR_TRADE_EXPIRATION_DENIED 147 Использование даты истечения ордера запрещено брокером
ERR_TRADE_TOO_MANY_ORDERS 148 Количество открытых и отложенных ордеров достигло предела, установленного брокером.
Константа Значение Описание
ERR_NO_MQLERROR 4000 Нет ошибки
ERR_WRONG_FUNCTION_POINTER 4001 Неправильный указатель функции
ERR_ARRAY_INDEX_OUT_OF_RANGE 4002 Индекс массива — вне диапазона
ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK 4003 Нет памяти для стека функций
ERR_RECURSIVE_STACK_OVERFLOW 4004 Переполнение стека после рекурсивного вызова
ERR_NOT_ENOUGH_STACK_FOR_PARAMETER 4005 На стеке нет памяти для передачи параметров
ERR_NO_MEMORY_FOR_PARAMETER_STRING 4006 Нет памяти для строкового параметра
ERR_NO_MEMORY_FOR_TEMP_STRING 4007 Нет памяти для временной строки
ERR_NOT_INITIALIZED_STRING 4008 Неинициализированная строка
ERR_NOT_INITIALIZED_ARRAYSTRING 4009 Неинициализированная строка в массиве
ERR_NO_MEMORY_FOR_ARRAYSTRING 4010 Нет памяти для строкового массива
ERR_TOO_LONG_STRING 4011 Слишком длинная строка
ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 Остаток от деления на ноль
ERR_ZERO_DIVIDE 4013 Деление на ноль
ERR_UNKNOWN_COMMAND 4014 Неизвестная команда
ERR_WRONG_JUMP 4015 Неправильный переход
ERR_NOT_INITIALIZED_ARRAY 4016 Неинициализированный массив
ERR_DLL_CALLS_NOT_ALLOWED 4017 Вызовы DLL не разрешены
ERR_CANNOT_LOAD_LIBRARY 4018 Невозможно загрузить библиотеку
ERR_CANNOT_CALL_FUNCTION 4019 Невозможно вызвать функцию
ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED 4020 Вызовы внешних библиотечных функций не разрешены
ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING 4021 Недостаточно памяти для строки, возвращаемой из функции
ERR_SYSTEM_BUSY 4022 Система занята
ERR_INVALID_FUNCTION_PARAMETERS_COUNT 4050 Неправильное количество параметров функции
ERR_INVALID_FUNCTION_PARAMETER_VALUE 4051 Недопустимое значение параметра функции
ERR_STRING_FUNCTION_INTERNAL_ERROR 4052 Внутренняя ошибка строковой функции
ERR_SOME_ARRAY_ERROR 4053 Ошибка массива
ERR_INCORRECT_SERIES_ARRAY_USING 4054 Неправильное использование массива-таймсерии
ERR_CUSTOM_INDICATOR_ERROR 4055 Ошибка пользовательского индикатора
ERR_INCOMPATIBLE_ARRAYS 4056 Массивы несовместимы
ERR_GLOBAL_VARIABLES_PROCESSING_ERROR 4057 Ошибка обработки глобальныех переменных
ERR_GLOBAL_VARIABLE_NOT_FOUND 4058 Глобальная переменная не обнаружена
ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE 4059 Функция не разрешена в тестовом режиме
ERR_FUNCTION_NOT_CONFIRMED 4060 Функция не подтверждена
ERR_SEND_MAIL_ERROR 4061 Ошибка отправки почты
ERR_STRING_PARAMETER_EXPECTED 4062 Ожидается параметр типа string
ERR_INTEGER_PARAMETER_EXPECTED 4063 Ожидается параметр типа integer
ERR_DOUBLE_PARAMETER_EXPECTED 4064 Ожидается параметр типа double
ERR_ARRAY_AS_PARAMETER_EXPECTED 4065 В качестве параметра ожидается массив
ERR_HISTORY_WILL_UPDATED 4066 Запрошенные исторические данные в состоянии обновления
ERR_TRADE_ERROR 4067 Ошибка при выполнении торговой операции
ERR_END_OF_FILE 4099 Конец файла
ERR_SOME_FILE_ERROR 4100 Ошибка при работе с файлом
ERR_WRONG_FILE_NAME 4101 Неправильное имя файла
ERR_TOO_MANY_OPENED_FILES 4102 Слишком много открытых файлов
ERR_CANNOT_OPEN_FILE 4103 Невозможно открыть файл
ERR_INCOMPATIBLE_ACCESS_TO_FILE 4104 Несовместимый режим доступа к файлу
ERR_NO_ORDER_SELECTED 4105 Ни один ордер не выбран
ERR_UNKNOWN_SYMBOL 4106 Неизвестный символ
ERR_INVALID_PRICE_PARAM 4107 Неправильный параметр цены для торговой функции
ERR_INVALID_TICKET 4108 Неверный номер тикета
ERR_TRADE_NOT_ALLOWED 4109 Торговля не разрешена
ERR_LONGS_NOT_ALLOWED 4110 Длинные позиции не разрешены
ERR_SHORTS_NOT_ALLOWED 4111 Короткие позиции не разрешены
ERR_OBJECT_ALREADY_EXISTS 4200 Объект уже существует
ERR_UNKNOWN_OBJECT_PROPERTY 4201 Запрошено неизвестное свойство объекта
ERR_OBJECT_DOES_NOT_EXIST 4202 Объект не существует
ERR_UNKNOWN_OBJECT_TYPE 4203 Неизвестный тип объекта
ERR_NO_OBJECT_NAME 4204 Нет имени объекта
ERR_OBJECT_COORDINATES_ERROR 4205 Ошибка координат объекта
ERR_NO_SPECIFIED_SUBWINDOW 4206 Не найдено указанное подокно
ERR_SOME_OBJECT_ERROR 4207 Ошибка при работе с объектом

Возможно, вам также будет интересно:

  • Order would immediately trigger ошибка
  • Order drum oki ошибка
  • Orcs must die 3 ошибка unreal engine
  • Orcs must die 3 smartsteamemu ошибка
  • Orangeemu ошибка при запуске need for speed heat

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии