Ошибка 130 mt4

Помогите, ошибка 130 при попытке открыть Sell Помогите, советник все время выдает ошибку 130 при попытке открыть Sell. При этом при попытке открыть Buy, выдал ошибку 130 один раз и после ни разу не выдавал, сколько я не присоединял советника к графику. Вот и получается, что все Buy он открывает, а Sell не может. […]

Содержание

  1. Помогите, ошибка 130 при попытке открыть Sell
  2. OrderSend Error 130 — What to Do?
  3. Market orders
  4. MQL4 solution to OrderSend Error 130 with market orders
  5. Pending orders
  6. MQL4 solution to OrderSend Error 130 with pending orders
  7. why do dolls die the power of passivity and the embodied interplay between disability and sex dolls?
  8. Video Tutorial
  9. The silent killer
  10. 1) StopLoss & TakeProfit are prices
  11. 2) 4-digits vs 5-digits
  12. 3) ECN brokers
  13. Conclusion

Помогите, ошибка 130 при попытке открыть Sell

Помогите, советник все время выдает ошибку 130 при попытке открыть Sell. При этом при попытке открыть Buy, выдал ошибку 130 один раз и после ни разу не выдавал, сколько я не присоединял советника к графику. Вот и получается, что все Buy он открывает, а Sell не может. Что это может быть.

while(true) // цикл закрытия ордера
<
if (Total==0 && Opn_B==true) // открытых ордеров нет +
< // критерий на открытие Buy
RefreshRates(); // обновление данных
SL=Bid — StopLoss*Point; // вычисление SL открываемого ордера
Alert(«Попытка открыть Buy. Ожидание ответа..»);
Ticket=OrderSend(Symb,OP_BUY,Lots,Ask,3,SL,Green); //открытие Buy
if (Ticket > 0) // получилось
<
Alert («Открыт ордер Buy «,Ticket);
return; // выход из функции start()
>
if (Fun_Error(GetLastError())==1) // обработка ошибок
continue; // повторная попытка
return; // выход из функции start()
>
if (Total==0 && Opn_S==true) // открытых ордеров нет +
< // критерий на открытие Sell
RefreshRates(); // обновление данных
SL=Ask + StopLoss*Point; // вычисление SL откр.
Alert(«Попытка открыть Sell. Ожидание ответа..»);
Ticket=OrderSend(Symb,OP_SELL,Lots,Bid,3,SL,Green); //открытие Sell
if (Ticket > 0) // получилось
<
Alert («Открыт ордер Sell «,Ticket);
return; // выход из функции start()
>
if (Fun_Error(GetLastError())==1) // обработка ошибок
continue; // повторная попытка
return; // выход из функции start()
>
break; // выход из функции while
>

Константа Значение Описание
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 Количество открытых и отложенных ордеров достигло предела, установленного брокером.

< // критерий на открытие Sell
RefreshRates(); // обновление данных
SL=Ask + StopLoss*Point; // вычисление SL откр.

Исправте на: SL=Bid + StopLoss*Point; // вычисление SL откр.

. Что это может быть.

ERR_INVALID_STOPS 130 Слишком близкие стопы или неправильно рассчитанные или ненормализованные цены в стопах (или в цене открытия отложенного ордера). Попытку можно повторять только в том случае, если ошибка произошла из-за устаревания цены. Необходимо после задержки от 5 секунд обновить данные при помощи функции RefreshRates и повторить попытку. Если ошибка не исчезает, необходимо прекратить все попытки торговых операций и изменить логику программы.

P.S. В Вашем варианте это или Слишком близкие стопы или ненормализованные цены в стопах или и то и другое.

См. также

MODE_STOPLEVEL 14 Минимально допустимый уровень стоп-лосса/тейк-профита в пунктах

В команде OrderSend после SL должно стоять значение для TP.

да, что тут скажешь . rtfm

То, что это неправильные стопы, я знаю. Я пробывал и нормализовывать цену, и RefreshRates есть, так на Buy то все нормально, а на Sell — ошибка 130 и все тут, хотя мой SL очень далек от StopLevel

Константа Значение Описание
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 Количество открытых и отложенных ордеров достигло предела, установленного брокером.

< // критерий на открытие Sell
RefreshRates(); // обновление данных
SL=Ask + StopLoss*Point; // вычисление SL откр.

Исправте на: SL=Bid + StopLoss*Point; // вычисление SL откр.

Спасибо, помогло. Открывает чудно. Я вроде пробовал так, как вы написали, и у меня ничего не получалось. Но. раз получилось сейчас, значит так пробовал.

Источник

OrderSend Error 130 — What to Do?

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 or 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 / 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 or 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 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 or in points is calculated, just make sure that they aren’t less than 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 Sell orders:

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.

Some brokers (ECN ones) don’t allow expert advisors to set or levels on market orders in the OrderSend() function even if it is greater than their MODE_STOPLEVEL value. In this case, you will have to change your EA to send market orders without SL and TP and then use OrderModify() function to set and for the open position. Alternatively, you can also switch the EA to using pending orders only.

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.

Источник

why do dolls die the power of passivity and the embodied interplay between disability and sex dolls?

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 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 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.

Источник

Содержание

  1. OrderModify и error 130 — моделирование по ценам открытия
  2. Error 130, invalid stops
  3. Error 130 on OrderModify
  4. Модификация ордера ошибка 130
  5. MQL для тебя
  6. Вопрос №5 — «Коды ошибок при тестировании советника»
  7. Коды ошибок

OrderModify и error 130 — моделирование по ценам открытия

Позиция на покупку открывается по Аску, а закрывается по Биду. Поэтому прежде всего нужно знать, что при подтягивании стопа нужно работать с ценой бид.
Далее. Если, как Вы утверждаете, подтягивание происходит слишком близко к рынку, то сама логика ситуации подсказывает Вам решение — сначала проверить цену на предмет близости, потом подтягивать, если близость допустимая.

Позиция на покупку открывается по Аску, а закрывается по Биду. Поэтому прежде всего нужно знать, что при подтягивании стопа нужно работать с ценой бид.
Далее. Если, как Вы утверждаете, подтягивание происходит слишком близко к рынку, то сама логика ситуации подсказывает Вам решение — сначала проверить цену на предмет близости, потом подтягивать, если близость допустимая.

Это правильно, если тестировать по тикам (методы «все тики» или «контрольные точки»). А как быть, если тестирование осуществляется «по ценам открытия». Как я уже упомянул, 1,3508 — это цена открытия текущего бара.
Как здесь написано, произойдет сравнение, SL не подтянется, правильно. Теперь следующий запуск функции start() произойдет ЛИШЬ на цене открытия следующего бара (так как метод моделирования по ценам открытия). И SL не будет подтянут. А само тело текущего бара запросто может пробить уровень SL, который не был выставлен.

Источник

Error 130, invalid stops

Подскажите пожалуйста, где может быть ошибка у меня в коде.

Я пытаюсь открыть позицию, но получаю ошибку 130 — invalid stops.

iTicket = OrderSend(Symbol(), OP_BUY, e_dLotSize, NormalizeDouble(Ask, Digits), 10, 0.0,
NormalizeDouble(dMABidMain + dSpreadCurr * e_dTakeProfitInSpreads, Digits));
if (iTicket > 0)
<
Print(g_strInf, «Opened new BUY positions #», iTicket,
«, Ask=», DoubleToStr(Ask, Digits),
«, Bid=», DoubleToStr(Bid, Digits),
«, OpenPrice=», DoubleToStr(Ask, Digits),
«, TakeProfit=», DoubleToStr(dMABidMain + dSpreadCurr * e_dTakeProfitInSpreads, Digits),
«, LotSize=», e_dLotSize
);
>
else
<
iErrorCode = GetLastError();
dNewStopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
dNewFreezeLevel = MarketInfo(Symbol(), MODE_FREEZELEVEL);
Print(g_strErr, «Failed to open new BUY position»,
«, NewStpLvl=», DoubleToStr(dNewStopLevel, Digits),
«, NewFrzLvl=», DoubleToStr(dNewFreezeLevel, Digits),
«, Ask=», DoubleToStr(Ask, Digits),
«, Bid=», DoubleToStr(Bid, Digits),
«, OpenPrice=», DoubleToStr(Ask, Digits),
«, TakeProfit=», DoubleToStr(dMABidMain + dSpreadCurr * e_dTakeProfitInSpreads, Digits),
«, LotSize=», e_dLotSize,
«, ErrCode=», iErrorCode, «, «, ErrorDescription(iErrorCode)
);
>

ERR Failed to open new BUY position, NewStpLvl=0.00000, NewFrzLvl=0.00000, Ask=1.26506, Bid=1.26432, OpenPrice=1.26506, TakeProfit=1.26573, LotSize=0.1, ErrCode=130, invalid stops

Видно, что пытаюсь купить по цене Ask. TakeProfit поставлен вроде правильно. И все равно не срабатывает. Может, я где-нибудь Bid/Ask перепутал?

Грешил на StopLevel, но он нулевой. Может нельзя выставлять уровень Take Profit одновременно с открытием позиции?

Как узнать в чем проблема?

Можно предположить, что с момента получения тика цены Bid/Ask изменились, но ведь тогда ошибка должна быть уже другой, верно?

Или нельзя не указывать stop loss (ставить нулевым) при задании take profit?

Источник

Error 130 on OrderModify

Hi, I’m Thomas a passionate beginner coder..

I have searched on a lot of topics but I did not find how to solve my problem .. maybe someone can enlighten me ..

Here is my code :

if (prev_ma10>prev_ma5 && ma10 if ( OrdersTotal () != 0 ) closeexisting(); OrderSend ( Symbol (),OP_BUY,LotSize,Ask, 3 ,Ask — (StopLoss * Pips), Ask + (TakeProfit * Pips), NULL ,MagicNumber, 0 ,Green); for ( int b= OrdersTotal ()- 1 ;b>= 0 ;b—) < if ( OrderSelect (b,SELECT_BY_POS,MODE_TRADES)) if (OrderSymbol()== Symbol ()) if (OrderType ()==OP_BUY) if ( HighestCandle //For current order OrderOpenPrice(), // opened for the OpenPrice Ask + (TraillingStep * Pips), // set stop loss OrderTakeProfit(), // unchanged takeprofit 0 , // no expiration CLR_NONE // no color );

Everything works perfectly except the modification of the stop loss (the bold part)

The stop loss is supposed to move from the moment it reaches the purchase price + the Takeprofit (traillingstopstart)

thank you in advance for your help,

You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit and open at the Ask.

Your buy order’s TP/SL (or Sell Stop’s/Sell Limit’s entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n , makes your SL shorter and your TP longer, by the spread. Don’t you want the specified amount used in either direction?

Your sell order’s TP/SL (or Buy Stop’s/Buy Limit’s entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close to a specific Bid price, add the average spread.
MODE_SPREAD (Paul) — MQL4 programming forum — Page 3 #25

The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)
Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes. My GBPJPY (OANDA) shows average spread = 26 points, but average maximum spread = 134 (your broker will be similar).

  • How can the stop loss be above the market for a buy order?
  • Vous achetez à la demande et vous vendez à l’ offre . Les ordres d’achat stop en attente deviennent des ordres de marché lorsqu’ils sont frappés et ouverts à la demande .

    Le TP / SL de votre ordre d’achat (ou l’entrée de Sell Stop / Sell Limit) est déclenché lorsque le Bid / OrderClosePrice l’ atteint. En utilisant Ask ± n , votre SL est plus court et votre TP plus long, par l’écart. Vous ne voulez pas que le montant spécifié soit utilisé dans les deux sens?

    Le TP / SL de votre ordre de vente (ou l’entrée de Buy Stop / Buy Limit) sera déclenché lorsque le Ask / OrderClosePrice l’ atteindra. Pour déclencher près d’un prix Bid spécifique , ajoutez le spread moyen.
    MODE_SPREAD (Paul) — Forum de programmation MQL4 — Page 3 # 25

    Les graphiques montrent uniquement les prix des offres . Activez la ligne Ask pour voir la taille du spread ( Outils → Options (contrôle + O) → graphiques → Afficher la ligne de demande .)
    La plupart des courtiers avec des spreads variables s’élargissent considérablement en fin de journée (17 h HE) ± 30 minutes. Mon GBPJPY (OANDA) montre un spread moyen = 26 points, mais un spread maximum moyen = 134 (votre courtier sera similaire).

  • Comment le stop loss peut -il être supérieur au marché pour un ordre d’achat?
  • Hi William Roeder 🙂

    Woah, actually I had totally neglected the spread!

    I will add it .. thank you very much for that (genius) ..

    So indeed it may be an abuse of language but the

    Ask + (TraillingStep * Pips), // définir la perte d’arrêt

    Is not a StopLoss .. but a «condition» If the high of the candle is equal to my «TraillingStopStart» (ask + 80 pips) then I would like to trigger my trailing StopLoss directly at (ask + 70) so 10 pips below on current price then thereafter my TraillingStep is the movement of my StopLoss by 10 pips by 10 pips each time the market increases by 10 pips.

    I had first created the code in a very simple EA with very simple order launch conditions, just to check the correct operation of my Trailling StopLoss .. Everything worked perfectly so I integrated my real strategy (therefore more complex) and bim .. Error 130 OrderModify

    Источник

    Модификация ордера ошибка 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)
    в большинстве случаев помогает.

    а еще можно перенести расчет тейка в цикл перед отправкой запроса на модификацию, так будет лучше, расчет тейка будет происходить по текущим данным цены.

    Спасибо буду пробовать. Вот что получилось))

    Источник

    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 программы:

    Источник

    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" );
             }
         }
    

    Stanislav Kralin's user avatar

    asked Dec 2, 2014 at 2:33

    Filipe Ferminiano's user avatar

    Filipe FerminianoFilipe Ferminiano

    8,13425 gold badges99 silver badges172 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 );
    

    user3666197's user avatar

    answered Dec 3, 2014 at 8:43

    whitebloodcell's user avatar

    whitebloodcellwhitebloodcell

    2981 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

    user3666197's user avatar

    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
                                      );
    

    user3666197's user avatar

    answered Nov 25, 2016 at 11:58

    Ramzy's user avatar

    RamzyRamzy

    1171 silver badge13 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

    Simo's user avatar

    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

    Henri Fanda's user avatar

    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" );
             }
         }
    

    Stanislav Kralin's user avatar

    asked Dec 2, 2014 at 2:33

    Filipe Ferminiano's user avatar

    Filipe FerminianoFilipe Ferminiano

    8,13425 gold badges99 silver badges172 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 );
    

    user3666197's user avatar

    answered Dec 3, 2014 at 8:43

    whitebloodcell's user avatar

    whitebloodcellwhitebloodcell

    2981 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

    user3666197's user avatar

    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
                                      );
    

    user3666197's user avatar

    answered Nov 25, 2016 at 11:58

    Ramzy's user avatar

    RamzyRamzy

    1171 silver badge13 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

    Simo's user avatar

    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

    Henri Fanda's user avatar

    ordersend-error-130

    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:

    ERR_INVALID_STOPS

    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:

    forex-symbol-properties

    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:

    Algorithmic Trading Course

    What are you waiting for?

    START LEARNING FOREX TODAY!

    Понравилась статья? Поделить с друзьями:
  • Ошибка 130 mql4
  • Ошибка 13 принтер пантум м6500 как исправить
  • Ошибка 13 планар 44д 4 квт
  • Ошибка 13 опель синтра
  • Ошибка 13 опель вектра а c20ne