200 orders launched, How to fit to only 1?

 

As you can see on the pictures, i've coded a script that buy when SMA CROSSUP and SELL when SMA CrossDown.

However, when i launch the backtests, it first launch 200 trades (BUY or SELL Depending on conditions) and then,the code executes normally except that I then end up with 199 trades which remain open and will not be closed due to the fact that my code only closes one trade for each condition met, and one by one. (see the photo with the list of trades)

How can I avoid to have so many orders launched on the beginning of the backtest?

#include "FONCTIONS.mq4"

void OnTick()
{
//------------------------------------------
   

   if (SMACrossUP()==true)
    { 
    BUY();                
    CloseSELLTrade();
    
}
//---------------------------------------
else
 

if (SMACrossDOWN()==true)
  {
CloseBUYTrade();
SELL();
   }
}
//-------------------------------------------
            
Files:
Order_Many.PNG  10 kb
OrderLists.PNG  260 kb
 

As you can see on this pictures, the conditions are not even met (no crossover), the SMA200 (red) has not even appeared yet (why?), the robot has already launched 200 trades.


*the red bar corresponds to the moment when I sent the backtest*

Files:
Conditions.PNG  39 kb
 
   if (SMACrossUP()==true)

You are acting on a signal. That signal will be true for an entire bar.

  1. Either check once per bar.

    For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
              MT4: New candle - MQL4 programming forum #3 (2014)
              MT5: Accessing variables - MQL4 programming forum #3 (2022)

    I disagree with making a new bar function, because it can only be called once per tick (second call returns false). A variable can be tested multiple times.
              Running EA once at the start of each bar - MQL4 programming forum (2011)

  2. Or, Act on a change of signal.
              Too many orders - MQL4 programming forum #1 (2017)
 

Maybe this will be closer to what you want?


#include "FONCTIONS.mq4"

void OnTick()
{
//------------------------------------------
   

   if (SMACrossUP()==true)
    { 
     if (OrdersTotal() == 1) {
        OrderSelect(1, SELECT_BY_POS, MODE_TRADES);
        if (OrderType() == 1) {
           BUY();                
           CloseSELLTrade();
        }
     }
}
//---------------------------------------
else
 

if (SMACrossDOWN()==true)
  {
     if (OrdersTotal() == 1) {
        OrderSelect(1, SELECT_BY_POS, MODE_TRADES);
        if (OrderType() == 0) {
           CloseBUYTrade();
           SELL();
        }
     }
}
//-------------------------------------------