Ошибка 130 mt4

Axioss писал(а) >>

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

Как уже написали — TP забыт

Ticket=OrderSend(Symb,OP_SELL,Lots,Bid,3,SL, TP, Green); //открытие Sell
Но видимо проблема не в этом?

Я сделал так

sl1 = NormalizeDouble(Bid + MLockSL * Point,Digits);
if (MLockSL <= 0) sl1 = NormalizeDouble(0,Digits);
tp1 = NormalizeDouble(Bid - MLockTP * Point,Digits);
if (MLockTP <= 0) tp1 = NormalizeDouble(0,Digits);

Balancelots = NormalizeDouble(Balancelots,Digits);

Comment ("155: Balancelots=",Balancelots);
Alert ("155: Пытаюсь залочить buy! Balancelots=",Balancelots," SL1=",sl1," TP1=",tp1);

LockTicketB=OrderSend(Symbol(),OP_SELL,Balancelots,Bid,Slippage,sl1,tp1,"225:залочили buy",362,0,Magenta); // лочим buy
if(LockTicketB<0)
     {
      LockBuy =0;
      Print("165: Не смог залочить buy ",ErrorDescription(GetLastError()));
      Alert ("165: Не смог залочить buy! Balancelots=",Balancelots," SL1=",sl1," TP1=",tp1,"Bid=",Bid);
     }
     else
     Alert ("166: Залочил buy! Balancelots=",Balancelots," SL1=",sl1," TP1=",tp1,"Bid=",Bid);

You should know that there exists a minimum Stop Loss Size (mSLS) given in pips. «mSLS» changes with the currency and broker. So, you need to put in the OnInit() procedure of your EA a variable to get it:

int mSLS = MarketInfo(symbol,MODE_STOPLEVEL);

The distance (in pips) from your Order Open Price (OOP) and the Stop-Loss Price (SLP) can not be smaller than mSLS value.

I will try to explain a general algorithm I use for opening orders in my EAs, and then apply the constrain on Stop-Loss level (at step 3):

Step 1. I introduce a flag (f) for the type of operation I will open, being:

f = 1 for Buy, and
f = -1 for Sell

You know that there are mql4 constants OP_SELL=1 and OP_BUY=0 (https://docs.mql4.com/constants/tradingconstants/orderproperties).

Once I have defined f, I set my operation type variable to

int OP_TYPE =  int(0.5((1+f)*OP_BUY+(1-f)*OP_SELL)); 

that takes value OP_TYPE=OP_BUY when f=1, while OP_TYPE=OP_SELL when f=-1.

NOTE: Regarding the color of the orders I put them in an array

color COL[2]= {clrBlue,clrRed};

then, having OP_TYPE, I set

color COLOR=COL[OP_TYPE];

Step 2. Similarly, I set the Order Open Price as

double OOP =  int(0.5*((1+f)*Ask+(1-f)*Bid));

which takes value OOP=Ask when f=1, while OOP=Bid when f=-1.

Step 3. Then, given my desired Stop Loss in pips (an external POSITIVE parameter of my EA, I named sl) I make sure that sl > SLS. In other words, I check

if (sl <= mSLS) // I set my sl as the minimum allowed
  {
    sl = 1 + mSLS;
  }

Step 4. Then I calculate the Stop-Loss Price of the order as

double SLP =  OOP - f * sl * Point;

Step 5. Given my desired Take Profit in pips (an external POSITIVE parameter of my EA, I named tp) I calculate the Take-Profit Price (TPP) of the order as

double TPP =  OOP + f * tp * Point;

OBSERVATION: I can not affirm, but, according to mql4 documentation, the minimum distance rule between the stop-loss limit prices and the open price also applies to the take profit limit price. In this case, a «tp» check-up needs to be done, similar to that of the sl check-up, above. that is, before calculating TPP it must be executed the control lines below

if (tp <= mSLS) // I set my tp as the minimum allowed
  {
    tp = 1 + mSLS;
  }

Step 5. I call for order opening with a given lot size (ls) and slippage (slip) on the operating currency pair (from where I get the Ask and Bid values)

float ls = 0.01;
int slip = 3; //(pips)

int order = OrderSend(Symbol(),OP_TYPE,ls,OOP,slip,SLP,TPP,"",0,0,COLOR);

Note that with these few lines it is easy to build a function that opens orders of any type under your command, in any currency pair you are operating, without receiving error message 130, passing to the function only 3 parameters: f, sl and tp.

It is worth including in the test phase of your EA a warning when the sl is corrected for being less than the allowed, this will allow you to increase its value so that it does not violate the stop-loss minimum value rule, while you have more control about the risk of its operations. Remember that the «sl» parameter defines how much you will lose if the order fails because the asset price ended up varying too much in the opposite direction to what was expected.

I hope I could help!

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.

MT Error 130 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:

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

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

    Invalid Stop Loss Buy Stop

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

    Invalid Stop Sell Stop

  4. Buy Limit (with Expert Advisor)

    For an Expert Advisor that returns MT4 error 130 when you are attempting to place a Buy Limit order:

    Invalid Stop Error Buy Limit

  5. Sell Limit (with Expert Advisor)

    On an Expert Advisor that returns MT4 error 130 when you try to place a Sell Limit order:

    Invalid Stop Error Sell Limit

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.

Recommended Posts

A.Kostin
  

0



A.Kostin

    • 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



ToB. CyxoB

    • 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



ToB. CyxoB

    • 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



ToB. CyxoB

    • Share
Link to post
Share on other sites

Ugar68
  

372



Ugar68

    • 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



40ru

    • Share

зачем вы дважды проводите умножение

100*Point*10 ?

лучше Point*1000

Сухов, я тя не узнаю. .Что с тобой??? Може пристрелить тя, что б не мучился??? :flower2:

Link to post
Share on other sites

ToB. CyxoB
  

324



ToB. CyxoB

    • 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



A.Kostin

  • Author
    • Share

зачем вы дважды проводите умножение

100*Point*10 ?

лучше Point*1000

Для наглядности 100-количество пунктов, 10-5й знак.

Link to post
Share on other sites

ToB. CyxoB
  

324



ToB. CyxoB

    • Share

Сухов, я тя не узнаю. .Что с тобой??? Може пристрелить тя, что б не мучился??? :flower2:

я читал что такие избыточные действия грузят систему..и их лучше избегать…

а так же лучше вместо деления на 10 например, выполнять умножение на 0.1…так как не будет проверки деления на 0 что ускорит работу….

а будешь грубить — я выпишу тебе предупреждение.

:1111483289:

Link to post
Share on other sites

40ru
  

9



40ru

    • Share

а будешь грубить — я выпишу тебе предупреждение.

:1111483289:

Не а, я знаю, ты хороший… ))))

Link to post
Share on other sites

A.Kostin
  

0



A.Kostin

  • 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



kazakov.v

    • Share

я читал что такие избыточные действия грузят систему..и их лучше избегать…

а так же лучше вместо деления на 10 например, выполнять умножение на 0.1…так как не будет проверки деления на 0 что ускорит работу….

Ну, это если на Радио-86РК запускать — может быть :crazy: (exeptions же изобрели уже)

———

А по теме: нормализация в данном случае не нужна, а вот ежели такую команду на ndd/ecn (на market execution) запускать — ругаться будет 130 ошибкой, ибо стопы нельзя сразу ставить.


Никому верить нельзя.

Мне — можно.

Link to post
Share on other sites

ToB. CyxoB
  

324



ToB. CyxoB

    • 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



ToB. CyxoB

    • Share

Ну, это если на Радио-86РК запускать — может быть :crazy: (exeptions же изобрели уже)

———

А по теме: нормализация в данном случае не нужна, а вот ежели такую команду на ndd/ecn (на market execution) запускать — ругаться будет 130 ошибкой, ибо стопы нельзя сразу ставить.

точно..не обращал внимание….:-D

Link to post
Share on other sites

A.Kostin
  

0



A.Kostin

  • Author
    • Share

Так в чем же может у меня быть дело?

Link to post
Share on other sites

40ru
  

9



40ru

    • Share

Ну, это если на Радио-86РК запускать — может быть

Ух, какая штука. .я собирал ее… Эх, во жили.. не то что сейчас…

Link to post
Share on other sites

kazakov.v
  

189



kazakov.v

    • Share

Так в чем же может у меня быть дело?

Счет какой у Вас?


Никому верить нельзя.

Мне — можно.

Link to post
Share on other sites

40ru
  

9



40ru

    • 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



A.Kostin

  • Author
    • Share

Счет какой у Вас?

Alpari MT4 — Демо счет

Link to post
Share on other sites

40ru
  

9



40ru

    • Share

Alpari MT4 — Демо счет

Замени свою бадью, моими значениями. и посмотри что будет… Намудрил ты…Если будет работать, значит все окей..

Link to post
Share on other sites

kazakov.v
  

189



kazakov.v

    • Share

Alpari MT4 — Демо счет

Демо разные есть:-demo, -ndd-demo, -ecn-demo.

Если 2 или 3 вариант — то там market execution, т.е. сначала нужно открыть ордер без стопов, а следующей командой (OrderModify) устанавливать стопы.

ЗЫ а вручную-то получается сразу открыть со стопами?


Никому верить нельзя.

Мне — можно.

Link to post
Share on other sites

A.Kostin
  

0



A.Kostin

  • Author
    • Share
Link to post
Share on other sites

Ugar68
  

372



Ugar68

    • Share

:badgrin: С этого надо было начинать. Проскальзывание надо ещё увеличить. И стопы с тейками потом.

Почитай


Пишу советники и индикаторы по вашим алгоритмам. Пишите в личку.
Чужие программы не переделываю.

Link to post
Share on other sites
  • 1 year later…

uralets58
  

0



uralets58

    • 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


Guest

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.

Example of OrderSend Error 130 in MetaTrader 4

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:

Example of StopLevel Output in MetaTrader 4

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.

What Stop Level Means for Buy Order's Stop-Loss and Take-Profit - Simple Chart

What Stop Level Means for Sell Order's Stop-Loss and Take-Profit - Simple Chart

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.

What Is Stop Level When Placing Buy Limit Pending Order - Relation to Entry, SL, and TP

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.

What Is Stop Level When Placing Sell Limit Pending Order - Relation to Entry, SL, and TP

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.

What Is Stop Level When Placing Buy Stop Pending Order - Relation to Entry, SL, and TP

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.

What Is Stop Level When Placing Sell Stop Pending Order - Relation to Entry, SL, and TP

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.

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