Functions in MQL 4 for closing positions - The #1 Blog on trading, personal investing! Best Tips for Beginners

Header Ads

Functions in MQL 4 for closing positions

User may want to close order if wanted conditions are met. You can achieve this with OrderClose(...) function. This function also creates a ticket number to show user if the closing operation is successfull or not. Value greater than 0 show the operation is successfull while -1 shows there were an error occured during closing process.
bool OrderClose(
   int ticket,                           // ticket number
   double lots,                          // lot size
   double price,                         // close price
   int slippage,                         // slippage
   color arrow_color                     // color
   );
Parameters
Ticket: [in]  Unique number of the order ticket.
Lots: [in]  Number of lots.
Price: [in]  Closing price.
Slippage: [in]  Value of the maximum price slippage in points.
arrow_color: [in]  Color of the closing arrow on the chart. If the parameter is missing or has CLR_NONE value closing arrow will not be drawn on the chart.
Returned value
Returns true if successful, otherwise false. To get additional error information, one has to call the GetLastError() function.
You can see how to close an order according to its type;
OrderSelect(closingTicket, SELECT_BY_TICKET);

if(OrderCloseTime() == 0 && OrderType() == OP_BUY)
{
double lotSize = OrderLots();
double closePrice = Bid;
bool Closed = OrderClose(closingTicket, lotSize, closePrice, slippage, Red);
}


if(OrderCloseTime() == 0 && OrderType() == OP_SELL)
{
double lotSize = OrderLots();
double closePrice = Ask;
bool Closed = OrderClose(closingTicket, lotSize, closePrice, slippage, Red);
}

For pending orders because it has not been opened there is no close operation. In order the cancel pending order OrderDelete(...) function can be used. Similarly this function also returns a ticket number which shows the process is successfull or not.
bool OrderDelete(
   int ticket,        // ticket number
   color arrow_color  // color
   );

Parameters
Ticket: [in]  Unique number of the order ticket.
arrow_color: [in]  Color of the arrow on the chart. If the parameter is missing or has CLR_NONE value arrow will not be drawn on the chart.
Returned value
If the function succeeds, it returns true, otherwise false. To get the detailed error information, call the GetLastError() function.

OrderSelect(closingTicket, SELECT_BY_TICKET);
if(OrderCloseTime() == 0 && OrderType() == OP_BUYSTOP)
{
    bool Deleted = OrderDelete(closingTicket, Red);
}