MetaTrader MQL Course.Module 5: Trade Managing Using OrderSelect

Trade Managing Using OrderSelect

In the last module, we went over how to get the values of any of the MetaTrader technical indicators.  If you’d like to review that module, click here: Using an MT Technical Indicator.

This is an exciting module because we are going to tie in everything we learned from the last 4 modules to build a real, working Expert Advisor.

Actually, we’ve already covered most of what we need: We can get an indicator value and we can open a trade.

The last step we need is a bit subtle: we need to know if we have already opened a trade, so we don’t keep opening trades over and over.

What’s missing is Trade Managing – an understanding what trades are owned by our EA, and therefore, should be managed by our EA.

Some form of Trade Managing is included in almost all Expert Advisors.  I am going to explain it from a high level and then you can refer to the MQL code.  This is worth spending some time to understand. Once you do understand it, you’ll hardly ever think of it again – you’ll just know it.

Every time our EA is called, we need to check and see if we have any trades open.  Remember, a broker can close a trade at any time due to a stoploss or takeprofit – or for many other worse reasons (margin calls, etc). Also, your EA can make a request to open a trade and it can take a while to be filled (a few seconds).

The bottom line: we are never really sure of the status of our trades – we simply must ask the broker every time.

We are going to use the MetaTrader functions OrdersTotal and OrderSelect to find out if our EA has opened any trades.

The OrdersTotal function is pretty darn simple – it just returns the total number of open (or pending) orders for the account. So, you may be wondering, why do we need anything else if OrdersTotal tells us the number of open trades?

The answer is that our EA may not have opened some (or all) of the trades reported by OrdersTotal.  Remember, OrdersTotal returns all open trades for the account – even trades opened manually.

Now, if you are only running one EA, and you won’t be doing any manual trading, then you may be able to get away with using OrdersTotal.  But, if you are like most traders, you’ll need to make a distinction between trades opened by your EA and all other trades.

We’ll use the OrderSelect function – in combination with some other MQL programming functions – to make this determination.

This is an overview of what we’ll do:

  • Get the total number of open trades for the entire account.
  • Look at each trade and check its magic number to see if this EA opened the trade.
  • If our EA has already opened a trade, just exit.  Don’t open another trade.
  • If out EA does not have an open trade, check the entry criteria for opening a trade.

Remember, there are many different ways of doing something in programming, I am going to show you one way.

Along with the OrderSelect function are a bunch of MQL functions for getting just about every piece of information about an open trade. Here is a list:

OrderClosePrice           OrderCloseTime       OrderComment            OrderCommission
OrderExpiration            OrderLots                OrderMagicNumber      OrderOpenPrice
OrderOpenTime           OrderProfit              OrderStopLoss              OrderSwap
OrderSymbol               OrderTakeProfit       OrderTicket                  OrderType

We are only going to use the OrderMagicNumber function in this module, but we’ll use many more in later modules.

This is an overview of our full functioning Expert Advisor:

  • First we use OrdersTotal, OrderSelect and OrderMagicNumber to check for open trades.
  • If there are no trades, we use iRsi to get the RSI values to see if we should open a Buy or Sell Trade.
  • If the RSI dictates we use OrderSend to open a trade.

Here is the MQL code using OrderSelect:

// these are all externs so they can be changed when the EA is attached to a chart
// the values set are default values
extern int stoploss=200;
extern int takeprofit=200;
extern double lots = 1.0;
extern int magic_number=12345;
extern int rsi_period=12;
extern double rsi_buy_level=75.0;
extern double rsi_sell_level=25.0;

int start()
{
// this variable will hold the number of trades open for this EA (as defined by magic number)
int my_trades=0;
// this variable will holds the total number of trades for the entire account
int all_trades=OrdersTotal();

// use a for loop to cycle through all of the trades, from 0 up to all_trades
for( int cnt=0;cnt<all_trades;cnt++ )
{
// use OrderSelect to get the info for each trade, cnt=0 the first time, then 1, 2, .., etc
// if OrderSelect fails it returns false, so we just continue
if( OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) == false )
continue;

// compare the magic_number of our EA (as passed in as an input parameter) to the order’s magic number
// if they are equal, increment my_trades
if( magic_number == OrderMagicNumber() )
my_trades++;
}

// my_trades should either be 1 or 0. if it is greater than zero, then we just exit
if( my_trades > 0 )
return(0);

// get the rsi value
double rsi_value = iRSI(Symbol(), Period(), rsi_period, PRICE_CLOSE, 0);

// if the rsi_value is larger than rsi_buy_level, we open a buy
if(rsi_value > rsi_buy_level)
{
int status =
OrderSend( Symbol(), // the synbol for this chart
OP_BUY, // a buy order
lots, // number of lots
Ask, // use the ask price for a BUY
3, // allow the price up to move 3 points
Ask – (stoploss*Point), // stop
Bid + (takeprofit*Point), // limit
“My Simple EA”, // comment to see in TerminalCompany
magic_number, // a unique # to id this trade
0, // expiration, doesn’t work
Blue // a blue arrow
);

if( status < 0 )
Comment(“OrderSend Failed!! Error=”, GetLastError());

// exit after trying to open a trade
return(0);
}

// if the rsi_value is larger than rsi_buy_level, we open a buy
if(rsi_value < rsi_sell_level)
{
status =
OrderSend( Symbol(), // the synbol for this chart
OP_SELL, // a buy order
lots, // number of lots
Bid, // use the ask price for a BUY
3, // allow the price up to move 3 points
Bid + (stoploss*Point), // stop
Ask – (takeprofit*Point), // limit
“My Simple EA”, // comment to see in TerminalCompany
magic_number, // a unique # to id this trade
0, // expiration, doesn’t work
Red // a blue arrow
);

if( status < 0 )
Comment(“OrderSend Failed!! Error=”, GetLastError());

  // exit after trying to open a trade
  return(0);
  }
 return(0);
}

Paste this code into your MetaEditor.  (It’s much easier to read the code in the MetaEditor because of the color coding.)  Try to understand each line and perhaps change a few lines to see if you truly understand.  This is a simple, but relatively complete EA.  Understanding this EA is a great foundation for more advanced (and more fun) MQL concepts.