Ошибка 4051 mql4 как исправить

Всем привет.

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

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

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

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

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

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

What is MT4 error 4051?

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

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

MT4 Error 4051

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

Why does MT4 error 4051 happen?

You are exceeding your trading limit

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

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

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

Your EA is generating inappropriate order parameters

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

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

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

How to fix MT4 error 4051?

How to fix OrderSend error for invalid lot amount

  1. Use NormalizeDouble in your code

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

    MT4 NormalizeDouble function

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

  2. Adjust the value of NormalizeDouble

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

    MT4 Doubletostring

  3. Make sure normalized figures are rounded

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

    MT4 Normalized Values

  4. Broker trading limitations for lot size

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

Step 1 – Solve Metatrader 4 Ordersend Error 4051

Is Metatrader 4 Ordersend Error 4051 appearing? Would you like to safely and quickly eliminate 4 Ordersend Error which additionally can lead to a blue screen of death?

When you manually edit your Windows Registry trying to take away the invalid invalid lots amount for ordersend function keys you’re taking a authentic chance. Unless you’ve got been adequately trained and experienced you’re in danger of disabling your computer system from working at all. You could bring about irreversible injury to your whole operating system. As very little as just 1 misplaced comma can preserve your Pc from even booting every one of the way by!

Troubleshooting mql4 ordersend error 4051 Windows XP, Vista, 7, 8 & 10

Simply because this chance is so higher, we hugely suggest that you make use of a trusted registry cleaner plan like CCleaner (Microsoft Gold Partner Licensed). This system will scan and then fix any Metatrader 4 Ordersend Error 4051 complications.

Registry cleaners automate the entire procedure of finding invalid registry entries and missing file references (including the Ordersend error) likewise as any broken hyperlinks inside of your registry.

Issue with mt4 ordersend error

Backups are made immediately prior to each and every scan providing you with the choice of undoing any changes with just one click. This protects you against doable damaging your pc. Another advantage to these registry cleaners is that repaired registry errors will strengthen the speed and performance of one’s procedure drastically.

  • http://www.strategyquant.com/forum/topic/2868-4051-metatrader-error-invalid-lots-amount-for-order-send-function/
  • http://www.tradingsystemforex.com/mql-programming/5012-question-ordersend-error-4051-a.html
  • https://www.mql5.com/en/forum/6330
  • http://www.forexfactory.com/showthread.php?p=5825157

Cautionary Note: Yet again, for those who are not an state-of-the-art consumer it’s very encouraged that you simply refrain from editing your Windows Registry manually. If you make even the smallest error within the Registry Editor it can result in you some serious issues that may even call for a brand new set up of Windows. Not all difficulties attributable to incorrect Registry Editor use are solvable.

Fixed: mt4 orderclose error 4051

Symptoms of Metatrader 4 Ordersend Error 4051
“Metatrader 4 Ordersend Error 4051” appears and crashes the energetic method window.
Your Personal computer routinely crashes with Metatrader 4 Ordersend Error 4051 when running the exact same system.
“Metatrader 4 Ordersend Error 4051” is shown.
Windows operates sluggishly and responds little by little to mouse or keyboard input.
Your computer periodically “freezes” for the number of seconds in a time.

Will cause of Metatrader 4 Ordersend Error 4051

Corrupt obtain or incomplete set up of Windows Operating System software program.

Corruption in Windows registry from a new Windows Operating System-related application adjust (install or uninstall).

Virus or malware infection which has corrupted Windows method documents or Windows Operating System-related application data files.

Another method maliciously or mistakenly deleted Windows Operating System-related files.

Mistakes this sort of as “Metatrader 4 Ordersend Error 4051” can be brought about by several different elements, so it really is important that you troubleshoot every of the achievable brings about to forestall it from recurring.

Simply click the beginning button.
Variety “command” inside the lookup box… Will not hit ENTER nonetheless!
Although keeping CTRL-Shift in your keyboard, hit ENTER.
You’re going to be prompted that has a authorization dialog box.
Click on Of course.
A black box will open having a blinking cursor.
Variety “regedit” and hit ENTER.
Within the Registry Editor, choose the invalid lots amount for ordersend function connected key (eg. Windows Operating System) you wish to back again up.
Within the File menu, choose Export.
Inside the Preserve In list, pick out the folder in which you wish to save the Windows Operating System backup key.
Inside the File Title box, sort a reputation for the backup file, these types of as “Windows Operating System Backup”.
From the Export Vary box, ensure that “Selected branch” is selected.
Click on Help you save.
The file is then saved by using a .reg file extension.
You now use a backup within your mql4 ordersend error 4051 related registry entry.

Solution to your order send error 4051 problem

There are actually some manual registry editing measures that can not be talked about in this article due to the high chance involved for your laptop or computer method. If you want to understand more then check out the links below.

Additional Measures:

One. Conduct a Thorough Malware Scan

There’s a probability the 4 Metatrader Error Ordersend 4051 error is relevant to some variety of walware infection. These infections are malicious and ready to corrupt or damage and possibly even delete your ActiveX Control Error files. Also, it’s attainable that your Metatrader 4 Ordersend Error 4051 is actually connected to some element of that malicious plan itself.

2. Clean Disk Cleanup

The a lot more you employ your computer the extra it accumulates junk files. This comes from surfing, downloading packages, and any sort of usual computer system use. When you don’t clean the junk out occasionally and keep your program clean, it could turn into clogged and respond slowly. That is when you can encounter an 4 error because of possible conflicts or from overloading your hard drive.

Once you clean up these types of files using Disk Cleanup it could not just remedy Metatrader 4 Ordersend Error 4051, but could also create a dramatic change in the computer’s efficiency.

Tip: While ‘Disk Cleanup’ is definitely an excellent built-in tool, it even now will not completely clean up Error 4051 discovered on your PC. There are numerous programs like Chrome, Firefox, Microsoft Office and more, that cannot be cleaned with ‘Disk Cleanup’.

Since the Disk Cleanup on Windows has its shortcomings it is extremely encouraged that you use a specialized sort of challenging drive cleanup and privacy safety application like CCleaner. This system can clean up your full pc. If you run this plan after each day (it could be set up to run instantly) you are able to be assured that your Pc is generally clean, often operating speedy, and always absolutely free of any Metatrader error associated with your temporary files.

How Disk Cleanup can help

1. Click your ‘Start’ Button.
2. Style ‘Command’ into your search box. (no ‘enter’ yet)
3. When holding down in your ‘CTRL-SHIFT’ important go ahead and hit ‘Enter’.
4. You will see a ‘permission dialogue’ box.
5. Click ‘Yes’
6. You will see a black box open up plus a blinking cursor.
7. Variety in ‘cleanmgr’. Hit ‘Enter’.
8. Now Disk Cleanup will start calculating the amount of occupied disk space you will be able to reclaim.
9. Now a ‘Disk Cleanup dialogue box’ seems. There will be a series of checkboxes for you personally to pick. Generally it will likely be the ‘Temporary Files’ that consider up the vast majority of your disk area.
10. Verify the boxes that you want cleaned. Click ‘OK’.

How to repair

3. System Restore can also be a worthwhile device if you ever get stuck and just desire to get back to a time when your computer system was working ideal. It will work without affecting your pics, paperwork, or other crucial information. You can discover this option with your User interface.

Error 4051

Manufacturer

Device

Operating System


Metatrader 4 Ordersend Error 4051


4.5 out of
5

based on
48 ratings.

 

Я забил код в скрипт, и нормально открывает по рынку, без ошибок…

Кстати, это условие:

if (SellTicket==0)

{

}

Если это скрипт, то условие совершенно бесполезное, так как ограничивать количество ордеров в скрипте не имеющем циклов, без смысленно.

Но если этот код из експерта, то так вы тоже не ограничите количество ордеров, так как переменная int SellTicket; инициализируется(обнуляется) в функции int start(){} на каждом тике.

Нужно вынести int SellTicket; за пределы Старта, то- есть вверх!

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

Мэкс, спасибо за комментарии. Я внёс некоторые изменения. Сразу уточню — это часть советника. Но, ошибка 130 может возникать только в строке где OrderSend.

Почему-то в 4-хзнаке всё работает, а в пятизнаке — выдаёт по-прежнему ошибку 130.

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

Заранее благодарен, если подскажите.

//+——————————————————————+

//| ccc.mq4 |

//| Copyright © 2011, MetaQuotes Software Corp. |

//| http://www.metaquotes.net |

//+——————————————————————+

#property copyright «VAGEYEV»

#include <stdlib.mqh>

//+——————————————————————+

//| expert initialization function |

//+——————————————————————+

int UseSlippage;

double UsePoint;

extern int Slippage = 5;

extern double StopLoss = 30;

extern double T_P=300;

extern int MagicNumber = 0;

int init()

{

//—-

UsePoint = PipPoint(Symbol());

UseSlippage = GetSlippage(Symbol(),Slippage);

//—-

return(0);

}

//+——————————————————————+

//| expert deinitialization function |

//+——————————————————————+

int deinit()

{

//—-

//—-

return(0);

}

//+——————————————————————+

//| expert start function |

//+——————————————————————+

int start()

{

//—-

double LotSize = 0.01;

// Open buy order

while(IsTradeContextBusy()) Sleep(10);

RefreshRates();

// Calculate stop loss and take profit

double OpenPrice = Ask;

double StopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL) * Point;

double UpperStopLevel = Ask + StopLevel;

double LowerStopLevel = Bid — StopLevel;

double MinStop = 5 * UsePoint;

// Calculate stop loss and take profit

if(StopLoss > 0) double BuyStopLoss = OpenPrice — (StopLoss * UsePoint);

if(T_P > 0) double BuyTakeProfit = OpenPrice + (T_P * UsePoint);

//Verify stop loss and take profit

if(BuyStopLoss > 0 && BuyStopLoss > LowerStopLevel)

{

BuyStopLoss = LowerStopLevel — MinStop;

}

if(BuyTakeProfit > 0 && BuyTakeProfit < UpperStopLevel)

{

BuyTakeProfit = UpperStopLevel + MinStop;

}

int BuyTicket = OrderSend(Symbol(),OP_BUY,3*LotSize,OpenPrice,UseSlippage,BuyStopLoss,BuyTakeProfit,»Buy Order»,MagicNumber,0,Green);

if (BuyTicket==-1)

{

int ErrorCode = GetLastError();

string ErrDesc = ErrorDescription(ErrorCode);

Print(ErrorCode,» «,ErrDesc);

string ErrAlert = StringConcatenate(ErrorCode,»: «,ErrDesc);

Alert(ErrAlert);

}

//—-

return(0);

}

// Get Slippage Function

int GetSlippage(string Currency, int SlippagePips)

{

int CalcDigits = MarketInfo(Currency,MODE_DIGITS);

if(CalcDigits == 2 || CalcDigits == 4) double CalcSlippage = SlippagePips;

else if(CalcDigits == 3 || CalcDigits == 5) CalcSlippage = SlippagePips * 10;

return(CalcSlippage);

}

// Pip Point Function

double PipPoint(string Currency)

{

int CalcDigits = MarketInfo(Currency,MODE_DIGITS);

if(CalcDigits == 2 || CalcDigits == 3) double CalcPoint = 0.01;

else if(CalcDigits == 4 || CalcDigits == 5) CalcPoint = 0.0001;

return(CalcPoint);

}

//+——————————————————————+

Всем привет.

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

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

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

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

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

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

Содержание

  1. MT4 Error 4051: How to Fix Invalid Trading Lot Amount
  2. What is MT4 error 4051?
  3. Why does MT4 error 4051 happen?
  4. You are exceeding your trading limit
  5. Your EA is generating inappropriate order parameters
  6. How to fix MT4 error 4051?
  7. Ошибка 4051
  8. Функция OrderClose — Error 4051
  9. Error 4051 occurred deleting an object
  10. Error Code 4051 Incorrect Params only on Sell Orders

MT4 Error 4051: How to Fix Invalid Trading Lot Amount

What is MT4 error 4051?

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

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

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

Why does MT4 error 4051 happen?

You are exceeding your trading limit

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

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

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

Your EA is generating inappropriate order parameters

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

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

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

How to fix MT4 error 4051?

How to fix OrderSend error for invalid lot amount

    Use NormalizeDouble in your code

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

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

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


Make sure normalized figures are rounded

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


Broker trading limitations for lot size

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

Источник

В истории есть закрытые ордера.

Выбирать ордер нужно в цикле (в общем случае)
Например так (МТ4) —

Дело не в том, какой цикл использовать (можно хоть for, хоть while), а в том, как он построен. В коде, который Вы привели, цикла нет вообще, выбирается ордер, которого заведомо нет в списке. Проверки успешности выбора ордера тоже нет.

Параметры в функции OrderSend вообще очень странные.

Дело не в том, какой цикл использовать (можно хоть for, хоть while), а в том, как он построен. В коде, который Вы привели, цикла нет вообще, выбирается ордер, которого заведомо нет в списке. Проверки успешности выбора ордера тоже нет.

Параметры в функции OrderSend вообще очень странные.

Не нужно рассчитывать на историю счета. В МТ4 пользователь может изменить глубину отображения истории, чем собьет с толку любой алгоритм, ориентирующийся на нее. Лучше отслеживать наличие ордеров, открытых советником, в списке рабочих ордеров. И только тогда, когда ордер исчез из этого списка (был закрыт), открывать следующий ордер.

Не нужно рассчитывать на историю счета. В МТ4 пользователь может изменить глубину отображения истории, чем собьет с толку любой алгоритм, ориентирующийся на нее. Лучше отслеживать наличие ордеров, открытых советником, в списке рабочих ордеров. И только тогда, когда ордер исчез из этого списка (был закрыт), открывать следующий ордер.

Эксперт работает не с одним ордером? Тогда все усложняется. При открытии каждого ордера нужно запомнить его тикет в собственном массиве. А потом на каждом тике проверять, существует ли этот ордер.

При открытии ордера:

Затем для проверки существования ордера:

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

Эксперт работает не с одним ордером? Тогда все усложняется. При открытии каждого ордера нужно запомнить его тикет в собственном массиве. А потом на каждом тике проверять, существует ли этот ордер.

При открытии ордера:

Затем для проверки существования ордера:

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

Это всего лишь пример кода. Писалось даже без проверки синтаксиса. Смысл — показать направление. Поэтому могут быть какие-то мелкие ошибки.

Это всего лишь пример кода. Писалось даже без проверки синтаксиса. Смысл — показать направление. Поэтому могут быть какие-то мелкие ошибки.

Источник

Функция OrderClose — Error 4051

Решил начать программировать на mql. Написал советник , проверяя как открываются и закрываются ордера. Открывается ордер при соответствующих условиях нормально, а при закррытии появляется Error 4051 — Invalid ticket to OrderClose Function. Помогите пожалуйста разобраться, что я делаю не так. Код советника ниже.

double MA;
MA=iMA(NULL,0,MA_Period,0,MODE_SMA,0,0);
int T;
T=OrdersTotal();
int ticket;
bool a;

После открытия позиции тикет у Вас не сохраняется. И при следующем запуске start переменная ticket инициализируется нулём. Нужно объявить ею как статическую или глобальную чтобы её значение сохранялось. Также полезно контролировать выполнение функции OrderSelect , например:

Что я не так зделал, подскажите плиз

выбираю ордер, узнаю тип, узнаю тиккет, пытаюсь удалить отложенный ордер — выдаёт ошибка 4051

Недопустимое значение параметра функции

if (a2>1)
OrderDelete(ticket2);
Alert (GetLastError()); // Сообщение об ошибке 4051

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

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

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

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

Источник

Error 4051 occurred deleting an object

I use a routine to create an entire table as a summary of all my active trades and each object has a name created by using its x and y positions.

The table maybe 10 columns by 10 lines — i.e. 100 objects created in the same routine — but all very similar

I noticed the following error 4051 and created some additional ‘FileWrite’ statements to try and track the error.

It is only COD330_130 that appears to generate this problem.

The next line would be — say — COD345_130 and no problem

There don’t appear to be any other problems and the EA continues to work

The ‘FileWrite’ generated the following

1 ObjName = COD330_130, Object_label = EURCHF colour = clrMidnightBlue xd = 330 yd = 130, 4051 invalid function parameter value

Any ideas appreciated.

[. ] Any ideas appreciated.

Are you sure that the error 4051 is generated during the code which you have posted, rather than before it?

It seems far more likely that the sequence of events, and the issue, is as follows:

  • Block of code earlier to that which you have posted, which does something leading to error 4051
  • Then the code which you have posted, which doesn’t generate an error
  • Checking GetLastError() then gives you the earlier error, which happened before the block of code which you are querying here.

Источник

Error Code 4051 Incorrect Params only on Sell Orders

This is my first posting on this forum, so please excuse any formatting/procedural errors. I am having difficulty with the Order Modify function. I use an ECN, so I must send the order with 0’s in the SL and TP fields and then use the Order Modify function.

The stop loss and take profit values are inserted perfectly with the buy order code, but fail when a sell order is input, resulting in the 4051 error code. This refers to invalid parameters on the take profit field, but I am using the same approach (not the calcs) on my buy order.

There is obviously something pretty basic that I am missing. I would really appreciate some help/insight on the extent of my error.

Thanks very much

  1. Always check your return codes. What are Function return values ? How do I use them ? — MQL4 forum
  2. What is the value of OpenPrice ?

RaptorUK :
Open price for a Buy is Ask, for a Sell it is Bid, how far has price moved between placing your Buy and your Sell ? Don’t use OpenPrice use Ask if you must or use OrderOpenPrice(). Why don’t you print OpenPrice when your OrdrModify() fails ? why don’t you Print Ask, Bid, etc ? don’t you think they are relevant to finding thee cause of your issue ?

I always print values to my journal, but the answer was not obvious until I read the thread on function return values and trapped them. Result was a mod to my code that corrected the problem.

Not sure about your reference to using Ask and Bid. My Order Send uses Ask and Bid as you suggest, and OrderOpenPrice() was used to set the TP and SL. Anyway, the mod to my code was successful.

Thank you both for your time.

This is my first posting on this forum, so please excuse any formatting/procedural errors. I am having difficulty with the Order Modify function. I use an ECN, so I must send the order with 0’s in the SL and TP fields and then use the Order Modify function.

The stop loss and take profit values are inserted perfectly with the buy order code, but fail when a sell order is input, resulting in the 4051 error code. This refers to invalid parameters on the take profit field, but I am using the same approach (not the calcs) on my buy order.

There is obviously something pretty basic that I am missing. I would really appreciate some help/insight on the extent of my error.

Thanks very much

For anyone reading this thread, here is the change I made to make the Stop Loss and Take Profit modification. My problem was based on the value of 0 being returned as the Ticket No. Code replaced in pink and code deleted in yellow .

Источник

What is MT4 error 4051?

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

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

MT4 Error 4051

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

Why does MT4 error 4051 happen?

You are exceeding your trading limit

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

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

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

Your EA is generating inappropriate order parameters

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

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

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

How to fix MT4 error 4051?

How to fix OrderSend error for invalid lot amount

  1. Use NormalizeDouble in your code

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

    MT4 NormalizeDouble function

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

  2. Adjust the value of NormalizeDouble

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

    MT4 Doubletostring

  3. Make sure normalized figures are rounded

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

    MT4 Normalized Values

  4. Broker trading limitations for lot size

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

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

Интересное по теме:

  • Ошибка 4051 codesys
  • Ошибка 404 размер страницы
  • Ошибка 404 пфр
  • Ошибка 404 примеры страниц
  • Ошибка 4051 audi

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

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