Mql4 ошибка 4111

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 Ошибка при работе с объектом

Let’s dis-assemble the OrderSend() call first:

int result = OrderSend( NULL,             // string:      _Symbol,
                        OP_SELL,          // int:         OP_SELL,
                        0.01,             // double:      NormalizeLOTs( nLOTs ),
                        Bid,              // double:      NormalizeDouble( Bid, Digits ),
                        5,                // int:         slippagePOINTs,
                        0,                // double:      {       0 | NormalizeDouble( aSlPriceTARGET, Digits ) },
                        Bid-0.002,        // double:      {       0 | NormalizeDouble( aTpPriceTARGET, Digits ) },
                        NULL,             // string:      {    NULL | aBrokerUnguaranteedStringCOMMENT },
                        0,                // int:         {       0 | aMagicNUMBER },
                        0,                // datetime:    {       0 | aPendingOrderEXPIRATION },
                        clrGreen          // color:       { clrNONE | aMarkerCOLOR }
                        );

For one’s further peace-of-mind, one ought always normalise all the values, that have some restrictive handling on the MQL4-side ( prices + lot ( quantised ) values — as these are not continuous values in R domain, but rather quantum-stepped:

prices: having a 0.00001 or 0.0001 or 0.001 or 0.01 or 0.1 or 1.0 etc. stepping,

lot-volumes: being more restricted by the Broker-specific settings, per instrument, of three key values, all allowable volume sizes have to meet:
[aMinLOTs<=, +aMinLotSTEP, <=aMaxLOTs] + a proper digit normalisation
~ thus a double NormalizeLOTs( aProposedVOLUME ) {...} is a handy tool for a seamless implementation of both parts of this need.


Error 4111:

There are a few other barriers, that prevent your MetaTrader Terminal 4 from running your code smooth:

4111
ERR_SHORTS_NOT_ALLOWED
Shorts are not allowed. Check the Expert Advisor properties

 if (  !TerminalInfoInteger( TERMINAL_TRADE_ALLOWED ) ) 
        Alert( "Check if automated trading is allowed in the terminal settings!" ); 
 else  if (  !MQLInfoInteger( MQL_TRADE_ALLOWED ) )
             Alert( "Automated trading is forbidden in the program settings for ",
                    __FILE__
                    );

This instructs user to revise MetaTrader Terminal 4 settings,
under MT4 -> Tools -> Options -> ExpertAdvisor Tab
and Broker-side Trading Instrument conditions, where shorting for some instruments may be restricted in general, or just for certain Account type(s).

 if (  !AccountInfoInteger( ACCOUNT_TRADE_EXPERT ) )
        Alert( "Automated trading is forbidden for the account",
                AccountInfoInteger( ACCOUNT_LOGIN ),
               " at the trade server side. Contact Broker's Customer Care Dept."
               );

For more details, printScreens and demonstrated programmatic handling of this group of both Terminal-side / Broker-side barriers: ref.-> MQL4 Reference / MQL4 programs / Trade Permission

Уважаемые программисты вылетает 4111 ошибка! только если нужно открыть селл, с бай все нормально, вроде должно все работать…… 1 раз сталкиваюсь!!!

Кто поможет благодарю 

Выкладываю код:

//+------------------------------------------------------------------+
//|                                           Скользящая средняя.mq4 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+

#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+

extern uchar   RaZ=25;
extern ushort  TP_SL=100;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   uchar  s=0;
   uchar  b=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol())
           {
            if(OrderType()==OP_BUY) b++;
            if(OrderType()==OP_SELL)s++;
           }
        }
     }
   double paznB=(Open[0]-Ask)/Point;
   double paznS=(Open[0]-Bid)/Point;
   double RZB=NormalizeDouble(paznB,2);
   double RZS=NormalizeDouble(paznS,2);

// if(RZB<-RaZ &&  b<1){OrderOPEN(0);}
   if(RZS>RaZ && s<1)
     {
      OrderOPEN(1);

      ObjectCreate("FFF11",OBJ_LABEL,0,0,0);// Создание объ.
      ObjectSet("FFF11",OBJPROP_XDISTANCE,1200);// Координата Х
      ObjectSet("FFF11",OBJPROP_YDISTANCE,25);// Координата Y
      ObjectSetText("FFF11","POINT = "+Point,10,"Arial",clrIndianRed);

      if(OrderSend(Symbol(),OP_SELL,1,Bid,10,0,0,NULL,1235,0,clrIndianRed));
      else Print("О как же так ",GetLastError());
     }

   ObjectCreate("FFF1",OBJ_LABEL,0,0,0);// Создание объ.
   ObjectSet("FFF1",OBJPROP_XDISTANCE,1200);// Координата Х
   ObjectSet("FFF1",OBJPROP_YDISTANCE,15);// Координата Y
   ObjectSetText("FFF1","RZS = "+RZS,10,"Arial",clrIndianRed);

   ObjectCreate("FFF",OBJ_LABEL,0,0,0);// Создание объ.
   ObjectSet("FFF",OBJPROP_XDISTANCE,1200);// Координата Х
   ObjectSet("FFF",OBJPROP_YDISTANCE,5);// Координата Y
   ObjectSetText("FFF","Open0 = "+Open[0],10,"Arial",clrIndianRed);
//+------------------------------------------------------------------+
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OrderOPEN(uchar z)
  {
   double PRice,SL,TP,lot;
   color CVET;
   if(z==0)
     {
      lot=1;
      PRice=Ask;
      SL=PRice-TP_SL*Point;
      TP=PRice+TP_SL*Point;
      CVET=LimeGreen;

      if(OrderSend(Symbol(),z,lot,PRice,10,SL,TP,NULL,1235,0,CVET));
      else Print("О как же так ",GetLastError());
     }
   if(z==1)

     {
      lot=1;
      PRice=Bid;
      SL=PRice+TP_SL*Point;
      TP=PRice-TP_SL*Point;
      CVET=Magenta;

      if(OrderSend(Symbol(),z,lot,PRice,10,SL,TP,NULL,1235,0,CVET));
      else Print("О как же так ",GetLastError());
     }
  }
//+------------------------------------------------------------------+

What is MT4 error 4111?

The MT4 error 4111 is an OrderSend error code. This code indicates an Expert Advisor (EA) is failing to execute a sell order.

Most of the EAs are enabled for executing both buy and sell orders. When an automated trading system spots a trading opportunity, it delivers an order command to MT4. In any case, the system fails to trigger a short entry and it sends the error code 4111.

MT4 error 4111

Why does MT4 error 4111 happen?

A trading platform shows the error code 4111 for the following reasons:

An issue with MT4 settings:

Each EA comes with a default system setting. Here, you need to specify if this software is allowed for long and short entries or both. For instance, if it is permitted for long entries only, the system will still generate sell signals, but the trading platform will not accept it due to the limitation specified in the settings menu. The MetaTrader terminal will send the error code 4111 indicating a missed attempt to execute a sell order in such a condition.

An error in the programming code of the EA

If you still see the platform sending the same error code after allowing the EA for both long and short trades, then it might be a coding error. In such a case, you need to re-check the code to see if the system is disabled for automated trading.

A restriction from the broker

There are specific timeframes or conditions in the market when the broker doesn’t allow new orders. For example, some brokers don’t allow new orders when announcing susceptible news or updates regarding major currencies. In that condition, your system will still show the same MT4 error code upon receiving a sell order request from the expert advisor.

How to fix MT4 error 4111

Time needed: 2 minutes.

Step-by-step instructions to fix OrderSend error

  1. Find Experts Advisors (EA) tab

    Click on View and select the Navigation option. Alternatively, click Ctrl+N for direct access to the menu. Next, click the Expert Advisor Tab. Here you’ll find all the automated trading systems installed in your MT4 platform.

  2. Check EA Properties

    Double-click on the troubled system, and it’ll show you the system properties. If it shows Only Long means your system is permitted to take on the buy orders only. For this reason, the platform is not accepting any sell orders and sending the MT4 error 4111 (OrderSend) error code.

    MT4 error 4111 only buy

  3. Fix EA properties

    Change this option to Long and Short, which will enable the MT4 to accept both buy and sell instructions from your trading system.

    Also, make sure you’ve enabled the live trading option. If this option is disabled, then the platform will reject all types of orders. In such situations, it will show both buy and sell OrderSend error codes.

    MT4 error 4111 check EA

  4. Check the short order parameters in the MetaEditor

    The code below represents a sample of an ideal short order configuration of a MACD based EA. Ensure the system applies correct values for determining lot sizes, the number of bidding attempts, and ticket modes for activating sell orders. Also, you can contact your broker to check if there is an issue with the system’s parameter that contradicts the broker’s requirements.

  5. MT4 error 4111 fix ea code

Уважаемые программисты вылетает 4111 ошибка! только если нужно открыть селл, с бай все нормально, вроде должно все работать…… 1 раз сталкиваюсь!!!

Кто поможет благодарю 

Выкладываю код:

//+------------------------------------------------------------------+
//|                                           Скользящая средняя.mq4 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+

#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+

extern uchar   RaZ=25;
extern ushort  TP_SL=100;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   uchar  s=0;
   uchar  b=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol())
           {
            if(OrderType()==OP_BUY) b++;
            if(OrderType()==OP_SELL)s++;
           }
        }
     }
   double paznB=(Open[0]-Ask)/Point;
   double paznS=(Open[0]-Bid)/Point;
   double RZB=NormalizeDouble(paznB,2);
   double RZS=NormalizeDouble(paznS,2);

// if(RZB<-RaZ &&  b<1){OrderOPEN(0);}
   if(RZS>RaZ && s<1)
     {
      OrderOPEN(1);

      ObjectCreate("FFF11",OBJ_LABEL,0,0,0);// Создание объ.
      ObjectSet("FFF11",OBJPROP_XDISTANCE,1200);// Координата Х
      ObjectSet("FFF11",OBJPROP_YDISTANCE,25);// Координата Y
      ObjectSetText("FFF11","POINT = "+Point,10,"Arial",clrIndianRed);

      if(OrderSend(Symbol(),OP_SELL,1,Bid,10,0,0,NULL,1235,0,clrIndianRed));
      else Print("О как же так ",GetLastError());
     }

   ObjectCreate("FFF1",OBJ_LABEL,0,0,0);// Создание объ.
   ObjectSet("FFF1",OBJPROP_XDISTANCE,1200);// Координата Х
   ObjectSet("FFF1",OBJPROP_YDISTANCE,15);// Координата Y
   ObjectSetText("FFF1","RZS = "+RZS,10,"Arial",clrIndianRed);

   ObjectCreate("FFF",OBJ_LABEL,0,0,0);// Создание объ.
   ObjectSet("FFF",OBJPROP_XDISTANCE,1200);// Координата Х
   ObjectSet("FFF",OBJPROP_YDISTANCE,5);// Координата Y
   ObjectSetText("FFF","Open0 = "+Open[0],10,"Arial",clrIndianRed);
//+------------------------------------------------------------------+
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OrderOPEN(uchar z)
  {
   double PRice,SL,TP,lot;
   color CVET;
   if(z==0)
     {
      lot=1;
      PRice=Ask;
      SL=PRice-TP_SL*Point;
      TP=PRice+TP_SL*Point;
      CVET=LimeGreen;

      if(OrderSend(Symbol(),z,lot,PRice,10,SL,TP,NULL,1235,0,CVET));
      else Print("О как же так ",GetLastError());
     }
   if(z==1)

     {
      lot=1;
      PRice=Bid;
      SL=PRice+TP_SL*Point;
      TP=PRice-TP_SL*Point;
      CVET=Magenta;

      if(OrderSend(Symbol(),z,lot,PRice,10,SL,TP,NULL,1235,0,CVET));
      else Print("О как же так ",GetLastError());
     }
  }
//+------------------------------------------------------------------+

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 Ошибка при работе с объектом

What is MT4 error 4111?

The MT4 error 4111 is an OrderSend error code. This code indicates an Expert Advisor (EA) is failing to execute a sell order.

Most of the EAs are enabled for executing both buy and sell orders. When an automated trading system spots a trading opportunity, it delivers an order command to MT4. In any case, the system fails to trigger a short entry and it sends the error code 4111.

MT4 error 4111

Why does MT4 error 4111 happen?

A trading platform shows the error code 4111 for the following reasons:

An issue with MT4 settings:

Each EA comes with a default system setting. Here, you need to specify if this software is allowed for long and short entries or both. For instance, if it is permitted for long entries only, the system will still generate sell signals, but the trading platform will not accept it due to the limitation specified in the settings menu. The MetaTrader terminal will send the error code 4111 indicating a missed attempt to execute a sell order in such a condition.

An error in the programming code of the EA

If you still see the platform sending the same error code after allowing the EA for both long and short trades, then it might be a coding error. In such a case, you need to re-check the code to see if the system is disabled for automated trading.

A restriction from the broker

There are specific timeframes or conditions in the market when the broker doesn’t allow new orders. For example, some brokers don’t allow new orders when announcing susceptible news or updates regarding major currencies. In that condition, your system will still show the same MT4 error code upon receiving a sell order request from the expert advisor.

How to fix MT4 error 4111

Time needed: 2 minutes.

Step-by-step instructions to fix OrderSend error

  1. Find Experts Advisors (EA) tab

    Click on View and select the Navigation option. Alternatively, click Ctrl+N for direct access to the menu. Next, click the Expert Advisor Tab. Here you’ll find all the automated trading systems installed in your MT4 platform.

  2. Check EA Properties

    Double-click on the troubled system, and it’ll show you the system properties. If it shows Only Long means your system is permitted to take on the buy orders only. For this reason, the platform is not accepting any sell orders and sending the MT4 error 4111 (OrderSend) error code.

    MT4 error 4111 only buy

  3. Fix EA properties

    Change this option to Long and Short, which will enable the MT4 to accept both buy and sell instructions from your trading system.

    Also, make sure you’ve enabled the live trading option. If this option is disabled, then the platform will reject all types of orders. In such situations, it will show both buy and sell OrderSend error codes.

    MT4 error 4111 check EA

  4. Check the short order parameters in the MetaEditor

    The code below represents a sample of an ideal short order configuration of a MACD based EA. Ensure the system applies correct values for determining lot sizes, the number of bidding attempts, and ticket modes for activating sell orders. Also, you can contact your broker to check if there is an issue with the system’s parameter that contradicts the broker’s requirements.

  5. MT4 error 4111 fix ea code
int result = OrderSend( NULL,             // string:      _Symbol,
                        OP_SELL,          // int:         OP_SELL,
                        0.01,             // double:      NormalizeLOTs( nLOTs ),
                        Bid,              // double:      NormalizeDouble( Bid, Digits ),
                        5,                // int:         slippagePOINTs,
                        0,                // double:      {       0 | NormalizeDouble( aSlPriceTARGET, Digits ) },
                        Bid-0.002,        // double:      {       0 | NormalizeDouble( aTpPriceTARGET, Digits ) },
                        NULL,             // string:      {    NULL | aBrokerUnguaranteedStringCOMMENT },
                        0,                // int:         {       0 | aMagicNUMBER },
                        0,                // datetime:    {       0 | aPendingOrderEXPIRATION },
                        clrGreen          // color:       { clrNONE | aMarkerCOLOR }
                        );

Для дальнейшего душевного спокойствия следует всегда нормализовать все ценности, которые имеют некоторые ограничительные возможности для MQL4-стороны (цены + лот (квантовая) значения — так как это не непрерывные значения в области R, а квантово-ступенчатые:

цены: имеющие 0.00001 или же 0.0001 или же 0.001 или же 0.01 или же 0.1 или же 1.0 и т. д.

объемы лотов: более строго ограниченные настройками брокера для каждого инструмента из трех ключевых значений, все допустимые размеры томов должны соответствовать:
[aMinLOTs<=, +aMinLotSTEP, <=aMaxLOTs]+ правильная нормализация цифр
таким образом double NormalizeLOTs( aProposedVOLUME ) {...} это удобный инструмент для беспрепятственного выполнения обеих частей этой потребности.


Error 4111:

Есть несколько других барьеров, которые мешают вашему MetaTrader Terminal 4 от запуска вашего кода гладко:

4111
ERR_SHORTS_NOT_ALLOWED
Shorts are not allowed. Check the Expert Advisor properties

 if (  !TerminalInfoInteger( TERMINAL_TRADE_ALLOWED ) ) 
        Alert( "Check if automated trading is allowed in the terminal settings!" ); 
 else  if (  !MQLInfoInteger( MQL_TRADE_ALLOWED ) )
             Alert( "Automated trading is forbidden in the program settings for ",
                    __FILE__
                    );

Это инструктирует пользователя пересматривать MetaTrader Terminal 4 настройки,
под MT4 -> Tools -> Options -> ExpertAdvisor табуляция
и условия Торгового инструмента на стороне брокера, где короткое замыкание для некоторых инструментов может быть ограничено в целом или только для определенных типов Счетов.

 if (  !AccountInfoInteger( ACCOUNT_TRADE_EXPERT ) )
        Alert( "Automated trading is forbidden for the account",
                AccountInfoInteger( ACCOUNT_LOGIN ),
               " at the trade server side. Contact Broker's Customer Care Dept."
               );

Для получения более подробной информации, printScreens и продемонстрировали программную обработку этой группы обоих Terminal со стороны / барьеры со стороны брокера: ref.-> MQL4 Reference / MQL4 программы / Разрешение на торговлю

Я пытаюсь разместить заказ, но мой вызов метода OrderSend() (https: // docs.mql4.com/trading/ordersend)
не работает:

2016.08.01 00:51:09.710 2016.07.01 01:00 s EURUSD,M1: OrderSend error 4111

void OnTick() {
    if (  OrdersTotal() == 0 ){
          int   result =  OrderSend( NULL, OP_SELL, 0.01, Bid, 5, 0, Bid - 0.002, NULL, 0, 0, clrGreen );
          if (  result <  0 ) Print( "Order failed #", GetLastError() );
          else                Print( "Order success" );
    }
} 

Вы знаете, что я делаю не так, пожалуйста?

Давайте сначала разберем вызов OrderSend():

int result = OrderSend( NULL,             // string:      _Symbol,
                        OP_SELL,          // int:         OP_SELL,
                        0.01,             // double:      NormalizeLOTs( nLOTs ),
                        Bid,              // double:      NormalizeDouble( Bid, Digits ),
                        5,                // int:         slippagePOINTs,
                        0,                // double:      {       0 | NormalizeDouble( aSlPriceTARGET, Digits ) },
                        Bid-0.002,        // double:      {       0 | NormalizeDouble( aTpPriceTARGET, Digits ) },
                        NULL,             // string:      {    NULL | aBrokerUnguaranteedStringCOMMENT },
                        0,                // int:         {       0 | aMagicNUMBER },
                        0,                // datetime:    {       0 | aPendingOrderEXPIRATION },
                        clrGreen          // color:       { clrNONE | aMarkerCOLOR }
                        );

Для дальнейшего спокойствия всегда следует нормализовать все значения, обработка которых ограничена на стороне MQL4 (цены + лот ( квантованные) значения — так как это не непрерывные значения в домене R, а скорее квантово-ступенчатые:

цены: со степпингом 0.00001, 0.0001, 0.001, 0.01, 0.1 или 1.0 и т. д.,

объемы лотов : поскольку настройки брокера более ограничены для каждого инструмента из трех ключевых значений, все допустимые размеры объемов должны соответствовать:
[aMinLOTs<=, +aMinLotSTEP, <=aMaxLOTs] + правильная нормализация цифр
~ поэтому double NormalizeLOTs( aProposedVOLUME ) {...} — удобный инструмент для беспрепятственной реализации обеих частей это нужно.


Error 4111:

Есть еще несколько препятствий, которые мешают вашему MetaTrader Terminal 4 выполнять ваш код гладко:

4111
ERR_SHORTS_NOT_ALLOWED
Shorts are not allowed. Check the Expert Advisor properties

 if (  !TerminalInfoInteger( TERMINAL_TRADE_ALLOWED ) ) 
        Alert( "Check if automated trading is allowed in the terminal settings!" ); 
 else  if (  !MQLInfoInteger( MQL_TRADE_ALLOWED ) )
             Alert( "Automated trading is forbidden in the program settings for ",
                    __FILE__
                    );

Это дает пользователю указание пересмотреть настройки MetaTrader Terminal 4 ,
на вкладке MT4 -> Tools -> Options -> ExpertAdvisor
и условия торговых инструментов на стороне брокера, где продажа некоторых инструментов может быть ограничена в целом или только для определенных типов счетов.

 if (  !AccountInfoInteger( ACCOUNT_TRADE_EXPERT ) )
        Alert( "Automated trading is forbidden for the account",
                AccountInfoInteger( ACCOUNT_LOGIN ),
               " at the trade server side. Contact Broker's Customer Care Dept."
               );

Дополнительные сведения см. В printScreens и продемонстрирована программная обработка этой группы как Terminal -сторонних / -брокерских -сторонних барьеров: ref .-> Справочник MQL4 / программы MQL4 / Разрешение на торговлю


1

user3666197
1 Авг 2016 в 16:23

Сначала OrderSend() вызов OrderSend():

int result = OrderSend( NULL,             // string:      _Symbol,
OP_SELL, // int: OP_SELL,
0.01, // double: NormalizeLOTs( nLOTs ),
Bid, // double: NormalizeDouble( Bid, Digits ),
5, // int: slippagePOINTs,
0, // double: { 0 | NormalizeDouble( aSlPriceTARGET, Digits ) },
Bid-0.002, // double: { 0 | NormalizeDouble( aTpPriceTARGET, Digits ) },
NULL, // string: { NULL | aBrokerUnguaranteedStringCOMMENT },
0, // int: { 0 | aMagicNUMBER },
0, // datetime: { 0 | aPendingOrderEXPIRATION },
clrGreen // color: { clrNONE | aMarkerCOLOR }
);

Для еще одного умиротворения нужно всегда нормализовать все ценности, которые имеют некоторую ограничительную обработку на MQL4 -side (цены + лот (квантованные) значения — поскольку они не являются непрерывными значениями в R-домене, а скорее квант-ступенчатый:

цены: с 0.00001 или 0.0001 или 0.001 или 0.01 или 0.1 или 1.0 и т.д.,

лоты-тома: более ограниченные специфическими для Брокера настройками, на один инструмент, из трех ключевых значений, все допустимые размеры тома должны соответствовать:
[aMinLOTs<=, +aMinLotSTEP, <=aMaxLOTs] + нормальная нормализация цифр
~ Таким образом, через double NormalizeLOTs( aProposedVOLUME ) {...} является удобным инструментом для бесшовной реализации обеих частей этой потребности.

Error 4111:

Есть еще несколько барьеров, которые не позволяют вашему TG20 работать с вашим кодом:

4111
ERR_SHORTS_NOT_ALLOWED
Shorts are not allowed. Check the Expert Advisor properties

 if (  !TerminalInfoInteger( TERMINAL_TRADE_ALLOWED ) ) 
Alert( "Check if automated trading is allowed in the terminal settings!" );
else if ( !MQLInfoInteger( MQL_TRADE_ALLOWED ) )
Alert( "Automated trading is forbidden in the program settings for ",
__FILE__
);

Это дает указание пользователю пересмотреть настройки MetaTrader Terminal 4
в разделе MT4 → Tools → Options → ExpertAdvisor вкладка MT4 → Tools → Options → ExpertAdvisor
и Условия брокера -side, когда ограничение на некоторые инструменты может быть ограничено в целом или только для определенных типов (типов) учетной записи.

 if (  !AccountInfoInteger( ACCOUNT_TRADE_EXPERT ) )
Alert( "Automated trading is forbidden for the account",
AccountInfoInteger( ACCOUNT_LOGIN ),
" at the trade server side. Contact Broker Customer Care Dept."
);

Для получения дополнительной информации, printScreens и продемонстрированной программной обработки этой группы барьеров Terminal -side/Broker -side: ref.-> MQL4 Reference/MQL4 programs/Trade Permission

Понравилась статья? Поделить с друзьями:
  • Mql4 ошибка 129
  • Mprint lp58 eva ошибка печати
  • Mortal kombat ошибка открытия
  • Mscorwks dll windows 7 ошибка
  • Mortal kombat ошибка msvcr110 dll