Orderclose error 131 mql4

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

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

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

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

Содержание

  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.

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.

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

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

Некоторые наиболее часто возникающие проблемы- ошибки в работе форекс — советников и возможные способы их решения. Коды ошибок можно узнать, посмотрев папки «Эксперты» и «Журнал» панели «Терминал», или папку «Журнал» панели «Тестер», если ошибки происходят в процессе тестирования.

ошибки в работе советника мт4

Ошибки в процессе тестирования советника

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

Все коды ошибок.

ошибка 4, 146
Торговый сервер занят
1. Советник подал слишком много приказов одновременно
2. Не дождавшись ответа от сервера, при выполнении операции — советник пытается отправить новый приказ, Сервер перегружен

Способы решения:
1. Перезагрузка терминала
2. Оптимизация кода советника с помощью функций обработки ошибок.

ошибка 8, 141
Слишком частые запросы
1. Предыдущие причины ошибки, в сильно частом запросе.

ошибка129
Неправильная цена
1. Цена по которой Вы пытаетесь открыть позицию (BUY SELL)- неправильная

Способы решения:
1. Золотое правило: BUY нужно открывать по Ask а закрывать по BID, SELL нужно открывать по BID а закрывать по ASK

ошибка 130,145
Неправильные стопы
1. Стопы= Стоплосс, тейкпрофит или уровень открытия отложенника или лимитника.
2. Стопы расположены слишком близко к цене
3. Ваш счет открыт в группе ECN  или NDD
4. Ваш брокер использует Рыночное исполнение позиций

Способы решения:
1. Проверьте значения Ваших стоплосс, тейпрофитов
2. Уточните минимальный стоп уровень по Вашему инструменту у брокера, при выставлении стопов — соблюдайте уровень минимальной дистанции
3. В хорошо написанном советнике должны быть функции работы на счетах ECN и NDD

ошибка 131
Неправильный объем
1. Неправильный лот при открытии сделки
2. Лот, который вы пытаетесь открыть, меньше минимального
3. Лот, который вы пытаетесь открыть больше максимального
4. Разрядность лота отличается от разрядности брокера.

Способы решения:
1. Проверьте правильность открытия лота, изучите спецификацию контракта и прочтите условия торговли в Вашем ДЦ
2. Проверьте, Минимальный и Максимальный лот в Вашем ДЦ и на Вашем счете. На некоторых типах счетов, минимальный лот может быть 0.01 а также 0.1 и даже 3. Максимальный лот может быть 5 лотов и 999 лотов и другие.

3. Уточните разрядность лотов на Вашем сервере. Если например разрядность лотов=1, то можно открыть лот 0.1 или 0.5 или 1.2 и так далее, с 1 знаком после запятой, если разрядность лота 2 знака, то исходя из минимального лота, лот может быть 0.01, 0.06, 0.17, 1.48. Также в некоторых ДЦ существует порядок степени лотов, например можно открыть 0.5 и 1 и 1.5 и так далее, а например 0.6 открыть нельзя. Уточните у своего брокера порядок установки лотов.

ошибка 132
Рынок закрыт
1. Рынок закрыт в Выходные дни

Способы решения:
1. Пробуйте связаться с рынком после выходных

ошибка 133
Торговля запрещена
1. В данный момент торговля запрещена
2. По данной валютной паре запрещено торговать

Способы решения:
1. Попробуйте торговать после выходных

ошибка134
Недостаточно денег для совершения операции
1. Лот, который Вы пытаетесь открыть, слишком большой, на него не хватает маржи

Способы решения:
1. Проверьте уровень свободных средств, и рассчитайте средства, которые Вам нужны, для открытия лота
2. Следите за уровнем Ваших свободных средств

ошибка135..138
Цена изменилась
1. Реквот
2. Слишком быстрый рынок
3. Брокер или ДЦ не дает Вам поставить позицию по заявленной цене

Способы решения:
1. Не торгуйте в такие моменты
2. Увеличьте уровень проскальзывания, но помните что это влечет за собой открытие позиций не по заявленной Вами цене.
3. Сделайте в советнике функцию обработки ошибок и количество попыток открытия позиций

ошибка 147
Использование даты истечения ордера запрещено брокером
1. Ваш советник или Вы пытаетесь установить срок истечения отложенного ордера

Способы решения:
1. В советнике, в функции OrderSend в параметре срок истечения поставьте=0
2. Не устанавливайте срок истечения ордера.

ошибка 148
Количество открытых и отложенных ордеров достигло предела, установленного брокером.
1. Максимальное количествоотк рытых ордеров и позиций достигнут предела, установленного брокером.

Способы решения:
1. Удалите или закройте часть позиций
2. Остановите процесс открытия новых позиций
3. Соблюдайте иерархию сделок, лучше открыть 1 позицию лото 0.1 одновременно, чем 10 позиций лотом 0.01 с потерей спреда.

ошибка 4012, 4013
zero devide

Остаток от деления на ноль
1. Вы пытаетесь поделить число на 0.

Способы решения:
1. Проверьте Весь код советника на наличие такой грубой ошибки, или же проверьте все значения из MarketInfo функций на момент возвращения 0, иногда при MarketInfo(Symbol(),MODE_SPREAD) возвращается не спред а 0 (у брокеров с плавающим спредом)

ошибка 4017
Вызовы DLL не разрешены
1. В Вашем терминале запрещен вызов DLL

Способы решения:
1. Разрешите вызов DLL через Меню – сервис – Настройки – Советник – Разрешить вызов DLL, но помните, разрешайте данную опцию только для советников, в которых Вы уверены, и уверены что в ДЛЛ не сидит какой-нибудь троян. Проверьте ДЛЛ на наличие троянов с помощью антивируса.

ошибка 4018 , 4019
Невозможно загрузить библиотеку
1. Библиотека повреждена
2. Вызов библиотеки осуществляется с ошибкой

Способы решения:
1. Проверьте библиотеку DLL
2. Обратитесь к разработчику данной библиотеки

ошибка 4020
Вызовы внешних библиотечных функций не разрешены
1. В Вашем терминале запрещен вызов функций из внешних экспертов
Способы решения:
1. Разрешите вызов функций через Меню – сервис – Настройки – Советник – Разрешить вызов внешних экспертов,

ошибка 4103
Невозможно открыть файл
1. Данный файл не существует
2. Данный файл заблокирован

Способы решения:
1. Проверьте наличие указанного файла в папке experts – files Тester – files
2. Проверьте не заблокирован ли файл системой антивируса. Разрешен ли режим записичтения файла

ошибка 4106
Неизвестный символ
1. Символа нет в обзоре рынка

Способы решения:
1. В обзоре рынка – правой кнопкой мыши – показать все символы
2. Проверить названия символа в советнике и наличие его в обзоре рынка
3. Некоторые советники используют четкие названия без суфиксов, а брокеры намеренно ставят суфиксы, например EURUSDx где х – суфикс.

ошибка 4108
Неверный номер тикета
1. Тикет ордера, который выбирает эксперт – не существует
2. Эксперт пытается выбрать тикет, но данный ордер был закрыт другим советником или руками.
3. При попытке осуществления приказа над ордером, тикет был исполнен и закрыт брокером.

Способы решения:
1. Если данная ошибка появляется очень часто, 100-1000 раз за минуту, проверьте функции Вашего советника
2. Отключите другие советники, или настройте их так, чтобы они не конфликтовали, не закрывайте ордер руками, когда эксперт выполняет операцию

ошибка 4109
Торговля не разрешена
1. Советнику запрещено торговать, на графике грустный смайл или крестик

Способы решения:
1. Включите галочку «Разрешить советнику торговать» в вкладе при установке советника, либо в меню- сервис – настройки – советники.

ошибка 4110, 4111
1. Длинные позиции не разрешены
2. Короткие позиции не разрешены

Способы решения:
1. В настройках советника, в вкладке Общие не разрешен тип позиций
2. В Вкладке Общие, при установке советника есть выбор позиций:

Long Short – Разрешены BUY SELL
Only Long– Разрешен BUY
Only Short – Разрешен SELL

Другие статьи по теме:

Устранение ошибок в работе эксперта

Коды ошибок в работе советников форекс (константы MQL4)

Тонкости работы торгового терминала MetaTrader4

Очистка терминала МТ4

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Order of war вылетает error memory
  • Order error unable to complete transaction перевод
  • Order drum oki ошибка
  • Order cancel error
  • Orcs must die ошибка при запуске

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

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