If your EA won’t close trades or won’t move stop loss… don’t worry. Most of the time it’s just one small mistake. This page explains it in the simplest way possible.
true or false
true means it worked.
false means it failed.
If it fails, you should print the error number so you know why.
bool ok = OrderClose(ticket, lots, price, slippage, clrRed);
if(!ok)
{
Print("OrderClose failed. Error = ", GetLastError());
}
To close a trade, you MUST use the correct price:
That’s it. This is the #1 reason OrderClose fails.
// First select an order, then:
RefreshRates(); // get fresh Bid/Ask
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!");
}
OrderModify is picky. You can’t say “only change stop loss”. You must send ALL the important values again.
// Select the order first:
RefreshRates();
double newSL = OrderOpenPrice(); // break-even price
newSL = NormalizeDouble(newSL, Digits);
bool ok = OrderModify(
OrderTicket(),
OrderOpenPrice(), // keep same open price
newSL, // new stop loss
OrderTakeProfit(), // keep same take profit
0,
clrYellow
);
if(!ok)
{
Print("OrderModify failed. Error = ", GetLastError());
}
else
{
Print("Stop moved!");
}
BUY closes with Bid, SELL closes with Ask.
Some brokers don’t allow stops too close to the price. So if your stop is “too close”, OrderModify fails.
int stopLevel = (int)MarketInfo(Symbol(), MODE_STOPLEVEL);
double minDist = stopLevel * Point;
if(MathAbs(Bid - newSL) < minDist)
{
Print("Stop is too close. Move it farther away.");
}
If you don’t print the error, you won’t know what happened. Always do this:
if(!ok)
{
Print("Failed. Error = ", GetLastError());
}
RefreshRates() before closing/modifyingThat’s it. If you follow those rules, your order code will work way more often.
Click here to return to MQL4 Basics Directory