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);
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.
What is MT4 error 130?
The MT4 error 130 is an OrderSend error code of the MetaTrader 4 platform. A trading platform shows this error code when an Expert Advisor fails to execute an order according to expectations. This error is also known as invalid stops.
An OrderSend error can be very crucial for the day traders because their timing of market entry and exits are equally important. Also, such errors may damage your profit factors and heavily affect your risk to reward ratio.
In this article, we will discuss when an MT4 error 130 happens and how to fix this issue ensuring a smoother trading experience.
Why does MT4 error 130 happen?
An MT4 error 130 may occur for the following reasons:
Market orders
While opening a buy or sell order if you set the stop-loss and take profit levels closer to the market price, the MT4 platform will not accept the order. Instead, it will show your the error code 130.
For direct buy orders, if your stop-loss limit is greater than the asking price and the take profit level is lower than the bidding price, the MT4 will still show the OrderSend error code. On the other hand, for market sell orders, an error code 130 appears when the stop-loss level is lower than the bidding price and the take-profit level is higher than the asking price.
Pending orders
An error code130 may also appear during placing a buy limit and buy stop order. It happens when the difference between the asking and the entry price or the difference between the entry and take profit price is less than the stop-loss limit.
For sell limit and sell stop orders, the OrderSend error occurs if the difference between the bidding and entry price or the difference between the entry and take profit price is less than the stop-loss level.
How to fix Invalid Stops errors
Time needed: 3 minutes.
Solutions for MT4 error 130 differ depending on whether you are using an Expert Advisor or not:
- Check with your broker the minimum Stop Loss & Take Profit Limits
If you are not using an Expert Advisor then what you can do best is to follow the rules set by the broker for setting the stop loss and take profit levels. Generally, most brokers don’t allow setting SL and TP less than 10 pips. When you place an order with less than 10 pips of SL or TP, the MT4 automatically denies executing the order. So, check with your broker about the minimum SL and TP limit, and place the order accordingly. If you still face the problem then it might be caused by slippage or high spreads due to the high volatility of the market.
- Buy Stop (with Expert Advisor)
When you are using Expert Advisors and receiving MT4 error 130 for a Buy Stop order, you need to make a few edits to the EA code.
- Sell Stop (with Expert Advisor)
To fix MT4 error 130 on an EA for a Sell Stop order, you need to make the following adjustments:
- Buy Limit (with Expert Advisor)
For an Expert Advisor that returns MT4 error 130 when you are attempting to place a Buy Limit order:
- Sell Limit (with Expert Advisor)
On an Expert Advisor that returns MT4 error 130 when you try to place a Sell Limit order:
The above codes will help you to prevent showing MT4 error code 130 while placing pending orders only. For market orders (direct buy/sell), check with your broker about their requirements, rules, and limits of setting stop-loss and take profit.
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 | Ошибка при работе с объектом |
I’m trying to modify an order, but I keep Error modifying order!, error#130. I’m using an ECN broker, so I need to modify the order to set a stoploss/takeprofit.
What I am doing wrong?
int digits = MarketInfo( Symbol(), MODE_DIGITS );
if ( digits == 2 || digits == 3 ) pipdigits = 0.01;
else if ( digits == 4 || digits == 5 ) pipdigits = 0.0001;
selltakeprofit = Ask + ( takeprofit * pipdigits );
sellstoploss = Ask - ( stoploss * pipdigits );
ticket = OrderSend( Symbol(), OP_SELL, lotsize, Ask, 100, 0, 0, 0, 0, 0, CLR_NONE );
if ( ticket < 0 )
{
Print( "venda Order send failed with error #", GetLastError() );
Print( "stop loss = ", sellstoploss );
}
else
{
Print( "Order send sucesso!!" );
Print( "Balance = ", AccountBalance() );
Print( "Equity = ", AccountEquity() );
bool res = OrderModify( ticket, 0, sellstoploss, selltakeprofit, 0 );
if ( res == false )
{
Print( "Error modifying order!, error#", GetLastError() );
Print( "sellstoploss ", sellstoploss );
Print( "selltakeprofit ", selltakeprofit );
Print( "StopLevel ", StopLevel );
Print( "Ask ", Ask );
}
else
{
Print( "Order modified successfully" );
}
}
asked Dec 2, 2014 at 2:33
Filipe FerminianoFilipe Ferminiano
8,39325 gold badges104 silver badges175 bronze badges
Error #130 is ERR_INVALID_STOPS
.
The most likely problem is that
a) the stoploss level you are inputting is too close to the order open price. This is dictated by
MarketInfo( Symbol(), MODE_STOPLEVEL ) // returns a min allowed distance [pts]
else
b) because you have not normalized the stoploss level with NormalizeDouble()
.
See below for a buy order example. In your example, i.e. for a sell order, note that you should be opening the order at the Bid price, not Ask as you have. Note also that the stoploss and takeprofit are usually calculated relative to the bid price, as the bid is what is displayed on your charts, unfortunately you just have to take the spread loss in stride.
Only other minor problem is that you input no colour for the last parameter in OrderModify()
. Unlike in OrderSend()
, these are not initialized by default in the function definition, so you should pass them really.
//--- get minimum stop level
double minstoplevel = MarketInfo( Symbol(), MODE_STOPLEVEL );
Print( "Minimum Stop Level=", minstoplevel, " points" );
double price = Ask;
//--- calculated SL and TP prices must be normalized
double stoploss = NormalizeDouble( Bid - minstoplevel * Point, Digits );
double takeprofit = NormalizeDouble( Bid + minstoplevel * Point, Digits );
//--- place market order to buy 1 lot
int ticket = OrderSend( Symbol(), OP_BUY, 1, price, 3, stoploss, takeprofit, "My order", 16384, 0, clrGreen );
answered Dec 3, 2014 at 8:43
whitebloodcellwhitebloodcell
3081 gold badge4 silver badges10 bronze badges
1
OrderModify()
call may collide with not one, but two constraints
The first, being a trivial one — one cannot put SL/TP closer than your Broker allows via a MODE_STOPLEVEL
defined distance.
The second, being a less visible one — one cannot change { SL | TP } in case a Broker defined freezing distance is visited by a respective XTO price ( an eXecute-Trade-Operation price, being { Ask
for Short.SL & Short.TP | Bid
for Long.TP & Long.SL } )
MarketInfo( Symbol(), MODE_STOPLEVEL ) // returns a min allowed distance [pts]
MarketInfo( Symbol(), MODE_FREEZELEVEL ) // returns a freezing distance [pts]
OrderSend()
may be constrained on some ECN/STP account types
Another quite common condition set on STP/ECN systems ( introduced by the Broker’s inhouse Risk Management policy ) is that one is not allowed to setup TP/SL right at the OrderSend()
, but has to leave these blank and upon a positive confirmation of the OrderSend()
, submit a separate OrderModify()
instruction for the given OrderTicketNumber to add ex-post the TP and/or SL price-level(s)
A NormalizeDouble()
-whenever-possible practice is not separately commented here, as MetaQuotes Inc. publishes this as a must-do.
A recommended practice
Carefully review your Broker’s Terms & Conditions and consult with your Account Manager the complete mix of Broker-side policies that apply to your type of Trading Account.
answered Dec 13, 2014 at 18:55
When you execute a buy trade, your price is the Ask
, your stoploss and takeprofit are reference to the opposite trade, as when closing you’re subject to the Bid
price.
using this simple rule, when you buy your stoploss
and takeprofit
will be:
double stoploss = NormalizeDouble( Bid - minstoplevel * Point, Digits );
double takeprofit = NormalizeDouble( Bid + minstoplevel * Point, Digits );
int ticket = OrderSend( Symbol(),
OP_BUY,
lots,
price,
slippage,
stoploss,
takeprofit
);
the opposite, when you sell:
double stoploss = NormalizeDouble( Ask + minstoplevel * Point, Digits );
double takeprofit = NormalizeDouble( Ask - minstoplevel * Point, Digits );
int ticket = OrderSend( Symbol(),
OP_SELL,
lots,
price,
slippage,
stoploss,
takeprofit
);
answered Nov 25, 2016 at 11:58
RamzyRamzy
1812 silver badges14 bronze badges
Hello some ECN Brokers doesn’t allow send orders with SL and TP, So first send the Order without SL and TP , then Modify it and asign it SL and TP.
answered Jul 23, 2018 at 12:15
SimoSimo
112 bronze badges
Actually the real issue is that your new stop loss price although for buy side is bigger than current stop loss, you still have to check if your new stop loss is actually smaller than current Bid price. If not you will get that Order Modify 130 error. I hope I make sense. And the opposite applies for the Sell side.
answered Jun 29, 2020 at 3:57