It's essential to control the number of trades an EA opens, especially if you want to limit the exposure of your account to the market. By default, an EA can open multiple trades unless you code it to behave differently. Let's explore how to prevent your EA from opening more than one trade at a time.
OrdersTotal()
FunctionThe quickest way to check if there are any open orders is by using the OrdersTotal()
function. This function returns the number of market and pending orders.
if (OrdersTotal() == 0) {
// Place your trade here
}
If you're running EAs on multiple currency pairs, you might want to ensure that the EA only checks trades for the specific symbol it's running on:
//put this before the Ontick() Function
int OrdersForCurrentSymbol() {
int count = 0;
for (int i = 0; i < OrdersTotal(); i++) {
if (OrderSelect(i, SELECT_BY_POS) && OrderSymbol() == Symbol()) {
count++;
}
}
return count;
}
OnTick(){
if (OrdersForCurrentSymbol() == 0) {
// Place your trade for the current symbol
}
}
If you want to ensure that there's only one Buy or Sell order, you can further refine the check:
int OrdersForCurrentSymbolAndType(int type) {
int count = 0;
for (int i = 0; i < OrdersTotal(); i++) {
if (OrderSelect(i, SELECT_BY_POS) && OrderSymbol() == Symbol() && OrderType() == type) {
count++;
}
}
return count;
}
OnTick(){
if (OrdersForCurrentSymbolAndType(OP_BUY) == 0) {
// Place your Buy order for the current symbol
}
if (OrdersForCurrentSymbolAndType(OP_SELL) == 0) {
// Place your Sell order for the current symbol
}
}
Limiting your EA to open only one trade at a time can be an effective risk management strategy. Through simple checks and filtering methods, you can ensure that your trading robot behaves according to your desired trading approach.
Click here to return to MQL4 Basics Directory