EA not opening trades at expected event

 

Backtesting an idea using Parabolic SAR. I was expecting the trade to open at the open of the new bar when the signal switches, but it doesn't. It is late and inconsistent. And it is not just the difference in the spread. I can't seem to find anything in the code that prevents it from opening the trade at the correct moment.

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>


//+------------------------------------------------------------------+
//| Global Variables                                |
//+------------------------------------------------------------------+


bool NewBar;

CTrade trade;
CPositionInfo position;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {

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

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

//Get the Ask and Bid prices
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);


// create the PSar
   int psarHandle;
   double PSarBuffer[];

   psarHandle = iSAR(_Symbol,PERIOD_CURRENT,0.02,0.2);

   ArraySetAsSeries(PSarBuffer,true);

// collects data from the PSar
   int PSarSequence = CopyBuffer(psarHandle,0,0,3,PSarBuffer);
   double CurrentSar = NormalizeDouble(PSarBuffer[0],3);
   double PreviousSar = NormalizeDouble(PSarBuffer[1],3);

//Create an array for the prices
   MqlRates PriceInfo[];

//Sort the price array from current candle downwards
   ArraySetAsSeries(PriceInfo,true);

//Fill the array with the price data
   int PriceData = CopyRates(_Symbol,PERIOD_CURRENT,0,3,PriceInfo);

   Comment("PSAR [0]:",CurrentSar,"\n",
           "PSAR [1]:",PreviousSar,"\n",
           " Open[1]:",PriceInfo[1].open,"\n",
           " Close[1]:",PriceInfo[1].close,"\n",
           "  High[1]:",PriceInfo[1].high,"\n",
           "  Low[1]:",PriceInfo[1].low);

//Check for PSAR reversal
//Buy condition
   if(PreviousSar>PriceInfo[1].high &&
      PriceInfo[1].close>PriceInfo[1].open &&
      CurrentSar<PriceInfo[0].open &&
      (PositionsTotal()==0))
     {

      trade.Buy(0.01,_Symbol,Ask,PriceInfo[1].low,0,NULL);
     }
//Sell condition
   if(PreviousSar<PriceInfo[1].high &&
      PriceInfo[1].close<PriceInfo[1].open &&
      CurrentSar>PriceInfo[0].open &&
      (PositionsTotal()==0))
     {

      trade.Sell(0.01,_Symbol,Bid,PriceInfo[1].high,0,NULL);
     }

//Close trade at the beginning of a new bar

   static datetime dtBarCurrent = WRONG_VALUE;
   datetime dtBarPrevious = dtBarCurrent;
   dtBarCurrent = iTime(_Symbol,PERIOD_CURRENT,0);
   NewBar = (dtBarCurrent != dtBarPrevious);

   if(NewBar)
     {
      // Manage existing trades
      for(int i = PositionsTotal() - 1; i >= 0; i--)
        {
         ulong ticket = PositionGetTicket(i);
         if(ticket != 0 && PositionSelectByTicket(ticket))
           {
            trade.PositionClose(ticket,-1);
           }
        }
     }


  }


//+------------------------------------------------------------------+
 
If you place the handle definition in OnTick, a new handle reference is made every single tick, you shouldn't do that. Put both the iSAR and ArraysSetAsSeries in OnInit(). Make "psarHandle" a global variable. Leave copybuffer in OnTick. Realize that parabolic sar can repaint. You might need bar confirmation logic to validate the start of a new trend
 
Conor Mcnamara #:
If you place the handle definition in OnTick, a new handle reference is made every single tick, you shouldn't do that. Put both the iSAR and ArraysSetAsSeries in OnInit(). Make "psarHandle" a global variable. Leave copybuffer in OnTick. Realize that parabolic sar can repaint. You might need bar confirmation logic to validate the start of a new trendThank you 

Thank you, I will try that. Could you explain or pass on a reference about bar confirmation logic?

 
Looks like the problem is the parabolic sar is repainting. Not sure how to work around that , lol.
 

bar confirmations can be handled in multiple different ways, it could be as simple as changing [0] and [1] indexes to [1] and [2]


I would avoid doing this in the trade logic as well:

  PriceInfo[1].close<PriceInfo[1].open 
 PriceInfo[1].close>PriceInfo[1].open

You don't need to make sure the candle is red for a sell position, or that the candle is green for a buy position. Because even when there's a buy trend on the PSAR, you will see some prior red candle, and you don't want to miss the trade opportunity on it - instead you want to believe in the trend