So it’s time to tell You how to close an open position with the help of the OrderClose() function.
bool OrderClose(int ticket, double lots, double price, int slippage,
color Color=CLR_NONE)
Parameters of the function:
- ticket — ticket of an open position;
- lots — volume in lots;
- price — the closing price of the position;
- slippage — the maximum permissible deviation between price and the server’s price at which the position will be closed;
- arrow_color — the color of closing arrow on the chart. If the parameter is lacking or its value equals to CLR_NONE, the arrow isn’t displayed on the chart.
The OrderClose() function will return true, if a position was closed successfully. If there was an error the function will return false and the error’s code you can get with the help of the GetLastError() function.
It is possible to give a innumerable quantity of practical examples how this function is used as in most Expert Advisors there is a necessity to close positions not only by a Stop Loss or Take Profit order but by the current price as well.
We will consider an expert advisor that closes all open positions and deletes all pending orders on Friday after 10 p.m. (according to the time of the trading platform) as an example of how to use the OrderClose() function.
//+------------------------------------------------------------------+
//| Close everything on Friday.mq4 |
//| Copyright © 2006, Andrey Vedikhin |
//| http://www.vedikhin.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2006, Andrey Vedikhin"
#property link "http://www.vedikhin.ru"
//---- input parameters
extern int MyHour=22;
extern int MyMinute=00;
// 5 - Friday
#define MyDay 5
datetime LastTradeTime;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
// we’ll set yesterday as the time of the last trading operation
LastTradeTime = CurTime()-24*60*60;
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----
// we’ll check whether we haven’t closed all positions today
// if we have - exit
if (TimeDayOfYear(CurTime())==TimeDayOfYear(LastTradeTime)) return(0);
// if it isn't Friaday exit the loop
if (DayOfWeek()!=MyDay) return(0);
// we’ll check whether it’s time to close positions
if (((TimeHour(CurTime())==MyHour)&&(TimeMinute(CurTime())>=MyMinute))
||(TimeHour(CurTime())>MyHour))
{
// we’ll close all positions and delete orders
while (OrdersTotal()>0)
{
// we’ll select the first position or order in the list
if (!OrderSelect(0, SELECT_BY_POS)) break; // in case of a failure exit the loop
// if it is a pending order delete it
if (OrderType()>OP_SELL)
{
if (!OrderDelete(OrderTicket()))
{
Print("Error ", GetLastError()," at deleting a pending order ",
OrderTicket());
break;
}
}
// if it is an open position, close it
else
{
double price;
if (OrderType()==OP_SELL)
price = MarketInfo(OrderSymbol(), MODE_ASK);
else
price = MarketInfo(OrderSymbol(), MODE_BID);
if (!OrderClose(OrderTicket(), OrderLots(), price, 3))
{
Print("Error ", GetLastError()," at closing a position ", OrderTicket());
break;
}
}
// 10 second pause
Sleep(10000);
}
if (OrdersTotal()==0) LastTradeTime = CurTime();
}
//----
return(0);
}
//+------------------------------------------------------------------+
Let’s analyze each line of the Expert Advisor.
First of all this Expert Advisor has several parameters:
extern int MyHour=22;
extern int MyMinute=00;
These parameters have the following meaning:
MyHour and MyMinute — the hour and minute when the expert advisor closes positions and deletes pending orders.
Let me remind you that how to describe parameters of an expert advisor in the code I wrote in the article «External variables».
We declared a global variable LastTradeTime:
datetime LastTradeTime;
With its help we can avoid «triggering» of the expert advisor on each ticket after 22:00, if on that day we closed already all open positions and deleted pending orders.
When we initialize the expert advisor in the init() function we assign the value of yesterday to this variable:
int init()
{
//----
// we’ll set yesterday as the time of the last trading operation
LastTradeTime = CurTime()-24*60*60;
//----
return(0);
}
Let me remind you that the CurTime() function returns the current time in the format datetime.
On each tick the start() function is called, in which we check at first whether we haven’t closed open positions today and haven’t deleted pending orders:
if (TimeDayOfYear(CurTime())==TimeDayOfYear(LastTradeTime)) return(0);
Here the TimeDayOfYear() function is used:
int TimeDayOfYear( datetime date )
This function returns the order number of the day (from the beginning of the year): 1 — January 1, … , 365 or 366 — December 31.
If the order number of the day of the last trading operation — TimeDayOfYear(LastTradeTime) — equals to the order number of the current day — TimeDayOfYear(CurTime()), — it means that we have already deleted orders and closed positions today, that’s why we exit the expert advisor: return(0).
We’ll check if is Friday today:
if (DayOfWeek()!=MyDay) return(0);
The DayOfWeek() function returns the order number of the day of week (Sunday — 0, 1 — Monday, …, 6 — Saturday) the last known time of the server.
Now we’ll check whether it is time to close positions:
if (((TimeHour(CurTime())==MyHour)&&(TimeMinute(CurTime())>=MyMinute))
||(TimeHour(CurTime())>MyHour))
{
...
}
In this portion of the code I have used two new functions:
- int TimeHour(datetime time) — returns the hour for the time time: 0..23;
- int TimeMinute(datetime time) — returns the minute for the time time: 0..59.
Then with the help of the OrderSelect() function we start to select the first position/order in the list trying to close the position or delete the order, and then with the help of the while loop this process is iterated again and again as long as there are open positions or pending orders. Also the loop is broken in case of an error.
It is necessary to have a 10-second pause between trading operations:
Sleep(10000);
The Sleep(int milliseconds) function makes a pause in the work of the Expert Advisor for milliseconds milliseconds (1 second = 1000 milliseconds).
After all positions are closed and all pending orders are deleted we set the current time as the time when the Expert Advisor «triggered» for the last time:
if (OrdersTotal()==0) LastTradeTime = CurTime();
You can see another unknown function in the code of the Expert Advisor — MarketInfo():
double MarketInfo(string symbol, int type)
With the help of this function it is possible to get different kind of information about the instrument symbol. The type of the information depends on the value of the parameter type:
| Constant | Value | Description |
| MODE_LOW | 1 | Minimum price for the day |
| MODE_HIGH | 2 | Maximum price for the day |
| MODE_TIME | 5 | The time when the last quotation came |
| MODE_BID | 9 | The last Bid |
| MODE_ASK | 10 | The last Ask |
| MODE_POINT | 11 | The size of a point in the currency of quotation |
| MODE_DIGITS | 12 | The number of digits after decimal point in the price of the instrument |
| MODE_SPREAD | 13 | Spread in points |
| MODE_STOPLEVEL | 14 | Minimum permissible level of a stop-loss/take-profit in points |
| MODE_LOTSIZE | 15 | The size of the contract in the base currency of the instrument |
| MODE_TICKVALUE | 16 | The size of the minimum change of the instrument’s price in the currency of the quotation |
| MODE_TICKSIZE | 17 | The minimum change of the instrument’s price in points |
| MODE_SWAPLONG | 18 | Storage for long positions |
| MODE_SWAPSHORT | 19 | Storage for short positions |
| MODE_STARTING | 20 | The date of the beginning of trading in the instrument (for futures) |
| MODE_EXPIRATION | 21 | The date of termination of trading in the instrument (for futures) |
| MODE_TRADEALLOWED | 22 | Flag of allowing trading in the instrument |
| MODE_MINLOT | 23 | Minimum size of a lot |
| MODE_LOTSTEP | 24 | Step of change of the lot’s size |
| MODE_MAXLOT | 25 | Maximum lot’s size |
Next article: "
The OrderCloseBy function"