Axioss писал(а) >>
То, что это неправильные стопы, я знаю. Я пробывал и нормализовывать цену, и RefreshRates есть, так на Buy то все нормально, а на Sell — ошибка 130 и все тут, хотя мой SL очень далек от StopLevel
Как уже написали — TP забыт
Ticket=OrderSend(Symb,OP_SELL,Lots,Bid,3,SL, TP, Green); //открытие Sell
Но видимо проблема не в этом?
Я сделал так
sl1 = NormalizeDouble(Bid + MLockSL * Point,Digits); if (MLockSL <= 0) sl1 = NormalizeDouble(0,Digits); tp1 = NormalizeDouble(Bid - MLockTP * Point,Digits); if (MLockTP <= 0) tp1 = NormalizeDouble(0,Digits); Balancelots = NormalizeDouble(Balancelots,Digits); Comment ("155: Balancelots=",Balancelots); Alert ("155: Пытаюсь залочить buy! Balancelots=",Balancelots," SL1=",sl1," TP1=",tp1); LockTicketB=OrderSend(Symbol(),OP_SELL,Balancelots,Bid,Slippage,sl1,tp1,"225:залочили buy",362,0,Magenta); // лочим buy
if(LockTicketB<0) { LockBuy =0; Print("165: Не смог залочить buy ",ErrorDescription(GetLastError())); Alert ("165: Не смог залочить buy! Balancelots=",Balancelots," SL1=",sl1," TP1=",tp1,"Bid=",Bid); } else Alert ("166: Залочил buy! Balancelots=",Balancelots," SL1=",sl1," TP1=",tp1,"Bid=",Bid);
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 | Ошибка при работе с объектом |
You should know that there exists a minimum Stop Loss Size (mSLS) given in pips. «mSLS» changes with the currency and broker. So, you need to put in the OnInit() procedure of your EA a variable to get it:
int mSLS = MarketInfo(symbol,MODE_STOPLEVEL);
The distance (in pips) from your Order Open Price (OOP) and the Stop-Loss Price (SLP) can not be smaller than mSLS value.
I will try to explain a general algorithm I use for opening orders in my EAs, and then apply the constrain on Stop-Loss level (at step 3):
Step 1. I introduce a flag (f) for the type of operation I will open, being:
f = 1 for Buy, and
f = -1 for Sell
You know that there are mql4 constants OP_SELL=1 and OP_BUY=0 (https://docs.mql4.com/constants/tradingconstants/orderproperties).
Once I have defined f, I set my operation type variable to
int OP_TYPE = int(0.5((1+f)*OP_BUY+(1-f)*OP_SELL));
that takes value OP_TYPE=OP_BUY when f=1, while OP_TYPE=OP_SELL when f=-1.
NOTE: Regarding the color of the orders I put them in an array
color COL[2]= {clrBlue,clrRed};
then, having OP_TYPE, I set
color COLOR=COL[OP_TYPE];
Step 2. Similarly, I set the Order Open Price as
double OOP = int(0.5*((1+f)*Ask+(1-f)*Bid));
which takes value OOP=Ask when f=1, while OOP=Bid when f=-1.
Step 3. Then, given my desired Stop Loss in pips (an external POSITIVE parameter of my EA, I named sl) I make sure that sl > SLS. In other words, I check
if (sl <= mSLS) // I set my sl as the minimum allowed
{
sl = 1 + mSLS;
}
Step 4. Then I calculate the Stop-Loss Price of the order as
double SLP = OOP - f * sl * Point;
Step 5. Given my desired Take Profit in pips (an external POSITIVE parameter of my EA, I named tp) I calculate the Take-Profit Price (TPP) of the order as
double TPP = OOP + f * tp * Point;
OBSERVATION: I can not affirm, but, according to mql4 documentation, the minimum distance rule between the stop-loss limit prices and the open price also applies to the take profit limit price. In this case, a «tp» check-up needs to be done, similar to that of the sl check-up, above. that is, before calculating TPP it must be executed the control lines below
if (tp <= mSLS) // I set my tp as the minimum allowed
{
tp = 1 + mSLS;
}
Step 5. I call for order opening with a given lot size (ls) and slippage (slip) on the operating currency pair (from where I get the Ask and Bid values)
float ls = 0.01;
int slip = 3; //(pips)
int order = OrderSend(Symbol(),OP_TYPE,ls,OOP,slip,SLP,TPP,"",0,0,COLOR);
Note that with these few lines it is easy to build a function that opens orders of any type under your command, in any currency pair you are operating, without receiving error message 130, passing to the function only 3 parameters: f, sl and tp.
It is worth including in the test phase of your EA a warning when the sl is corrected for being less than the allowed, this will allow you to increase its value so that it does not violate the stop-loss minimum value rule, while you have more control about the risk of its operations. Remember that the «sl» parameter defines how much you will lose if the order fails because the asset price ended up varying too much in the opposite direction to what was expected.
I hope I could help!
The expert advisors that work on one broker can stop working on another; the problem with them often lies in the OrderSend Error 130. If you see Error 130 in the log of the Experts or Journal tabs in your MetaTrader platform when your expert advisor should be opening a position, then that means that the stop-loss or take-profit levels are set too close to the current market price. In the MQL4 documentation, this error is called ERR_INVALID_STOPS
(Invalid stops). Some Forex brokers set the minimum distance between the current price and the stop-loss/take-profit levels to prevent scalping or abusing the quote delays. That isn’t a real problem for the majority of expert advisors that aren’t used for scalping. To prevent this error from occurring, you need to change the expert advisor’s code.
First, you might want to know what the minimum stop level is set in your broker’s MetaTrader server. Adding this line of code will output the current minimum stop level for the currency pair of the chart where you run the EA:
One thing you should be wary of is that a stop level value of zero doesn’t mean that your broker doesn’t set any minimum stop distance. It could also mean that the broker uses some external system for dynamic management of their stop level. In this case, it may be variable and undetectable via MQL4.
Market orders
When opening a market order, you won’t be able to set a stop-loss or take-profit level that is closer than MarketInfo(Symbol(), MODE_STOPLEVEL)
to the current price.
MQL4 solution to OrderSend Error 130 with market orders
If your EA calculates stops and take-profits dynamically, below is the solution to prevent OrderSend Error 130 from occurring.
Declare a global variable for the minimum stop level; e.g.:
In the OnInit()
function (or init()
in older versions of MT4) of your expert advisor, define the minimum stop level:
Next time your stop-loss or take-profit in points is calculated, just make sure that they aren’t less than StopLevel
:
if (SL < StopLevel) SL = StopLevel; if (TP < StopLevel) TP = StopLevel;
To check with actual stop-loss and take-profit price levels, a difference between them and the current Bid price for Buy orders or a difference between them and the current Ask price for Sell orders should be checked.
For Buy orders:
if (Bid - StopLoss < StopLevel * _Point) StopLoss = Bid - StopLevel * _Point; if (TakeProfit - Bid < StopLevel * _Point) TakeProfit = Bid + StopLevel * _Point;
For Sell orders:
if (StopLoss - Ask < StopLevel * _Point) StopLoss = Ask + StopLevel * _Point; if (Ask - TakeProfit < StopLevel * _Point) TakeProfit = Ask - StopLevel * _Point;
Don’t forget to refresh the current market rates with a call to the RefreshRates()
function before adding the SL/TP distance to the current market rates or before comparing calculated stop-loss and take-profit levels to the current market rates.
Pending orders
For pending orders (stop or limit), MetaTrader 4 offers the following restrictions in regards to stop level:
Buy Limit — the distances between the current Ask and the Entry, between the Entry and the Stop-Loss, and between the Entry and Take-Profit should all be greater or equal to the stop level.
Sell Limit — the distances between the current Bid and the Entry, between the Entry and the Stop-Loss, and between the Entry and Take-Profit should all be greater or equal to the stop level.
Buy Stop — the distances between the current Ask and the Entry, between the Entry and the Stop-Loss, and between the Entry and Take-Profit should all be greater or equal to the stop level. Actually, the conditions are the same conditions as for the Buy Limit order, but the Entry level is located above the current Ask in Buy Stop.
Sell Stop — the distances between the current Bid and the Entry, between the Entry and the Stop-Loss, and between the Entry and Take-Profit should all be greater or equal to the stop level. Actually, the conditions are the same conditions as for the Sell Limit order, but the Entry level is located below the current Bid in Sell Stop.
MQL4 solution to OrderSend Error 130 with pending orders
Here are examples of MQL4 code checks to make sure your Entry, Stop-Loss, and Take-Profit levels for MT4 pending orders comply with the broker’s stop level restriction.
For Buy Limit orders:
if (Ask - Entry < StopLevel * _Point) Entry = Ask - StopLevel * _Point; if (Entry - StopLoss < StopLevel * _Point) StopLoss = Entry - StopLevel * _Point; if (TakeProfit - Entry < StopLevel * _Point) TakeProfit = Entry + StopLevel * _Point;
For Sell Limit orders:
if (Entry - Bid < StopLevel * _Point) Entry = Bid + StopLevel * _Point; if (StopLoss - Entry < StopLevel * _Point) StopLoss = Entry + StopLevel * _Point; if (Entry - TakeProfit < StopLevel * _Point) TakeProfit = Entry - StopLevel * _Point;
For Buy Stop orders:
if (Entry - Ask < StopLevel * _Point) Entry = Ask + StopLevel * _Point; if (Entry - StopLoss < StopLevel * _Point) StopLoss = Entry - StopLevel * _Point; if (TakeProfit - Entry < StopLevel * _Point) TakeProfit = Entry + StopLevel * _Point;
For Sell Stop orders:
if (Bid - Entry < StopLevel * _Point) Entry = Bid - StopLevel * _Point; if (StopLoss - Entry < StopLevel * _Point) StopLoss = Entry + StopLevel * _Point; if (Entry - TakeProfit < StopLevel * _Point) TakeProfit = Entry - StopLevel * _Point;
Summary
This should help in the majority of cases when you see OrderSend Error 130 in your MetaTrader 4 Experts tab.
You discuss your personal struggles with OrderSend Error 130 problem on our forum if you are having trouble solving this issue on your own.
By popular demand, proven strategies on how to beat every algorithmic trader’s worst nightmare – Error 130
The OrderSend Error 130 appears in MetaTrader 4 when an Expert Advisor can’t execute a marker order as expected. Also known as the Invalid Stop (ERR_INVALID_STOPS) in MQL jargon, the Error 130 happens when the TakeProfit and StopLoss levels are set to close to the current market price.
Where does this error come from? What does it mean for your Expert Advisor? How can you find the part of your code that is causing the error? We tackle all this and more…
Video Tutorial
Alright! Let’s go ahead and send some orders with OrderSend. The video below is available if you prefer watching instead of reading
To start off, a formal definition from our friend, MQL4 Documentation:
That’s right! That is all you get from MetaQuotes. And the rest… Go figure!
Ordersend Error 130 is briefly mentioned in other sections of the documentation. However, there is no thorough guide to what “Invalid Stops” actually means and how to deal with this, perhaps, most common problem in Forex programming.
But not a worry! That’s why I have written this article. Let’s get through this together!
The silent killer
So… you launched your expert advisor and… nothing happens. No BUY orders, no SELL orders, no pending orders, not even error messages in the logs…. Just silence. You decide to wait a few hours / days / weeks, and nothing really changes – the charts go up and down, but you don’t see any profit. This can go on forever…
The real reason is simple – you’re actually getting ERR_INVALID_STOPS (which is the correct technical term for the issue), but you can’t see it. That’s because 130 is a silent killer. A cold-blooded murderer of your brain and inner calm 🙂
There is no way to pick up this error through expert advisor logs or even terminal logs. The only way to catch it is by adding the right failsafe mechanisms into your code. Here’s an example you can adapt to your code:
int ticket;
ticket = OrderSend("EURUSD", OP_BUY, 1.0, Ask, 10, StopLossLevel, TakeProfitLevel, "My 1st Order!");
if(ticket < 0)
{
Alert(“OrderSend Error: “, GetLastError());
}
else
{
Alert(“Order Sent Successfully, Ticket # is: ” + string(ticket));
}
What we are doing here is taking the ticket number and that OrderSend() returns and checking if it is less than zero. If yes, then that is a signal from MetaTrader 4 telling us that there was a problem with the request.
The error code is then printed out onto the screen using Alert() and the built-in GetLastError() function. This code will give a pop-up window like in the image up at the top of this article.
Note: you can use Print() instead of Alert() to redirect the message straight to the EA’s log instead of displaying it on the screen.
Core of Ordersend Error 130
Invalid stops is the real name for the culprit we are dealing with today. So what does invalid stops in MetaTrader 4 actually mean?
- For a market order (BUY or SELL) invalid stops means that the StopLoss and/or TakeProfit you requested were not possible to set for your order. Therefore, since a request cannot be fulfilled only partially, the order was not executed at all
- For a pending order (BUY STOP, BUY LIMIT, SELL STOP, or SELL LIMIT) invalid stops means that either (1) there were issues with the SL/TP (same as above) OR (2) the issue was with the entry price which you specified for the order itself
As we can see, the issue is always with one (or many) of the prices that your Forex Robot specified in its request to the trade server. Now that we know our enemy – let’s beat it!
1) StopLoss & TakeProfit are prices
There are several possible causes of ERR_INVALID_STOPS, and one of the more frequent ones among beginners is specifying the StopLoss and TakeProfit in pips rather than actual price levels. Like this:
OrderSend(EURUSD, OP_BUY, 0.1, 1.1606, 10, 20, 40);
This person tried to set a StopLoss of 20 pips and a TakeProfit of 40 pips. Big NO-NO….. The correct and only way of specifying your SL and TP is through price levels:
OrderSend(EURUSD, OP_BUY, 0.1, 1.1606, 10, 1.1585, 1.1645);
By the way, here we assumed that the current ASK price is 1.1606 and current BID price is 1.1605 (i.e. 1 pip spread).
2) 4-digits vs 5-digits
Another reason you could be getting ERR_INVALID_STOPS is if you are setting the input parameters of your EA in Pips (4-digit points) when the Robot is anticipating 5-digit points. Let’s look at an example:
extern int StopLoss = 20;
extern int TakeProfit = 40;
//…
OrderSend(EURUSD, OP_BUY, 0.1, Ask, 10, Bid-StopLoss*Point(), Bid+TakeProfit*Point());
This code will work fine on a 4-digit broker, however will fail on a 5-digit broker. The reason is that on a 4-digit broker, Point() equals to 0.0001, whereas on a 5-digit broker Point() equals to 0.00001.
Basically, with no additional adjustments, on a 5-digit broker the EA will be attempting to set the StopLoss and TakeProfit at only 2 and 4 pips away from the Bid price respectively!
That’s why in the case of a 5-digit broker you have to increase your StopLoss and TakeProfit parameters tenfold. Like this:
extern int StopLoss = 200;
extern int TakeProfit = 400;
//…
OrderSend(EURUSD, OP_BUY, 0.1, Ask, 10, Bid-StopLoss*Point(), Bid+TakeProfit*Point());
However, be careful! Some EA’s already have modules that will detect the number of digits after the decimal and will automatically adjust your input parameters for you. In these situations multiplying inputs by 10 can actually lead to erroneous performance.
Note: I plan on posting a separate article where we will discuss how to create our own modules to detect the number of digits after the decimal
3) ECN brokers
ECN accounts have their own specifics. One of them is – when trading through a ECN broker you will not be able to set a StopLoss and/or TakeProfit with your Market Order (BUY or SELL). If you try to do this – you will get Error 130.
However, of course, you do need to set a StopLoss (and maybe TakeProfit) for your order, and this must be done as soon as possible after the order has been executed. Try this code:
int MarketOrderSend(string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment, int magic)
{
int ticket;
ticket = OrderSend(symbol, cmd, volume, price, slippage, 0, 0, NULL, magic);
if(ticket <= 0) Alert(“OrderSend Error: “, GetLastError());
else
{
bool res = OrderModify(ticket, 0, stoploss, takeprofit, 0);
if(!res) { Alert(“OrderModify Error: “, GetLastError());
Alert(“IMPORTANT: ORDER #”, ticket, ” HAS NO STOPLOSS AND TAKEPROFIT”);}
}
return(ticket);
}
You can add this function to your code (at the very end) and then use it instead of OrderSend() in your main code. This function adds an extra step in the process of sending a Market Order.
First, it send the request to execute a market order stripping out the StopLoss and TakeProfit. Next, it modifies the newly opened market order by adding the desired SL and TP.
There is, of course, a risk that the order will be executed, but the modification will fail. However, in that case the function will promptly notify the trader that the StopLoss and TakeProfit have not been set.
Feel free to modify this function to suit your needs and trading style.
4) Stop-Levels
Stop-Levels are a mechanism for brokers to protect themselves from certain volatility and liquidity related risks. In simple terms, you will not be able to set your StopLoss or TakeProfit OR any pending order closer than a predetermined number of Pips to the current market price.
To find out what the Stop Level is for a specific currency pair you need to press CTRL+U on your keyboard, select the desired currency pair and click the “Properties” button as shown on the illustration below:
In this example the Stop Level for AUDUSD is 3 Pips. This means that you will not be able to set the StopLoss for your order closer than 3 Pips to the price at which the order will be opened.
This also means that any pending order will have to be set at least 3 Pips away from the current market price.
If you Robot tries to break these rules and set a StopLoss / TakeProfit or Pending Order within the Stop Level range, then it will get Error 130 “Invalid Stops”. So just be mindful of the Stop Level of the currency where your EA’s are trading – don’t specify excessively small StopLoss and TakeProfit parameters.
It is also worth noting that more exotic currency pairs can have much more significant Stop Levels. Fore example, for AUDNZD the Stop Level with the same broker as in the above example is 20 Pips. For GBPSEK (British Pound vs Swedish Krone) – it’s 100 Pips.
5) Normalization of doubles
With some brokers you will find that for an unknown reason the Ask and Bid prices are passed onto the trader with additional negligible digits after the decimal. For example:
Instead of 1.1606 the broker would give you 1.160600001
Now this phenomenon has no effect on manual trading, moreover since the MT4 terminal is hardwired to display a certain number of digits after the decimal point (either 4 or 5) – you will not be able to notice any difference at all!
However, these ‘negligible’ digits after the decimal can have a dramatic effect on Expert Advisors causing……… that’s right! Our old friend, OrderSend Error 130!
Here’s a strategy that I personally use to protect my Robots from this issue:
void OnTick()
{
//...
OrderSend(EURUSD, OP_BUY, 0.1, ND(Ask), 10, ND(Bid-StopLoss*Point()), ND(Bid+TakeProfit*Point()));
}
double ND(double val)
{
return(NormalizeDouble(val, Digits));
}
This neat little trick allows you to normalize (in simple terms – Round) any prices that you are inputting into the OrderSend() function. This way you cut off all ‘negligible’ digits after the decimal point.
Conclusion
Today we saw that there may be multiple (at least 5) causes to error 130. Though this is quite a few, the underlying issues are all trivial and can be corrected in a matter of minutes.
Therefore, Error 130 should not be feared! If you have encountered this culprit, it’s just a matter of going through the list above, finding the situation that applies to you and applying the prescribed solution.
Hope you found this article useful!
Let me know if you have any questions by using the comments section below.
Happy trading,
Kirill
P.S: if you liked what you read in this article, here you can find the full course:
What are you waiting for?