If you see "OrderClose failed error 130", it usually means one thing: MT4 thinks your price, stop loss, or take profit is not allowed.
You are closing with the wrong price.
If you close at the wrong one, MT4 can freak out and throw errors.
RefreshRates();
double closePrice = (OrderType() == OP_BUY) ? Bid : Ask;
closePrice = NormalizeDouble(closePrice, Digits);
bool ok = OrderClose(OrderTicket(), OrderLots(), closePrice, 3, clrRed);
if(!ok)
{
Print("OrderClose failed. Error = ", GetLastError());
}
else
{
Print("Trade closed!");
}
Error 130 means “invalid stops”. Even though you are closing a trade, MT4 still checks things like:
This gets the newest Bid/Ask prices. Without it, you might close using old prices.
RefreshRates();
Some brokers are picky about decimal places.
closePrice = NormalizeDouble(closePrice, Digits);
Some brokers don’t allow stops too close to price. This is called the stop level.
int stopLevel = (int)MarketInfo(Symbol(), MODE_STOPLEVEL);
Print("StopLevel (points) = ", stopLevel);
If stopLevel is 30, that means your SL/TP must be at least:
30 * Point
Sometimes your code is trying to close something that is not selected properly. Always make sure you used OrderSelect().
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
continue;
// Now it's safe to use OrderClose on this order
}
This version is simple and safe:
// SAFE CLOSE TEMPLATE
RefreshRates();
double closePrice = (OrderType() == OP_BUY) ? Bid : Ask;
closePrice = NormalizeDouble(closePrice, Digits);
bool ok = OrderClose(OrderTicket(), OrderLots(), closePrice, 3, clrRed);
if(!ok)
{
int err = GetLastError();
Print("OrderClose failed. Error = ", err);
// Extra info to help you debug
Print("Type=", OrderType(),
" Lots=", DoubleToString(OrderLots(),2),
" ClosePrice=", DoubleToString(closePrice, Digits),
" Bid=", DoubleToString(Bid, Digits),
" Ask=", DoubleToString(Ask, Digits));
}
Then it's usually one of these:
// If you're using 1, try 3 or 5 int slippage = 5;
Once you follow those, Error 130 usually disappears.
Click here to return to MQL4 Basics Directory