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 | Ошибка при работе с объектом |
Здравствуйте, есть такой вопрос, почему появляется ошибка 138,переменная становится Price=0 время от времени, как решить эту проблему?
Как только отложенный ордер исполняется, необходимо установить новый отложник в противоположную сторону по цене stop loss того ордера, который в рынке. Когда срабатывает лось должен исполнится новый отложенник и т.д. Не получается грамотно сделать(
Кусок кода:
if ((Total<=1) && (N>1)) { if ((N==3) || (N==5) || (N==7) || (N==9) || (N==11) || (N==13) || (N==15)) Price=Price1; if ((N==2) || (N==4) || (N==6) || (N==8) || (N==10) || (N==12) || (N==14)) Price=Price2; } while(true) { if (Total<=1) //Total - кол-во имеющихся ордеров, в рынке и отложенных { RefreshRates(); if ((N==1) && (Type==OP_BUY)) //N-номер ордера в серии ордеров {SL=Ask - 12*Point; //Price1 и Price2 являются static TP=Ask + takeprofit*Point; Price=Ask; Price1=Ask; Price2=SL; } if ((N>1) && (Type==OP_BUYSTOP)) {SL=Price - 12*Point; TP=Price + takeprofit*Point; } if ((N==1) && (Type==OP_SELL)) {SL=Ask + 12*Point; TP=Ask - takeprofit*Point; Price=Bid; Price1=Bid; Price2=SL; } if ((N>1) && (Type==OP_SELLSTOP)) {SL=Price + 12*Point; TP=Price - takeprofit*Point; } Alert("Попытка открыть ",Type,". Ожидание ответа.."); Ticket=OrderSend(Symb,Type,Lts,Price,2,SL,TP," ",N); if (Ticket > 0) { Alert ("Открыт ордер ",Ticket); } if (Fun_Error(GetLastError())==1) continue; return; } break; }
What is MT4 error 138?
OrderSend Error 138 (or ERR_REQUOTE
) may appear during the execution (but not backtesting) of MetaTrader expert advisors. This error appears only in MT4 as the MetaTrader 5 platform uses a different system of OrderSend error codes. Error 138 means that the broker replied with a «Requote» signal to your expert advisor’s OrderSend()
function call. In other words, the price used in the order is outdated compared to the current market price.
Also, error 138 can appear as a result of the OrderClose()
function call if it is performed with an outdated or wrong price.
Why does MT4 error 138 appear?
There are two main reasons for this error to appear:
- The order price is completely outdated and is not present in the recent quotes. The order will not be executed (and the error 138 will be generated) even if the current market price is within the given Slippage from the order price.
- The order price is present in the recent quotes but differs from the current market price by more than the given Slippage parameter.
How to fix OrderSend error 138 in MT4?
To avoid getting OrderSend Error 138 from your expert advisors, you have to use RefreshRates()
function call immediately before calling OrderSend()
function and before you use the Ask/Bid to calculate parameter values for OrderSend()
function. This will save you from the first of the above-listed cases. However, if your broker is experiencing some technical problems, this won’t help and the error may still appear — there is little you can do in that case.
Here is an MQL4 example of how this is handled in the Chart Pattern Helper EA’s code:
// Get current market prices. RefreshRates(); // Calculate volume based on the current Bid. NewVolume = GetPositionSize(Bid, LowerSL); // Send a Sell order at the current Bid price. LowerTicket = OrderSend(Symbol(), OP_SELL, NewVolume, Bid, Slippage, LowerSL, LowerTP, "ChartPatternHelper", Magic);
Additionally, you should specify a rather large slippage in the parameters of the OrderSend()
function to prevent error 138 from appearing during very volatile conditions. Even if you use the RefreshRates()
function, there is a possibility that prices will change between the call of RefreshRates()
and the execution of OrderSend()
. Setting a tolerable slippage of 5&ndas;10 pips (normal ones, not fractional) will allow your expert advisors to execute orders without requote errors. Of course, if you are scalping or otherwise aiming for small profit targets, you should set a much smaller slippage parameter and bear with the error 138 and failed orders. As an alternative solution, you can always switch your Forex broker to one with less slippage and fewer requotes.
How to fix OrderClose error 138 in MT4?
With OrderClose()
, it is usually much simpler — you just have to make sure that you are closing Buy orders using the current Bid
price, and Sell orders using the current Ask
price. If you encounter MQL4 error 138 with OrderClose()
, check if you are sending the correct variable for a price parameter.
Here is an example of a correctly set up OrderClose()
call to close out a trade from our News Trader EA:
If you have any thoughts, comments, or questions regarding MT4 OrderSend Error 138 and the ways to fix it, feel free to discuss it on our forum with other traders and MQL4 developers.
The MT4 error 138 indicates a price requote issue of the MetaTrader4 platform. This error code may appear when you attempt to execute an order during a highly volatile market.
An error code 138 means the MT4 platform has missed your quoted price for executing an order. In such a situation, your trading platform cancels the current order and requotes another price as an option for re-executing the order. When you visit the platform’s journal at its terminal, you will see the software showing the message “OrderSend error 138”.
Why does MT4 error 138 happen?
Your MT4 platform may show an error code 138 for several reasons:
Slippage
A slippage refers to the difference between the current price and the execution price of a particular trade. A slippage occurs mostly in a highly volatile market when the price rapidly changes every second. For example, you place a buy order (instant execution) of EURUSD on 1.2019. By the time you click on “buy” the price already reaches 1.2021. When the MT4 platform finds such a difference between the execution and actual price, it withdraws the order and shows the error code 138.
Connection dropouts
For any reason, your internet connection dropouts during the execution of an order will also show an error code 138. It happens when your platform gets disconnected from the internet right after you place an order. As a result, your MT4 platform fails to find the price you have quoted due to the connection dropout and shows the OrderSend error signal.
How to fix MT4 requotes?
Time needed: 5 minutes.
How to fix MT4 error 138
Use the RefreshRates function in your EA
- If you wish to remove the OrderSend error138 from your EA, you need to place a RefreshRates function before the OrderSend and Ask/Bid function. Here is an example:
- Handle slippage when closing orders with your EA
Slippage can occur during an attempt to close an order. When MT4 fails to close an order within your quoted price it sends “OrderClose error 138”. To fix such order close issue you need to edit your MT4 EA as follows:
- Add slippage limit to your EA
Please note that even if you place RefreshRates in your EA, there might still be slippage in between the execution of OrderSend and RefreshRates. So, setting a slippage limit in the EA can help you in executing the orders without requotes. When you set a slippage limit in your EA, the platform finds the best price within the slippage limit, executes the trade, and prevents showing MT4 error 138 requote.
- Enable the Deviation feature in MT4
You will find the deviation feature at the bottom of the order execution window of the MT4 platform. Enable the feature and set a value at the maximum deviation box. If you set the maximum deviation as 30, it means the platform will execute an order within 3 pips closer to the originally quoted price. For example, if you place a EURUSD buy order at 1.2023 but the price slips to 1.2026 during the execution process. In such a case the platform will accept the new price and will execute the order at 1.2026 without requoting.
- Select a broker that offers ECN or DMA (Direct Market Access) accounts
If you are trading with a market maker broker, there is a higher chance of facing the error code 138. Because a market maker broker manipulates the price and often fails to match the exact order price provided by the user. On the other hand, a broker that offers ECN or DMA accounts will provide an instant order execution facility. So, trading on an ECN account significantly reduces the risk of slippage.
I get ordersend error 138, be it buy or sell, but only in back testing not in live demo. I have try to adjust slippage to no avail. Does anyone have any idea what’s wrong?
double price = iClose(Symbol(), PERIOD_H1, 1);
if (up > down && up > sideway){
double stoploss = NormalizeDouble(price-piploss*Point, Digits);
double takeprofit = NormalizeDouble(price+pipgain*Point, Digits);
int ticket = OrderSend(Symbol(), OP_BUY, 1, price, 5, stoploss, takeprofit, "buy", 16384, 0, clrGreen);
if (ticket<0){
Print("Order send error: ", GetLastError());
} else{
Print("Order success");
}
} else if (down > up && down > sideway) {
double stoploss = NormalizeDouble(price+piploss*Point, Digits);
double takeprofit = NormalizeDouble(price-pipgain*Point, Digits);
int ticket = OrderSend(Symbol(), OP_SELL, 1, price, 5, stoploss, takeprofit, "sell", 16384, 0, clrGreen);
if (ticket<0){
Print("Order send error: ", GetLastError());
} else{
Print("Order success");
}
} else {
Print("sideway");
}
}