Need simple MQL4 help, How to prevent re-entry on same bar?

Hi guys,

I am a super beginner at MQL4, and I am actually using an online EA Builder - StrategyTune (strategytune.com/app/) to make my EA.

I am very happy with what I can do with it so far, but I met with a problem with my EA.

I am trying to make a very simple EA.

Timeframe: Daily

The rules are:
[ul]
[li]Price goes up by 1% from low of the day, Sell TP20 SL20
[/li][li]Price goes down by 1% from high of the day, Buy TP20 SL20
[/li][/ul]

I have made the EA, and the entry and exit is correct.

But my problem is that after the EA exit a trade, it will enter into another trade. While I only want it to trade once within a day.

So my question is: What code do I need to add to prevent an EA from re-entering a trade on the same bar? keeping it to 1 trade only per bar?

Thank You in advance for any of your help!

use a global variable that saves the traded bars time, check it before entring a trade, like example below:

datetime LastBarTraded = 0;

int start() {

… some code of the ea …

if (trade conditions met)
{
if (LastBarTraded != Time[0])
{
//send your order here

           LastBarTraded = Time[0];   // Set the time of the traded bar
      }
}

}

may the pips be with you

I wrote a short tutorial that walks through how to prevent reentry on a single bar that you might find interesting. There is also a downloadable demo that shows how to put together a simple RSI based EA. The basic steps are summarized below. Good luck!

One trade per bar on a forex MT4 EA

To recap, if you wish to limit processing of a certain block of MQL4 code to only once per bar do the following:
Declare a module level variable of type integer.
Place a conditional if block around the block of code you would like to limit and check for inequality (!=) of your module level variable with Bars.
Within the conditional if block, set your module level variable equal to Bars.

How to create a simple MT4 expert advisor that trades once per bar (code included).

Thank You. Your site is very helpful, I have bookmarked it.

Rather then using global variables you could check the orders using iTime

int OpenOrdersPerBar()
   {
      int orders=0;
      if(OrdersTotal()>0)
        {
         for(i=OrdersTotal()-1;i>=0;i--)
           {
            OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
            if(OrderOpenTime()>iTime(NULL,0,0))orders++;
           }
      return(orders);
        }
   }
int ClosedOrdersPerBar()
   {
      int orders=0;
      if(OrdersTotal()>0)
        {
         for(i=OrdersTotal()-1;i>=0;i--)
           {
            OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
            if(OrderOpenTime()>iTime(NULL,0,0))orders++;
           }
      return(orders);
        }
   }
1 Like