Содержание
- MQL для тебя
- Вопрос №5 — «Коды ошибок при тестировании советника»
- Коды ошибок
- OrderModify и error 130 — моделирование по ценам открытия
- Модификация ордера ошибка 130
- OrderModify Error 130 on pending orders
- FreezeLevel Limitation (Freezing Distance).
- OrderModify sometimes returning ERROR 130
MQL для тебя
MQL для чайников, программирование на MQL4, MQL5
Вопрос №5 — «Коды ошибок при тестировании советника»
Что значит 2010.02.01 17:00 MyExpert GBPUSD,M15: OrderModify error 130
почему обычно эта ошибка возникает?
Очень много подобных вопросов мне приходит. Поэтому публикую таблицу кодов ошибок. Например посмотрев вышеописанную ошибку error 130 становится понятно, что функция OrderModify пытается изменить стоп-лосс или тейк-профит слишком близко к текущей цене.
Коды ошибок
GetLastError() — функция, возвращающая коды ошибок. Кодовые константы ошибок определены в файле stderror.mqh. Для вывода текстовых сообщений следует использовать функцию ErrorDescription(), определенную в файле stdlib.mqh.
Коды ошибок, возвращаемые торговым сервером или клиентским терминалом:
Значение | Описание |
---|---|
Нет ошибки | |
1 | Нет ошибки, но результат неизвестен |
2 | Общая ошибка |
3 | Неправильные параметры |
4 | Торговый сервер занят |
5 | Старая версия клиентского терминала |
6 | Нет связи с торговым сервером |
7 | Недостаточно прав |
8 | Слишком частые запросы |
9 | Недопустимая операция нарушающая функционирование сервера |
64 | Счет заблокирован |
65 | Неправильный номер счета |
128 | Истек срок ожидания совершения сделки |
129 | Неправильная цена |
130 | Неправильные стопы |
131 | Неправильный объем |
132 | Рынок закрыт |
133 | Торговля запрещена |
134 | Недостаточно денег для совершения операции |
135 | Цена изменилась |
136 | Нет цен |
137 | Брокер занят |
138 | Новые цены |
139 | Ордер заблокирован и уже обрабатывается |
140 | Разрешена только покупка |
141 | Слишком много запросов |
145 | Модификация запрещена, так как ордер слишком близок к рынку |
146 | Подсистема торговли занята |
147 | Использование даты истечения ордера запрещено брокером |
148 | Количество открытых и отложенных ордеров достигло предела, установленного брокером. |
Коды ошибок выполнения MQL4 программы:
Источник
OrderModify и error 130 — моделирование по ценам открытия
Позиция на покупку открывается по Аску, а закрывается по Биду. Поэтому прежде всего нужно знать, что при подтягивании стопа нужно работать с ценой бид.
Далее. Если, как Вы утверждаете, подтягивание происходит слишком близко к рынку, то сама логика ситуации подсказывает Вам решение — сначала проверить цену на предмет близости, потом подтягивать, если близость допустимая.
Позиция на покупку открывается по Аску, а закрывается по Биду. Поэтому прежде всего нужно знать, что при подтягивании стопа нужно работать с ценой бид.
Далее. Если, как Вы утверждаете, подтягивание происходит слишком близко к рынку, то сама логика ситуации подсказывает Вам решение — сначала проверить цену на предмет близости, потом подтягивать, если близость допустимая.
Это правильно, если тестировать по тикам (методы «все тики» или «контрольные точки»). А как быть, если тестирование осуществляется «по ценам открытия». Как я уже упомянул, 1,3508 — это цена открытия текущего бара.
Как здесь написано, произойдет сравнение, SL не подтянется, правильно. Теперь следующий запуск функции start() произойдет ЛИШЬ на цене открытия следующего бара (так как метод моделирования по ценам открытия). И SL не будет подтянут. А само тело текущего бара запросто может пробить уровень SL, который не был выставлен.
Источник
Модификация ордера ошибка 130
Всем привет! Советник работает хорошо, но бывает выскакивает ошибка 130 , а бывает не выставляет ТП, бывает очень редко, в основном на движухе и то не всегда. Но это очень напрягает. Вот кусок кода и модификация ордера. NumberOfTry=5 , то есть всего 5 попыток. Понимаю, что цена за это время пока он крутит эти 5 попыток цикле уходит дальше чем ТП+Проскальзывание и потому вылетает эта ошибка 130. Но как сделать, чтобы он открывал по цене какая есть? Хотя тоже понимаю, что цена может рвануть сильно и никакое проскальзывание не спасёт и будет невозможно выставить ТП даже по новой цене или это не так? В общем, помогите опытные товарищи, советом как поступить?!
Всем привет! Советник работает хорошо, но бывает выскакивает ошибка 130 , а бывает не выставляет ТП, бывает очень редко, в основном на движухе и то не всегда. Но это очень напрягает. Вот кусок кода и модификация ордера. NumberOfTry=5 , то есть всего 5 попыток. Понимаю, что цена за это время пока он крутит эти 5 попыток цикле уходит дальше чем ТП+Проскальзывание и потому вылетает эта ошибка 130. Но как сделать, чтобы он открывал по цене какая есть? Хотя тоже понимаю, что цена может рвануть сильно и никакое проскальзывание не спасёт и будет невозможно выставить ТП даже по новой цене или это не так? В общем, помогите опытные товарищи, советом как поступить?!
Добрый день.
замените Аsк на MarketInfo(_Symbol,MODE_ASK)
в большинстве случаев помогает.
а еще можно перенести расчет тейка в цикл перед отправкой запроса на модификацию, так будет лучше, расчет тейка будет происходить по текущим данным цены.
Andrey Kisselyov :
Добрый день.
замените Аsк на MarketInfo(_Symbol,MODE_ASK)
в большинстве случаев помогает.
а еще можно перенести расчет тейка в цикл перед отправкой запроса на модификацию, так будет лучше, расчет тейка будет происходить по текущим данным цены.
Спасибо буду пробовать. Вот что получилось))
Источник
OrderModify Error 130 on pending orders
I got the error «OrderModify error 130» but I do not why I got this error since I have all required check on take profit and stop loss before to call the function orderModify.
Below is my code:
I got the error «OrderModify error 130» but I do not why I got this error since I have all required check on take profit and stop loss before to call the function orderModify.
Below is my code:
int openOrder(int cmd, double volume,double priceDistance=0, double sl=0,double tp=0)
<
double marginFree = AccountFreeMargin(); // Allow some slack
double marginPerLot = MarketInfo( Symbol(), MODE_MARGINREQUIRED );
double stoplevel = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point; //minimum stop loss/ take profit level, in points or pending order
double freezelevel = MarketInfo(Symbol(),MODE_FREEZELEVEL)*Point;
//number of digit for min lot
double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
double minLot=MarketInfo(Symbol(),MODE_MINLOT);
int lotDigit=2;
if(minLot==0.1)
lotDigit=1;
else if(minLot==1)
lotDigit=0;
double size =volume;
size=NormalizeDouble(size,lotDigit);
string description;
size=MathMax(minLot,size);
size=MathMin(maxLot,size);
if(!CheckVolumeValue(size,description))
<
lastErrorMessage=»Volume is not correct»;
lastDateErrorMessage=TimeCurrent();
Print(«Error opening order for size «,size,» : «,description);
return -1;
>
if(sl>0 || tp>0)
<
//bool res=OrderModify(lastTicketNumber,OrderOpenPrice(),NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),0,White);
bool res=OrderModify(lastTicketNumber,NormalizeDouble(openPrice,Digits),NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),0,White);
if(!res)
<
lastErrorMessage=»#»+IntegerToString(GetLastError())+» can not modify order»;
lastDateErrorMessage=TimeCurrent();
Print(«Error #»,GetLastError(),» Cmd:»,cmd,» Order :»,OrderType(),» Price:»,OrderOpenPrice(),» SL:»,NormalizeDouble(sl,Digits),» TP:»,NormalizeDouble(tp,Digits));
Print(«Error initial price: «,NormalizeDouble(openPrice,Digits));
>
>
return lastTicketNumber;
>
else
<
error_code=GetLastError();
switch(error_code)
<
case ERR_TRADE_NOT_ALLOWED :
lastErrorMessage=»#»+IntegerToString(error_code)+» Trade is not allowed»;
break; //4109 Trade is not allowed.
case ERR_INVALID_STOPS:
lastErrorMessage=»#»+IntegerToString(error_code)+» Invalid stop»;
break; //130 invalid stop
default:
lastErrorMessage=»#»+IntegerToString(error_code)+» Error opening order»;
>
lastDateErrorMessage=TimeCurrent();
>
return 0;
>
FreezeLevel Limitation (Freezing Distance).
Market orders can not be closed if the StopLoss and TakeProfit values violate the FreezLevel parameter requirements.
StopLoss or TakeProfit orders can not be modified if StopLoss or TakeProfit values violate the StopLevel parameter requirements.
Pending orders can not be deleted or modified if the declared open price violates the FreezeLevel parameter requirements.
Источник
OrderModify sometimes returning ERROR 130
Please read some other posts before posting . . .
Please edit your post or your thread will be removed . . . please use the SRC button to post code: How to use the SRC button.
-
Play videoPlease edit your post.
For large amounts of code, attach it. - The == operand. — MQL4 forum
I cant use the operator != do this ?
I should use it?
I cant use the operator != do this ?
I should use it?
The code now is:
For me is the same problem yet.
You are modifying your order when it hits 100 Points profit
You are not checking to see if it has already been modified
Next tick, if profit remains at more than 100 Points, the program will try to modify the order again with the same values.
This will return the error.
You are modifying your order when it hits 100 Points profit
You are not checking to see if it has already been modified
Next tick, if profit remains at more than 100 Points, the program will try to modify the order again with the same values.
This will return the error.
The check below ensure that the order already been modified. And the error 130 is not about it, if you the in the table ERROR this error say: Stops are too close, or prices are ill-calculated or unnormalized . .
The check below ensure that the order already been modified. And the error 130 is not about it, if you the in the table ERROR this error say: Stops are too close, or prices are ill-calculated or unnormalized . .
The check below ensure that the order already been modified. And the error 130 is not about it, if you the in the table ERROR this error say: Stops are too close, or prices are ill-calculated or unnormalized . .
Sorry about that.
To be honest, with a name like checkDoubles(), I thought that it was some kind of checking normalise double function, so I didn’t look too closely at it.
Especially as you wrote in your post «I changed the code removing the NormalizeDouble in the ‘if’ operators and put the function checkDoubles, but the error 130 continue happening.»
Источник
Что значит 2010.02.01 17:00 MyExpert GBPUSD,M15: OrderModify error 130
почему обычно эта ошибка возникает?
Очень много подобных вопросов мне приходит. Поэтому публикую таблицу кодов ошибок. Например посмотрев вышеописанную ошибку error 130 становится понятно, что функция OrderModify пытается изменить стоп-лосс или тейк-профит слишком близко к текущей цене.
Коды ошибок
GetLastError() — функция, возвращающая коды ошибок. Кодовые константы ошибок определены в файле stderror.mqh. Для вывода текстовых сообщений следует использовать функцию ErrorDescription(), определенную в файле stdlib.mqh.
Коды ошибок, возвращаемые торговым сервером или клиентским терминалом:
Значение | Описание |
---|---|
0 | Нет ошибки |
1 | Нет ошибки, но результат неизвестен |
2 | Общая ошибка |
3 | Неправильные параметры |
4 | Торговый сервер занят |
5 | Старая версия клиентского терминала |
6 | Нет связи с торговым сервером |
7 | Недостаточно прав |
8 | Слишком частые запросы |
9 | Недопустимая операция нарушающая функционирование сервера |
64 | Счет заблокирован |
65 | Неправильный номер счета |
128 | Истек срок ожидания совершения сделки |
129 | Неправильная цена |
130 | Неправильные стопы |
131 | Неправильный объем |
132 | Рынок закрыт |
133 | Торговля запрещена |
134 | Недостаточно денег для совершения операции |
135 | Цена изменилась |
136 | Нет цен |
137 | Брокер занят |
138 | Новые цены |
139 | Ордер заблокирован и уже обрабатывается |
140 | Разрешена только покупка |
141 | Слишком много запросов |
145 | Модификация запрещена, так как ордер слишком близок к рынку |
146 | Подсистема торговли занята |
147 | Использование даты истечения ордера запрещено брокером |
148 | Количество открытых и отложенных ордеров достигло предела, установленного брокером. |
Коды ошибок выполнения MQL4 программы:
Значение | Описание |
---|---|
4000 | Нет ошибки |
4001 | Неправильный указатель функции |
4002 | Индекс массива — вне диапазона |
4003 | Нет памяти для стека функций |
4004 | Переполнение стека после рекурсивного вызова |
4005 | На стеке нет памяти для передачи параметров |
4006 | Нет памяти для строкового параметра |
4007 | Нет памяти для временной строки |
4008 | Неинициализированная строка |
4009 | Неинициализированная строка в массиве |
4010 | Нет памяти для строкового массива |
4011 | Слишком длинная строка |
4012 | Остаток от деления на ноль |
4013 | Деление на ноль |
4014 | Неизвестная команда |
4015 | Неправильный переход |
4016 | Неинициализированный массив |
4017 | Вызовы DLL не разрешены |
4018 | Невозможно загрузить библиотеку |
4019 | Невозможно вызвать функцию |
4020 | Вызовы внешних библиотечных функций не разрешены |
4021 | Недостаточно памяти для строки, возвращаемой из функции |
4022 | Система занята |
4050 | Неправильное количество параметров функции |
4051 | Недопустимое значение параметра функции |
4052 | Внутренняя ошибка строковой функции |
4053 | Ошибка массива |
4054 | Неправильное использование массива-таймсерии |
4055 | Ошибка пользовательского индикатора |
4056 | Массивы несовместимы |
4057 | Ошибка обработки глобальныех переменных |
4058 | Глобальная переменная не обнаружена |
4059 | Функция не разрешена в тестовом режиме |
4060 | Функция не подтверждена |
4061 | Ошибка отправки почты |
4062 | Ожидается параметр типа string |
4063 | Ожидается параметр типа integer |
4064 | Ожидается параметр типа double |
4065 | В качестве параметра ожидается массив |
4066 | Запрошенные исторические данные в состоянии обновления |
4067 | Ошибка при выполнении торговой операции |
4099 | Конец файла |
4100 | Ошибка при работе с файлом |
4101 | Неправильное имя файла |
4102 | Слишком много открытых файлов |
4103 | Невозможно открыть файл |
4104 | Несовместимый режим доступа к файлу |
4105 | Ни один ордер не выбран |
4106 | Неизвестный символ |
4107 | Неправильный параметр цены для торговой функции |
4108 | Неверный номер тикета |
4109 | Торговля не разрешена |
4110 | Длинные позиции не разрешены |
4111 | Короткие позиции не разрешены |
4200 | Объект уже существует |
4201 | Запрошено неизвестное свойство объекта |
4202 | Объект не существует |
4203 | Неизвестный тип объекта |
4204 | Нет имени объекта |
4205 | Ошибка координат объекта |
4206 | Не найдено указанное подокно |
4207 | Ошибка при работе с объектом |
Если Вы хотите изучать язык MQL или вам понравилась данная публикация — Вы можете подписаться на получение новых материалов сайта mql4you.ru по
RSS
или по e-mail:
Другие публикации рубрики «FAQ по MQL и Metatrader»:
- Вопрос №9 «Как заставить работать советник при выключенном компьютере?»
- Вопрос №8 «Как рассчитать размер лота в зависимости от размера стоплосса?»
- Можно ли настроить нестандартный тайм-фрейм в MT4? — Вопрос №7
- Вопрос №6 «Как уменьшить размер папки с терминалом MT4?»
- Вопрос №4 — «Выключение компьютера из MQL»
- Вопрос №3
- Вопрос №2
- Вопрос №1
Recommended Posts
A.Kostin
0
-
- Share
int ticket=OrderSend(Symbol(),OP_BUY,MarketInfo(Symbol(),MODE_MINLOT),Ask,3,Bid-100*Point*10,Ask+100*Point*10);
отдаёт ошибку 130 Неправильные стопы-(((
Link to post
Share on other sites
ToB. CyxoB
324
-
- Share
int ticket=OrderSend(Symbol(),OP_BUY,MarketInfo(Symbol(),MODE_MINLOT),Ask,3,Bid-100*Point*10,Ask+100*Point*10);
отдаёт ошибку 130 Неправильные стопы-(((
зачем вы дважды проводите умножение
100*Point*10 ?
лучше Point*1000
Link to post
Share on other sites
ToB. CyxoB
324
-
- Share
int ticket=OrderSend(Symbol(),OP_BUY,MarketInfo(Symbol(),MODE_MINLOT),Ask,3,Bid-100*Point*10,Ask+100*Point*10);
отдаёт ошибку 130 Неправильные стопы-(((
тут лучше поставить 0.01
Link to post
Share on other sites
ToB. CyxoB
324
-
- Share
Link to post
Share on other sites
Ugar68
372
-
- Share
int ticket=OrderSend(Symbol(),OP_BUY,MarketInfo(Symbol(),MODE_MINLOT),Ask,3,Bid-100*Point*10,Ask+100*Point*10);
отдаёт ошибку 130 Неправильные стопы-(((
Я так понял что умножение на 10 это для 5ти знака. Тогда и проскальзывание надо умножить.
А цены надо нормировать.
double lot=MarketInfo(Symbol(),MODE_MINLOT);
double op=NormalizeDouble(Ask,Digits);
double sl=NormalizeDouble(Bid-100*Point*10,Digits);
double tp=NormalizeDouble(Ask+100*Point*10,Digits);
ticket=OrderSend(Symbol(),OP_BUY,lot,op,30,sl,tp,NULL,0,0,CLR_NONE);
Пишу советники и индикаторы по вашим алгоритмам. Пишите в личку.
Чужие программы не переделываю.
Link to post
Share on other sites
40ru
9
-
- Share
зачем вы дважды проводите умножение
100*Point*10 ?
лучше Point*1000
Сухов, я тя не узнаю. .Что с тобой??? Може пристрелить тя, что б не мучился???
Link to post
Share on other sites
ToB. CyxoB
324
-
- Share
int ticket=OrderSend(Symbol(),OP_BUY,MarketInfo(Symbol(),MODE_MINLOT),Ask,3,Bid-100*Point*10,Ask+100*Point*10);
отдаёт ошибку 130 Неправильные стопы-(((
если убрать красное — то все работает
Link to post
Share on other sites
A.Kostin
0
- Author
-
- Share
зачем вы дважды проводите умножение
100*Point*10 ?
лучше Point*1000
Для наглядности 100-количество пунктов, 10-5й знак.
Link to post
Share on other sites
ToB. CyxoB
324
-
- Share
Сухов, я тя не узнаю. .Что с тобой??? Може пристрелить тя, что б не мучился???
я читал что такие избыточные действия грузят систему..и их лучше избегать…
а так же лучше вместо деления на 10 например, выполнять умножение на 0.1…так как не будет проверки деления на 0 что ускорит работу….
а будешь грубить — я выпишу тебе предупреждение.
Link to post
Share on other sites
40ru
9
-
- Share
а будешь грубить — я выпишу тебе предупреждение.
Не а, я знаю, ты хороший… ))))
Link to post
Share on other sites
A.Kostin
0
- Author
-
- Share
Не получается и с красным и без него-(((
double lot=MarketInfo(Symbol(),MODE_MINLOT);
double cena=NormalizeDouble(Ask,Digits);
double sliv=NormalizeDouble(Bid-1000*Point,Digits);
double plus=NormalizeDouble(Ask+1000*Point,Digits);
int ticket=OrderSend(Symbol(),OP_BUY,lot,cena,30,sliv,plus,NULL,0,0,CLR_NONE);
Alert(«Ошибка «,GetLastError());
Link to post
Share on other sites
kazakov.v
189
-
- Share
я читал что такие избыточные действия грузят систему..и их лучше избегать…
а так же лучше вместо деления на 10 например, выполнять умножение на 0.1…так как не будет проверки деления на 0 что ускорит работу….
Ну, это если на Радио-86РК запускать — может быть (exeptions же изобрели уже)
———
А по теме: нормализация в данном случае не нужна, а вот ежели такую команду на ndd/ecn (на market execution) запускать — ругаться будет 130 ошибкой, ибо стопы нельзя сразу ставить.
Никому верить нельзя.
Мне — можно.
Link to post
Share on other sites
ToB. CyxoB
324
-
- Share
Не получается и с красным и без него-(((
double lot=MarketInfo(Symbol(),MODE_MINLOT);
double cena=NormalizeDouble(Ask,Digits);
double sliv=NormalizeDouble(Bid-1000*Point,Digits);
double plus=NormalizeDouble(Ask+1000*Point,Digits);
int ticket=OrderSend(Symbol(),OP_BUY,lot,cena,30,sliv,plus,NULL,0,0,CLR_NONE);
Alert(«Ошибка «,GetLastError());
я поменял вашу строку вместо своей — то что ранее отметил красным убрал ибо у меня этого не было — шла проверка на условие, и если ДА — то покупка. и все работало. значит ошибка НЕ в стопах , а в int ticket
Link to post
Share on other sites
ToB. CyxoB
324
-
- Share
Ну, это если на Радио-86РК запускать — может быть
(exeptions же изобрели уже)
———
А по теме: нормализация в данном случае не нужна, а вот ежели такую команду на ndd/ecn (на market execution) запускать — ругаться будет 130 ошибкой, ибо стопы нельзя сразу ставить.
точно..не обращал внимание….:-D
Link to post
Share on other sites
A.Kostin
0
- Author
-
- Share
Так в чем же может у меня быть дело?
Link to post
Share on other sites
40ru
9
-
- Share
Ну, это если на Радио-86РК запускать — может быть
Ух, какая штука. .я собирал ее… Эх, во жили.. не то что сейчас…
Link to post
Share on other sites
kazakov.v
189
-
- Share
Так в чем же может у меня быть дело?
Счет какой у Вас?
Никому верить нельзя.
Мне — можно.
Link to post
Share on other sites
40ru
9
-
- Share
ticket=OrderSend(Symbol(),OP_BUY,lot,cena,30,sliv,plus,NULL,0,0,CLR_NONE);
Alert(«Ошибка «,GetLastError());
OP_BUY открывается по ACK а ты его по Bid открываешь. .эх ты, дядя…
ticket=OrderSend(Symbol(), OP_BUY, Lot, Ask, slip, 0, 0, NULL, Magic);
ticket=OrderSend(Symbol(), OP_SELL, Lot, Bid, slip, 0, 0, NULL, Magic);
P.S хотя не, вроде верно у него… Во намутил ..
Edited November 24, 2010 by 40ru
Link to post
Share on other sites
A.Kostin
0
- Author
-
- Share
Счет какой у Вас?
Alpari MT4 — Демо счет
Link to post
Share on other sites
40ru
9
-
- Share
Alpari MT4 — Демо счет
Замени свою бадью, моими значениями. и посмотри что будет… Намудрил ты…Если будет работать, значит все окей..
Link to post
Share on other sites
kazakov.v
189
-
- Share
Alpari MT4 — Демо счет
Демо разные есть:-demo, -ndd-demo, -ecn-demo.
Если 2 или 3 вариант — то там market execution, т.е. сначала нужно открыть ордер без стопов, а следующей командой (OrderModify) устанавливать стопы.
ЗЫ а вручную-то получается сразу открыть со стопами?
Никому верить нельзя.
Мне — можно.
Link to post
Share on other sites
A.Kostin
0
- Author
-
- Share
Link to post
Share on other sites
Ugar68
372
-
- Share
С этого надо было начинать. Проскальзывание надо ещё увеличить. И стопы с тейками потом.
Почитай
Пишу советники и индикаторы по вашим алгоритмам. Пишите в личку.
Чужие программы не переделываю.
Link to post
Share on other sites
- 1 year later…
uralets58
0
-
- Share
Большое спасибо за ответы.3 дня убил на ошибку 130.Оказывается надо вместо S/L и T/P ставить 0 в OrderSend.Вот как это выглядит:
OrderSend(Symbol(),OP_BUY,Lot,Ask,slip,0,0);-для покупки.
OrderSend(Symbol(),OP_SELL,Lot,Bid,slip,0,0);-для продажи.
Вставляю в советник вместе с Alert(GetLastError());друг под другом.Окошко выдаёт «Код ошибок»,легко ориентироваться.
Link to post
Share on other sites
Мэкс
9
-
- Share
Не забудьте только обновить цены с помощью RefreshRates() !
Вот как это выглядит:
RefreshRates();
OrderSend(Symbol(),OP_BUY,Lot,Ask,slip,0,0);-для покупки.
RefreshRates();
OrderSend(Symbol(),OP_SELL,Lot,Bid,slip,0,0);-для продажи.
Link to post
Share on other sites
-
2 yr
Capman locked this topic
This topic is now closed to further replies.
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.
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?