Ошибка 131 mql4

Коды ошибок - Приложения - Учебник по MQL4

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

Содержание

  1. Не полное закрытие ордера.
  2. Handling OrderSend Error 131 in MetaTrader 4
  3. OrderSend: Error code 131
  4. Помогите исправить ошибку OrderModify error 1 и OrderSend error 131!

Не полное закрытие ордера.

Господа, я знаю что значит эта ошибка. я не пойму почему она выскакивает.

Нельзя роботом закрыть часть открытой позиции? При этом оставить отрытой часть не меньше минимального лота?

приведенные вами примеры сводятся к тому, что робот посылает не верный лот, или меньше минимально, или больше максимального или не нормализованный, т.е. с большим количеством знаков после запятой . в моем случае лот нормализован, больше или равен минимальному и меньше лота открытого ордера который хочу частично покрыть.

сделайте для начала закрытие просто 0,1 лота.

затем проверьте как закрывает просто объем по MODE_MINLOT.

Если получится. то работайте с тем, что надо N*. и ищите ошибку в распринтовке.

Господа, я знаю что значит эта ошибка. я не пойму почему она выскакивает.

Нельзя роботом закрыть часть открытой позиции? При этом оставить отрытой часть не меньше минимального лота?

приведенные вами примеры сводятся к тому, что робот посылает не верный лот, или меньше минимально, или больше максимального или не нормализованный, т.е. с большим количеством знаков после запятой. в моем случае лот нормализован, больше или равен минимальному и меньше лота открытого ордера который хочу частично покрыть.

void _OrderCloseByTrend(int _OrderCloseType) <
int _closeType=-1,
i,
_ticket=-1,
_points=0;
double _summ=0.0,
_closePrice=0,
_loss=0.0,
_lots=0.0;

if (_OrderCloseType==OP_BUY) <
_closeType=OP_SELL;
_closePrice=Ask;
> // End of if (_OrderCloseTyp==OP_BUY)
if (_OrderCloseType==OP_SELL) <
_closeType=OP_BUY;
_closePrice=Bid;
> // End of if (_OrderCloseType==OP_SELL)
Alert(«Закрывае прибыльные «+_TypeToStr(_closeType)+» ордера!»);
if (OrdersTotal()>0) <
for (i=OrdersTotal()-1; i>=0; i—) <
if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) <
if (OrderType()==_closeType && OrderProfit()>0) <
_summ=_summ+OrderProfit();
while (!OrderClose(OrderTicket(),OrderLots(),_closePrice,0,0)) <
RefreshRates();
if (_closeType==OP_BUY) _closePrice=Bid;
if (_closeType==OP_SELL) _closePrice=Ask;
>// End of while
>// End of if (OrderType()==_closeType && OrderProfit()>0)
>// End of if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)
>// End of for
>// End of if (OrdersTotal()>0)
Alert(«Закрывае убыточные «+_TypeToStr(_closeType)+» ордера!»);
while (OrdersTotal()>0 && _summ>0) <
_ticket=-1;
for (i=OrdersTotal()-1; i>=0; i—) < // Ищем самый убыточный ордер
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) <
if(OrderType()==_closeType && OrderProfit() 0)
else <
_lots=OrderLots();
> // End of else
_summ=_summ+OrderProfit();
Alert(«Пытаемся закрыть ордер — «,_ticket,», Объемом — «,_lots);
while (!OrderClose(_ticket,_lots,_closePrice,0,0)) <
RefreshRates();
if (_closeType==OP_BUY) _closePrice=Bid;
if (_closeType==OP_SELL) _closePrice=Ask;
> // End of while
> // End of if (OrderSelect(_ticket, SELECT_BY_TICKET)
>//End of while
return;
>

Источник

OrderSend Error 131 is a very frequent problem that is usually encountered when testing MT4 expert advisors. What causes this error? It is called ERR_INVALID_TRADE_VOLUME in the MetaTrader 4 documentation. It means that your expert advisor (EA) is trying to send an order with invalid trade volume. At the absolute majority of the MT4 brokers, setting some EA to open an order with 0.123 lots volume will generate this error. But sometimes, it is generated when an EA created for mini or micro accounts is used on a standard account. If you stumble upon an OrderSend Error 131 during your strategy testing, you can quickly find the wrong settings of your EA. To do so, find the standard OnInit() (or init() in older versions of MT4) function inside your EA’s code and insert these lines of code there:

The output will be valid for the current chart’s trading symbol and for the trading account type you are currently logged in. The first line will tell you how many units there are in one lot of the current trading symbol (100,000 would mean a lot). Remember that in your expert advisor’s log, this line will be first from the bottom. The second line will tell you the minimum amount of lots you can trade (this is the most usual error; you probably just need to fix the amount of lots your EA trades from 0.1 to 1). The third one will give the step size for the trade volume in lots. The fourth line will tell you the maximum number of lots that your EA can trade.

For example, a Standard trading account at Exness Forex broker generates the following information when the above-mentioned lines of code are executed on a EUR/USD chart:

This means that 1 lot comprises 100,000 units (a standard size), the minimum trade volume is 0.01 lot (so, you can trade starting from $0.10 per pip in a currency pair), the minimum trade volume step is also 0.01 lot (you can trade 0.33, 0.4 or 1.25 lot volumes, but you cannot send orders with 0.333 lot size), and the maximum volume you can use to open a position is 200 lots.

You can incorporate the MarketInfo() function at a more complex level into your EA, so that it could automatically check the allowed values and auto-correct the EA’s trade parameters. But if you don’t want to code much, you can just use the code above to find out the right values and correct the settings manually.

You can discuss your personal struggles with the OrderSend Error 131 problem on our forum if you are having trouble solving this issue on your own.

If you want to get news of the most recent updates to our guides or anything else related to Forex trading, you can subscribe to our monthly newsletter.

Источник

OrderSend: Error code 131

You should backtest the EA with a larger lot size that exceeds the margin limit,

or the broker lot size limit. Then, of course you will get an error,
— because the validation process performs that stage.

So, now you can set a new function to handle it automatically.

You can use this function to normalize volume:

You have to check if the returned value isn’t zero (it means that your requested volume is less than the minimum allowed volume).

I am using this code for Money Management, it uses NormalizeDouble for round lots and minimum lot size (0.01):

So I think MQL5 system doesn’t admit less than 0.1 lot, is it true?

You can use this function to normalize volume:

You have to check if the returned value isn’t zero (it means that your requested volume is less than the minimum allowed volume).

Yohana Parmi :

131 Invalid trade volume.

You should backtest the EA with a larger lot size that exceeds the margin limit,

or the broker lot size limit. Then, of course you will get an error,
— because the validation process performs that stage.

So, now you can set a new function to handle it automatically.

I tried this and doesn’t give that error anymore.

Now it gives a new error code 134, I tried this:

And now error 131 again.

I tried this and doesn’t give that error anymore.

Now it gives a new error code 134, I tried this:

And now error 131 again.

«If a check shows that there are insufficient funds to perform a trade operation, it is necessary to output an error message to the log instead of calling the OrderSend() function».

Just added that error message and passed the validation. Thanks to all.

Источник

Помогите исправить ошибку OrderModify error 1 и OrderSend error 131!

Советник по принципу Мартингейла, вход по сигналам индикатора CCI, eurusd, M5. Результат теста не плохой! Но..

После теста советника выдает ошибку: OrderModify error 1 и OrderSend error 131. Лот используется 1.0

Ничего не получается! Помогите наглядно поправить код советника или правильно вписать функцию отправки запроса на модификацию уровней и проверку корректности объема. Спасибо!

//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
#property copyright «»
#property link «»
#include
#include
//ннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
extern string MM_set = «Money Managment settings» ;
extern double Lot = 0.01 ; // разер лота для начала торгов
extern int lotdecimal = 2 ; // сколько знаков после запятой в лоте рассчитывать 0 — нормальные лоты (1), 1 — минилоты (0.1), 2 — микро (0.01)
extern double ExpoLot = 1.2 ; // на сколько умножать лот при выставлении следующего колена. пример: первый лот 0.1, серия: 0.16, 0.26, 0.43 .
bool DynamicPips = true ;
int DefaultPips= 0 ;
extern int Depth = 12 ;
extern int Grid = 2 ;
extern double slip = 2.0 ; // на сколько может отличаться цена в случае если ДЦ запросит реквоты (в последний момент немного поменяет цену)
extern double TakeProfit = 10.0 ; // по достижении скольких пунктов прибыли закрывать сделку
extern double Drop = 1500 ;
int PipStep= 0 ;
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
extern int MaxTrades = 10 ; // максимально количество одновременно открытых ордеров
extern bool UseEquityStop = FALSE ;
extern double TotalEquityRisk = 20.0 ;
extern int MagicNumber = 2222 ; // волшебное число (помогает советнику отличить свои ставки от чужих)
//extern bool UseTrailingStop = FALSE;
bool UseTimeOut = FALSE ; // использовать таймаут (закрывать сделки если они «висят» слишком долго)
double MaxTradeOpenHours = 48.0 ; // время таймаута сделок в часах (через сколько закрывать зависшие сделки)
extern string CCI_set = «CCI settings» ;
extern int CCI_Period = 21 ;
extern int CCI_Price = 2 ;
extern double CCI_Max = 300 ;
extern double CCI_Min = — 300 ;
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
double PriceTarget, StartEquity, BuyTarget, SellTarget;
double AveragePrice, SellLimit, BuyLimit;
double LastBuyPrice, LastSellPrice, Spread;
bool flag;
string EAName= «CCI Martin» ;
int timeprev = 0 , expiration;
int NumOfTrades = 0 ;
double iLots;
int cnt = 0 , total;
double Stopper = 0.0 ;
bool TradeNow = FALSE , LongTrade = FALSE , ShortTrade = FALSE ;
int ticket,Error;
bool NewOrdersPlaced = FALSE , NeedModifyOrder = False ;
double AccountEquityHighAmt, PrevEquity;
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
int init() <
Spread = MarketInfo ( Symbol (), MODE_SPREAD ) * Point ;
return ( 0 );
>

int deinit() <
return ( 0 );
>
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
int start()
<
double PrevCl;
double CurrCl;
//*защита от резкого движения*//
if (( iCCI ( NULL , 30 , 55 , 0 , 0 )>Drop && ShortTrade)||( iCCI ( NULL , 30 , 55 , 0 , 0 ) Print ( «Closed All due to TimeOut» );
>

if (timeprev == Time [ 0 ]) return ( 0 ); //new bar apear check
timeprev = Time [ 0 ];

if (DynamicPips)
<
double hival= High [ iHighest ( NULL , 0 , MODE_HIGH ,Depth, 1 )]; // calculate highest and lowest price from last bar to 24 bars ago
double loval= Low [ iLowest ( NULL , 0 , MODE_LOW ,Depth, 1 )]; // chart used for symbol and time period
PipStep= NormalizeDouble ((hival-loval)/Grid/ Point , 0 ); // calculate pips for spread between orders
Print ( «PipStep = » ,PipStep);

>
double CurrentPairProfit = CalculateProfit();
if (UseEquityStop)
if (CurrentPairProfit 0.0 && MathAbs (CurrentPairProfit) > TotalEquityRisk / 100.0 * AccountEquityHigh())
<
CloseThisSymbolAll();
Print ( «Closed All due to Stop Out» );
NewOrdersPlaced = FALSE ;
>

total = CountOfOrders(); //calculating open orders function

if (total > 0 && total Print ( «total > 0» );
for ( int i = 0 ; i OrdersTotal (); i++)
if ( OrderSelect ( i, SELECT_BY_POS , MODE_TRADES ))
if ( OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber)
<
switch ( OrderType ())
<
case OP_BUY :
LongTrade = TRUE ;
ShortTrade = FALSE ;
break ;
case OP_SELL :
LongTrade = FALSE ;
ShortTrade = TRUE ;
break ;
>
break ;
>
LastBuyPrice = FindLastBuyPrice();
LastSellPrice = FindLastSellPrice();
if (LongTrade && LastBuyPrice — Ask >= PipStep * Point ) TradeNow = TRUE ;
if (ShortTrade && Bid — LastSellPrice >= PipStep * Point ) TradeNow = TRUE ;

>
else
<
Print ( «total = 0» );
ShortTrade = FALSE ;
LongTrade = FALSE ;
TradeNow = TRUE ;
StartEquity = AccountEquity ();
>
if (total > 0 )
if (TradeNow)
<
iLots = NormalizeDouble (Lot * MathPow (ExpoLot, total), lotdecimal);
if (ShortTrade)
<
ticket = SendMarketOrder( OP_SELL , iLots, 0 , 0 , MagicNumber, EAName + «-» + NumOfTrades + «-» + PipStep);
>
if (LongTrade)
<
ticket = SendMarketOrder( OP_BUY , iLots, 0 , 0 , MagicNumber, EAName + «-» + NumOfTrades + «-» + PipStep);
>
if (ticket > 0 )
<
TradeNow = FALSE ;
NewOrdersPlaced = TRUE ;
NeedModifyOrder = TRUE ;
>
else
return ( 0 );
>

if (TradeNow && total 1 ) <
Print ( «Open first order» );
ticket = 0 ;
PrevCl = iClose ( Symbol (), 0 , 2 );
CurrCl = iClose ( Symbol (), 0 , 1 );

if (PrevCl > CurrCl)
<
Print ( «Achieved condition SELL» );
if ( iCCI ( Symbol (), Period (), CCI_Period, CCI_Price, 1 ) Print ( «successful check» );
ticket = SendMarketOrder( OP_SELL , Lot, TakeProfit, 0 , MagicNumber, EAName + «-» + total);
>
>
if (PrevCl Print ( «Achieved condition BUY» );
if ( iCCI ( Symbol (), Period (), CCI_Period, CCI_Price, 1 ) >= CCI_Max)
<
Print ( «successful check» );
ticket = SendMarketOrder( OP_BUY , Lot, TakeProfit, 0 , MagicNumber, EAName + «-» + total);
>
>
if (ticket > 0 )
<
TradeNow = FALSE ;
NewOrdersPlaced = TRUE ;
NeedModifyOrder = False ;
>
else
return ( 0 );
>

if (ShortTrade)
<
PriceTarget = AveragePrice — TakeProfit * Point ;
NeedModifyOrder = TRUE ;
>
if (LongTrade)
<
PriceTarget = AveragePrice + TakeProfit * Point ;
NeedModifyOrder = TRUE ;
>
>

if (NewOrdersPlaced)
if (NeedModifyOrder)
<
Print ( «Modify all orders in the market» );
for ( int i1 = 0 ; i1 OrdersTotal (); i1++)
if ( OrderSelect (i1, SELECT_BY_POS , MODE_TRADES ))
if ( OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber)
ModifyOrder(PriceTarget);
NewOrdersPlaced = FALSE ;
>
return ( 0 );
>
//ннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
int CountOfOrders()
<
int count = 0 ;
for ( int i = 0 ; i OrdersTotal (); i++)
if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
if (( OrderSymbol () == Symbol ()) && ( OrderMagicNumber () == MagicNumber))
if (( OrderType () == OP_SELL ) || ( OrderType () == OP_BUY ))
count++;
return (count);
>

void CloseThisSymbolAll() <
for ( int trade = OrdersTotal () — 1 ; trade >= 0 ; trade—) <
if (! OrderSelect (trade, SELECT_BY_POS , MODE_TRADES )) Print ( «error!» );
if ( OrderSymbol () == Symbol ()) <
if ( OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber) <
if ( OrderType () == OP_BUY ) int ticket1= OrderClose ( OrderTicket (), OrderLots (), Bid , slip, Blue);
if ( OrderType () == OP_SELL ) ticket1= OrderClose ( OrderTicket (), OrderLots (), Ask , slip, Red);
>
Sleep ( 1000 );
>
>
>
//=========================================================================
int SendMarketOrder( int Type, double Lot1, int TP, int SL, int Magic, string Cmnt)
<
double Price, Take, Stop;
int Ticket, Slippage, Color, Err;
bool Delay = False ;
Print ( «SendMarketOrder function» );
while (! IsStopped ())
<
/*if(!IsExpertEnabled())
<
Error = ERR_TRADE_DISABLED;
Print(«EA trading is forbidden!»);
return(-1);
>
Print(«EA trading is allowed»);*/
if (! IsConnected ())
<
Error = ERR_NO_CONNECTION ;
Print ( «Communication is absent!» );
return (- 1 );
>
Print ( «Communication with the server is installed» );
if ( IsTradeContextBusy ())
<
Print ( «The trade stream is occupied!» );
Print ( «waiting 3 sec. » );
Sleep ( 3000 );
Delay = True ;
continue ;
>
Print ( «The trade stream is free» );
if (Delay)
<
Print ( «updating quotes» );
RefreshRates ();
Delay = False ;
>
else
<
Print ( «Delays weren’t» );
>
switch (Type)
<
case OP_BUY :
Print ( «initialize parameters for BUY-order» );
Price = NormalizeDouble ( Ask , Digits );
Take = IIFd(TP == 0 , 0 , NormalizeDouble ( Ask + TP * Point , Digits ));
Stop = IIFd(SL == 0 , 0 , NormalizeDouble ( Ask — SL * Point , Digits ));
Color = Blue;
break ;
case OP_SELL :
Print ( «iinitialize parameters for SELL-order» );
Price = NormalizeDouble ( Bid , Digits );
Take = IIFd(TP == 0 , 0 , NormalizeDouble ( Bid — TP * Point , Digits ));
Stop = IIFd(SL == 0 , 0 , NormalizeDouble ( Bid + SL * Point , Digits ));
Color = Red;
break ;
default :
Print ( «order type doesn’t conform to requirements.» );
return (- 1 );
>
Slippage = MarketInfo ( Symbol (), MODE_SPREAD );
Print ( «Slippage = » ,Slippage);
if ( IsTradeAllowed ())
<
Print ( «Trading is allowed, sending order. » );
Ticket = OrderSend ( Symbol (), Type, Lot1, Price, Slippage, Stop, Take, Cmnt, Magic, 0 , Color);
if (Ticket 0 )
<
Err = GetLastError ();
if (Err == 4 || /* SERVER_BUSY */
//Err == 130 || /* INVALID_STOPS */
Err == 135 || /* PRICE_CHANGED */
Err == 137 || /* BROKER_BUSY */
Err == 138 || /* REQUOTE */
Err == 146 || /* TRADE_CONTEXT_BUSY */
Err == 136 ) /* OFF_QUOTES */
<
Print ( «error» ) ;
Print ( «waitng 3 sec. » );
Sleep ( 3000 );
Delay = True ;
continue ;
>
else
<
Print ( «Critical error» );
Error = Err;
break ;
>
>
break ;
>
else
<
Print ( «EA trading is forbidden or trade stream is occupied!» );
Print ( «waitng 3 sec. » );
Sleep ( 3000 );
Delay = True ;
continue ;
>
>
Print ( «The order has been sent successfully. Тicket = » ,Ticket);
return (Ticket);
>
//==================================================================
double IIFd( bool condition, double ifTrue, double ifFalse)
<
if (condition) return (ifTrue); else return (ifFalse);
>
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
double CalculateProfit()
<
double Profit = 0 ;
for ( int i = 0 ; i OrdersTotal (); i++)
if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
if (( OrderSymbol () == Symbol ()) && ( OrderMagicNumber () == MagicNumber))
if (( OrderType () == OP_BUY ) || ( OrderType () == OP_SELL ))
Profit += OrderProfit ();
return (Profit);
>
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн

double AccountEquityHigh() <
if (CountOfOrders() == 0 ) AccountEquityHighAmt = AccountEquity ();
if (AccountEquityHighAmt else AccountEquityHighAmt = AccountEquity ();
PrevEquity = AccountEquity ();
return (AccountEquityHighAmt);
>
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн

double FindLastBuyPrice() <
double oldorderopenprice;
int oldticketnumber;
double unused = 0 ;
int ticketnumber = 0 ;
for (cnt = OrdersTotal () — 1 ; cnt >= 0 ; cnt—) <
if (! OrderSelect (cnt, SELECT_BY_POS , MODE_TRADES )) Print ( «error!» );
if ( OrderSymbol () != Symbol () || OrderMagicNumber () != MagicNumber) continue ;
if ( OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber && OrderType () == OP_BUY ) <
oldticketnumber = OrderTicket ();
if (oldticketnumber > ticketnumber) <
oldorderopenprice = OrderOpenPrice ();
unused = oldorderopenprice;
ticketnumber = oldticketnumber;
>
>
>
return (oldorderopenprice);
>

double FindLastSellPrice() <
double oldorderopenprice;
int oldticketnumber;
double unused = 0 ;
int ticketnumber = 0 ;
for (cnt = OrdersTotal () — 1 ; cnt >= 0 ; cnt—) <
if (! OrderSelect (cnt, SELECT_BY_POS , MODE_TRADES )) Print ( «error» );
if ( OrderSymbol () != Symbol () || OrderMagicNumber () != MagicNumber) continue ;
if ( OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber && OrderType () == OP_SELL ) <
oldticketnumber = OrderTicket ();
if (oldticketnumber > ticketnumber) <
oldorderopenprice = OrderOpenPrice ();
unused = oldorderopenprice;
ticketnumber = oldticketnumber;
>
>
>
return (oldorderopenprice);
>
//ннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
double CalculateAveragePrice()
<
AveragePrice = 0 ;
double Count = 0 ;
for ( int i = 0 ; i OrdersTotal (); i++)
if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
if ( OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber)
if ( OrderType () == OP_BUY || OrderType () == OP_SELL )
<
AveragePrice += OrderOpenPrice () * OrderLots ();
Count += OrderLots ();
>
if (AveragePrice > 0 && Count > 0 )
return ( NormalizeDouble (AveragePrice / Count, Digits ));
else
return ( 0 );
>

bool ModifyOrder( double takeprofit)
<
while (! IsStopped ())
<
Print ( «ModifyOrder function» );
if ( IsTradeContextBusy ())
<
Print ( «The trade stream is occupied!» );
Sleep ( 3000 );
continue ;
>
Print ( «The trade stream is free» );
if (! IsTradeAllowed ())
<
Print ( «EA trading is forbidden or trade stream is occupied!» );
Sleep ( 3000 );
continue ;
>
Print ( «EA trading is allowed, order modify #» , OrderTicket ());
if (! OrderModify ( OrderTicket (), OrderOpenPrice (), 0 , NormalizeDouble (takeprofit, Digits ), 0 , Yellow))
<
Print ( «Unable to modify order» );
int Err = GetLastError ();
Print ( «error» );
break ;
//Sleep(1000);
//continue;
>
else
<
Print ( «Order modification completed successfully» );
break ;
>
>
return ( True );
>

Источник

OrderSend Error 131 is a very frequent problem that is usually encountered when testing MT4 expert advisors. What causes this error? It is called ERR_INVALID_TRADE_VOLUME in the MetaTrader 4 documentation. It means that your expert advisor (EA) is trying to send an order with invalid trade volume. At the absolute majority of the MT4 brokers, setting some EA to open an order with 0.123 lots volume will generate this error. But sometimes, it is generated when an EA created for mini or micro accounts is used on a standard account. If you stumble upon an OrderSend Error 131 during your strategy testing, you can quickly find the wrong settings of your EA. To do so, find the standard OnInit() (or init() in older versions of MT4) function inside your EA’s code and insert these lines of code there:

The output will be valid for the current chart’s trading symbol and for the trading account type you are currently logged in. The first line will tell you how many units there are in one lot of the current trading symbol (100,000 would mean a standard-sized lot). Remember that in your expert advisor’s log, this line will be first from the bottom. The second line will tell you the minimum amount of lots you can trade (this is the most usual error; you probably just need to fix the amount of lots your EA trades from 0.1 to 1). The third one will give the step size for the trade volume in lots. The fourth line will tell you the maximum number of lots that your EA can trade.

For example, a Standard trading account at Exness Forex broker generates the following information when the above-mentioned lines of code are executed on a EUR/USD chart:

Example Output of Min Lot, Max Lot, Lot Size, and Lot Step in MetaTrader 4

This means that 1 lot comprises 100,000 units (a standard size), the minimum trade volume is 0.01 lot (so, you can trade starting from $0.10 per pip in a dollar-based currency pair), the minimum trade volume step is also 0.01 lot (you can trade 0.33, 0.4 or 1.25 lot volumes, but you cannot send orders with 0.333 lot size), and the maximum volume you can use to open a position is 200 lots.

You can incorporate the MarketInfo() function at a more complex level into your EA, so that it could automatically check the allowed values and auto-correct the EA’s trade parameters. But if you don’t want to code much, you can just use the code above to find out the right values and correct the settings manually.

You can discuss your personal struggles with the OrderSend Error 131 problem on our forum if you are having trouble solving this issue on your own.

2009.10.27 22:49:11 2009.04.01 03:23 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50975000 sl 1.32780000 tp 1.51157000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 03:23 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 03:15 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50908000 sl 1.32713000 tp 1.51090000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 03:15 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 03:10 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50853000 sl 1.32658000 tp 1.51035000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 03:10 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 03:10 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50843000 sl 1.32648000 tp 1.51025000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 03:10 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 03:10 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50848000 sl 1.32653000 tp 1.51030000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 03:10 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 03:09 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50803000 sl 1.32608000 tp 1.50985000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 03:09 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 02:59 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50668000 sl 1.32472000 tp 1.50850000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 02:59 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50749000 sl 1.32553000 tp 1.50931000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50754000 sl 1.32558000 tp 1.50936000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50759000 sl 1.32563000 tp 1.50941000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50763000 sl 1.32567000 tp 1.50945000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend error 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend()- Ошибка OP_BUY. op 1.50768000 sl 1.32572000 tp 1.50950000 lot 0.11000000 free margin 164043.29600000 err 131
2009.10.27 22:49:11 2009.04.01 02:58 (777) YODJ EURCHF,M1: OrderSend error 131

такая воот ошибка, не могу понять откуда берется….

нормалайз все значения, деньги есть (в приведенном логе видно), вообщем что то я в тупике :)) какие объемы? все выставленно нормально -(

What is MT4 Error 131?

The MT4 error 131 is an invalid volume OrderSend error code. It suggests that your Expert Advisor (EA) sends an order with an inappropriate trade volume to your broker’s server.

This error code may frequently appear during testing an MT4 EA, especially when there is an issue with the volume settings of your trading robot. Otherwise, it may happen due to a coding error of the expert advisor.

MT4 Error 131

The biggest problem with the OrderSend error 131 is it entirely disables your trading bot from executing backtests and fresh orders. It may happen for both paid and open-source EAs, because most of the time, it occurs due to a mismatch of volume calculation methods between the EA and the serving brokers.

So, your trading platform showing an error 131 doesn’t necessarily mean you need to abandon your EA or the broker. If there is a problem with the bot’s programming, you might need a few edits with the coding. Otherwise, you may check the volume settings of your expert advisor and fix the issue by only making a few changes.

In this guide, we explain the possible scenarios of encountering the error 131. Also, we discuss a couple of solutions for getting rid of the invalid volume OrderSend problem from your MT4 platform.

Why does MT4 error 131 happen?

An MT4 error 131 may happen due to the following reasons:

The EA is using an inappropriate volume figure

Most EAs calculate a trading volume based on the risk percentage, which is entirely acceptable and fair. But the problem occurs when the calculated figure comes with more than two digits. For instance, if it is a 0.01 or 0.11 lot, then there is no problem. But if it sends an order with a volume like 0.111 or 0.245, it’ll show the error code 131.

Issues with the volume settings

How your broker recognizes a trading volume may differ depending on your trading account types. Suppose your EA is configured for a micro account, and you’re using it for a standard account. In this case, your broker may read a 0.01 lot as 0.001, considering the figure is less than the minimum order limit. As a result, the order becomes invalid, and the system shows the same OrderSend error.

How to fix MT4 error 131?

Time needed: 5 minutes.

How to fix MT4 Invalid Volume OrderSend errors

  1. Adjust the volume settings

    If your broker fails to define the trading volume correctly, then insert the following codes to reset your volume settings:

    MT4 error 131 adjust-volume

    MODE_LOTSIZE – It determines the number of units an EA will consider to count as one standard lot. Typically, a standard-size lot equals 100,000 units.

    MODE_MINLOT – The minimum amount of trading volume you’ll use for executing an order. If your broker doesn’t accept 0.01 as the minimum lot size, consider replacing the value by 1.

    MODE_LOTSTEP – It sets the step size of your trading volume.

    MODE_MAXLOT – The maximum trading lot you can use for an order.

  2. Normalize the volume

    Alternatively, you can try normalizing the volume configuration of the EA with the following lines of code:

    MT4 Error 131 normalise volume

    This setting will keep the normalized volume lesser than the non-normalized value. For example, if the non-normalized volume is 0.1234, then the normalized volume will be 0.12.

    Also, you may encounter the MT4 error 131 during backtesting an EA. In that case, simply go offline and then try backtesting again.

July 10th, 2008

OrderSend Error 131 is a very popular problem that is usually encountered when testing MT4 expert advisors.
What causes this error? It’s called ERR_INVALID_TRADE_VOLUME
in the MT4 code. That means that your expert advisor is trying to send
an order with invalid trade volume. On the absolute majority
of the MT4 brokers setting some EA to open an order 0.123 lots will
generate this error. But sometimes it’s generated when the EA, created
for mini or micro accounts, is used on the standard account. If you
stumble on OrderSend Error 131 during your testing, you can quickly find
out the wrong settings of your EA — find the standard init() function
inside your EA’s code and insert these lines of code there:

Print(MarketInfo(Symbol(), MODE_LOTSIZE));
Print(MarketInfo(Symbol(), MODE_MINLOT));
Print(MarketInfo(Symbol(), MODE_LOTSTEP));
Print(MarketInfo(Symbol(), MODE_MAXLOT));

The first line will give you the information regarding how many units
one lot holds when you trade in this account (100000 would mean a 

standard-sized

lot). Remember, that in your expert advisor’s log this line will
be first starting from down to up, not vice versa. The second line will
tell you the minimum amount of lots you can trade (this is the most
usual error; you’ll probably just need to fix the amount of lots your
EA trades from 0.1 to 1). The third one will give the minimum step
for the trade volume in lots. The fourth line will tell you the maximum
amount of lots that your EA can trade.

For example, demo account at FXOpen generates this info when I insert those lines into the code:

2008.07.10 15:13:37 MACD Sample EURUSD, H1: 10000
2008.07.10 15:13:37 MACD Sample EURUSD, H1: 0.01
2008.07.10 15:13:37 MACD Sample EURUSD, H1: 0.01
2008.07.10 15:13:37 MACD Sample EURUSD, H1: 100000

That means that 1 lot is 100,000 units (a standard size), minimum
trade volume is 0.01 lot (so, one can trade starting from
$10 on 1 position in a 

dollar-based

currency pair), minimum
trade volume step is also 0.01 lot (one can trade 0.33, 0.4 or 1.25 lot
volumes, but can’t send orders with 0.333 lot size) and the maximum
volume one can use to open a position is 10,000 lots.

You can incorporate the MarketInfo() function at a more complex level
into your EA, so it could automatically check the allowed values
and correct its settings. But if you don’t want to code much, you can
just use the code above to find out the right values and correct
the settings manually.

Hi Petko,

Thanks for your reply, and for pointing out that the journal shows an error.. I looked up “mt4 ordersend error 131” and found out the following info:

Handling OrderSend Error 131 in MetaTrader 4

OrderSend Error 131 is a very popular problem that is usually encountered when testing MT4 expert advisors. What causes this error? It’s called ERR_INVALID_TRADE_VOLUME in the MT4 code. That means that your expert advisor is trying to send an order with invalid trade volume. On the absolute majority of the MT4 brokers setting some EA to open an order 0.123 lots will generate this error. But sometimes it’s generated when the EA, created for mini or micro accounts, is used on the standard account.

I am using a micro live account, could it be that the EA is programmed with the wrong lot size for the account I have? Or does the .json exported from MT4 file know all that stuff automatically?

Yes, I know my data is very limited.. it has been a huge struggle for me. My understanding is the the best data is the ACTUAL data from your broker, but here in the UK, not many brokers seem to offer MT4 that comes with data longer than a few months when you first install it.

My method to get around this, so far, has been to set up a VPS purely for the purpose of collecting data – I first started collecting it in January 2018, but very frustratingly (and I hold my hand up here for negligence), the VPS must have been rebooted by the hosting provider, possibly for maintenance or similar, some time in June 2018, because after a very busy summer/autumn with my other business, I checked the VPS  in Jan 2019 to assess the data it had collected, only to find it had not been doing so since Jun 2018. Hence using the small amount of data I do have, starting in Jan 2019, and looking at the M1 timeframe, as that is obviously the highest count of bars I have for getting the largest data horizon.

I read about people using services like Tickstory, but I just don’t see how it can be as reliable as ACTUAL broker data, do you have any thoughts on that?…

In any case, after looking up the ordersend error 131, I altered the lot size for the strategy to 0.1 lot, and tried again in the MT4 Strategy Tester, and actually got much better results, please see below:

(PS: this isn’t a strategy at all developed for trading, it’s purely for checking that my workflow process is being set up ok)

You can see that it has 410 journal entries… the MT4 Strategy Tester results tab as 440 results, although the times and prices of the trades don’t match up very well at the start of the backtest, but they do at the end… why is that?

Is it because EA Studio is not calibrated to the same timezone as my MT4?

The graph is similar to the graph in EA Studio, although it shows better results than in EA Studio..

I don’t know what much of the report tab means, but I’m guessing that the completely red bar at the top isn’t good?..

Thanks,

Simon

All Expert Advisors created by EA Coder display a special error message code on MT4 charts when an error occurs during the open, close or modification phase of an order. If you see a message like ‘oe131’ on your chart when a new trade was supposed to be opened, you’ll know that an error has occurred.

Types of error message codes

Error message codes always start with two letters followed by an error code number. The error codes I use are the same as those used in the MQL4 programming language and are explained in detail on the MQL4 documentation page.

Error codes may start with oe, me or ce.

oe stands for “open error“, me stands for “modify error“, and ce stands for “close error“.

MT4 chart with error message code and a trade delay indicator

When an error occurs during trade open

Take our previous example oe131. Now we know that it indicates an error during a trade open, with the code 131. If you look at the full list of error code descriptions, this one means “invalid trade volume”, which alerts us to check the money management settings that we have set for the Expert Advisor. This kind of error appears when a lot size is zero, if it is too small or if it is too big, because all brokers have lot size limitations. Some do not allow the lot size to be smaller than 0.1 while others allow lot sizes as low as 0.01. This varies among different brokers and different account types.

Usually Expert Advisors from EA Coder fix the lot size according to the broker limitations, but exceptions may apply because not all brokers report the correct limitation values for the EAs. An example of this is a broker reporting the minimum allowed lot size to be 0.01 while in reality it is actually 0.1. In a case like this, if you to set the EA to use a lot size somewhere between 0.01 and 0.09 it will fail to place orders as it won’t be able to fix the lot size because of it being reported incorrectly. Then you will get the oe131 error message printed on the chart.

Another example would be to get the oe133 error. This stands as “Trade is disabled” and it means that the broker does not allow to trade that pair. If this error appears even when customer tries to open trade manually on the same chart, then MT4 EA should be attached to a similar pair with the suffix. For example if you get this error on EURUSD, please look for pair name like EURUSDm or EURUSDFXF.

If you are able to open trades manually on the same pair it could be that your broker does not allow to use trading robots (EA’s) on that pair or account. Contact them for more info.

Common trade open errors:

  • 128 – Trade timeout.
  • 129 – Invalid price.
  • 130 – Invalid stops.
  • 131 – Invalid trade volume.
  • 133 – Trade is disabled.
  • 134 – Not enough money.
  • 146 – Trade context is busy.

When an error occurs during order modification

Let’s take a look at another common error that you may receive. It would be printed on your chart as me130 which stands for “modify error 130” and means “invalid stops”. This tells us that the stop loss and/or take profit values are incorrect or too close to the current market price. The minimum distance between the market and stop prices are called StopLevel limitation; this value simply tells the EA what size in pips the limitation is. On 5 digit brokers this is reported as points and must be converted to pips. However that is something the user don’t need to worry about, because EA Coder Expert Advisors handle these things automatically. But if you get a me130 error, be sure to check the TP and SL values that you’re using.

Common trade modification errors:

  • 128 – Trade timeout.
  • 130 – Invalid stops.
  • 146 – Trade context is busy.

When an error occurs during trade close

You may get a ce146 error when EA tries to close an order. This indicates that a “close error” occurred whose code is 146. This means “trading context busy” and it is very common error, specially on older MT4 terminals when you have multiple Expert Advisors attached. EA Coder robots have an intelligent error handling mechanism built in and will do their best to avoid “trading context busy” errors even if you have multiple robots operating on your account. But in case you get one of these errors, just try to minimize the number of EAs running on the same account or set them to avoid performing trading operations at the same time if that’s possible with your EA.

Common trade close errors:

  • 128 – Trade timeout.
  • 146 – Trade context is busy.

Delaying of trading operations

EA may need to delay a trading operation to avoid disrupting the MQL programming rules when an error occurs. It will retry the same trading operation if required and will have to wait somewhere between 1 to 5 seconds between each attempt. These are very logical rules of Metatrader programming and EA Coder trading robots obey them. See full list of execution errors.

In case there is a delay in performing a trading operation (whether it is opening, modifying or closing a trade) EA will print a small clock picture on the chart. This indicates that there was some kind of error and EA had to delay its operation for a few seconds to obey the rules and not overload the brokers’ servers.

Experts tab in MT4 terminal

When any error occurs, the EA will print a more detailed error message in the Experts tab at the bottom of the MT4 terminal. You can switch to that tab any time and scroll down to see a complete list of errors, warnings and informational messages. These can help to solve a range of problems quickly even if you don’t have a lot of experience in using the MT4 platform and Expert Advisors or custom indicators.

Error messages in the Experts tab of the MT4 client terminal

Opening the log files folder directly from an MT4 terminal

When you’re viewing the Experts tab you can click the right mouse button anywhere in that area and choose “Open”. This will open the log files folder for you. This folder contains files with the same messages that you see in the Experts tab, but from here you can access messages from previous days and weeks. Also, messages in the log files are presented in their full format and are not trimmed like some of the messages shown in the Experts tab when they are too long.

Open MT4 Experts log files folder easily

MT4 Experts log files folder

Reporting an error to EA Coder

When you need to report an error to EA Coder, please describe the problem you are having in detail, include the trade numbers that you are having problems with, and make sure you attach any necessary files. It is very important that you send the log files from your MT4-folderexpertslogs so that I’m able to investigate an error. Also please include screen shots of the chart where EA is running and if possible make sure that the problem is visible in the picture. This will help us provide you with more useful support.

You might notice that your log files folder is empty or doesn’t have any recent log files (the file names indicate the date they were created). In this case please carry out the steps described above which detail how to open the log files folder directly from the Experts tab at the bottom of your MT4 terminal.

Before you report a problem or request support for learning how an EA feature works, please refer to the instructional manual. This may help you solve your problem faster and you will also learn how to use the application better.

Order labeling during EA backtest

Our Expert Advisors have a special order labeling mechanism built in. It is activated when you run EA in the Strategy Tester of your MT4 and it will create label numbers for each order that is placed during a backtest. This helps to track your trades easily as you will see the order numbers above each trade on the chart.

Trade numbering when EA runs in MT4 strategy tester

[mailchimp-article-newsletter]


Rimantas Petrauskas

First I am a father, a husband and then the author of the book “How to Start Your Own Forex Signals Service”. I am also a Forex trader, a programmer, an entrepreneur, and the founder of ea-coder.com Forex blog. I have created two of the most popular trade copiers and other trading tools for MT4 that are already used world wide by hundreds of currency traders.

Понравилась статья? Поделить с друзьями:
  • Ошибка 131 iveco daily
  • Ошибка 130е20 bmw
  • Ошибка 130f00 мерседес
  • Ошибка 1327 недопустимый диск f
  • Ошибка 130e01 бмв