Close positions and pending orders on a new bar.

 
Hello everyone, I am coding my first expert advisor, and I have encountered some issues with mine. The first one is that I can't code the EA to close the pending orders or open positions when a new bar appears. The EA is coded to open place one pending order per bar and when the bar close I want it to cancel the pending order of the bar or the open position of the bar at the same time, without affecting the new pending order that will be placed on the bar[0].  Here's the code
Please i'm a newbie don't mind about the other errors lol. 



#include <Trade\Trade.mqh>
CTrade trade;
int handleEma;
int barstotal;
bool newbar;
datetime lastbartime;
MqlRates bar[];

//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
    barstotal = iBars(_Symbol,PERIOD_CURRENT);
    handleEma = iMA(_Symbol,PERIOD_CURRENT,10,0,MODE_EMA,PRICE_CLOSE);
    ArraySetAsSeries(bar,true);
  
//---
   return(INIT_SUCCEEDED);
  }



void OnDeinit(const int reason)
  {
//---
   
  }



void OnTick()
  {
    
        
        double high = iHigh(_Symbol,PERIOD_CURRENT,1);
        double low = iLow(_Symbol,PERIOD_CURRENT,1);
        double close = iClose(_Symbol,PERIOD_CURRENT,1);
        double open = iOpen(_Symbol,PERIOD_CURRENT,1);
        double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
        double upperwick = high - close ;
        double lowerwick = low < close;
        double ema[];
        CopyBuffer(handleEma,MAIN_LINE,1,2,ema);
        CopyRates(_Symbol,PERIOD_CURRENT,0,1,bar);
        
        
         
        
        if(bar[0].time > lastbartime){
        newbar = true;
        lastbartime = bar[0].time;
         closepositions();
         closeorders();
        
        }else {
          newbar= false;
        }
        if (newbar == true) {
        
        // Trade Conditions//
        Alert("New Bar: ", lastbartime);   
        
        
       
        if( close >= open && close > ema[1] ){
         
          double sl= NormalizeDouble(low, _Digits);
          trade.BuyStop(0.1,close+ 1* _Point,_Symbol,sl,0,0);
          Print(" buy nowwwwww");
    
    
        }else if( close <= open && close < ema[1] ){
          
           double sl= NormalizeDouble(high, _Digits);
           trade.SellStop(0.1,close - 1* _Point, _Symbol,sl,0,0);      
           Print(" sell nowwwwww");
    
          }
   
    
    
   
         Comment("\nBid: ", bid,
           "\nHigh: ",high,
           "\nLow: " ,low,
           "\nema[0]: ", DoubleToString(ema[0],_Digits),
           "\nema[1]: ", DoubleToString(ema[1],_Digits));
        
        
        }
        
    
  }


 
the logic to make it work: If the current time minus the position time is greater or equal to the amount of seconds in bar - perform task. 

items to use:
TimeCurrent();
PositionGetInteger(POSITION_TIME);
PeriodSeconds();
 
Conor Mcnamara #:
the logic to make it work: If the current time minus the position time is greater or equal to the amount of seconds in bar - perform task. 

items to use:
TimeCurrent();
PositionGetInteger(POSITION_TIME);
PeriodSeconds();
Sorry I still don't get it, because sometimes, when I run the EA on the 1 minute time frame, the order can be triggered at 40 seconds of the current candle, thus when the current candle is closed, the duration of the order is less then 60 seconds, but for me, I just want it to close not after a predetermined amount of seconds, but only when a new bar shows up. Also, thank you for replying me sir.
 
Well then you could get the actual bar open time instead of the position open time using CopyTime or else iTime with iBarShift. I made a function before that does that. Another approach you could take if you only need the 1 minute timeframe:
if (TimeCurrent() % 60==0){   // do task      }
 

simple working example with CopyTime

datetime lastBarTime = 0;
datetime time_buf[];

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   ArrayResize(time_buf, 1);
   ArraySetAsSeries(time_buf, true);

   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(){


   if (IsNewBarFormed()){
   
   
      Print("New bar opened at ", TimeToString(lastBarTime, TIME_DATE|TIME_MINUTES|TIME_SECONDS));
   }
   
   
   
}


//+------------------------------------------------------------------+
datetime GetCurrentBarTime()
{
   CopyTime(_Symbol, _Period, 0, 1, time_buf);
   return time_buf[0];
}

bool IsNewBarFormed()
{
   datetime currentBarTime = GetCurrentBarTime();

   if (currentBarTime > lastBarTime){
      lastBarTime = currentBarTime;
      return true;
   }
   
   return false;
}
//+------------------------------------------------------------------+
 
Conor Mcnamara #:

simple working example with CopyTime

I tried them in my code, but didn't work, I'll see what I can do. Thank you a lot for giving me some ideas sir 🙏🏾