Why it opens orders 10 pips higher than price? It executes them as wel....

 

Hello everyone, i have a problem with this ea. I think the images can explain themselves.

//+------------------------------------------------------------------+
//|                                                  Momentum_v1.mq4 |
//|                                                             Skox |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Skox"
#property link      ""
#property indicator_separate_window

double Punto;
extern bool DisplayInfo=true;
extern string    S1 ="Lotti da aprire, minimo 0.02 ";
extern double BE=15;
extern double Lotti=0.02;
extern string    S2 ="Numero posizioni massime. Minimo 2";
extern int NPosMax=2;
static double trl;

extern double TrailingStop = 7;
static int ticketTL, ticketTL2;
string Cross;


int TF,i;
string cmt;
datetime Time_0;


extern int MagicNumber=987569;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
Time_0=Time[0];

// Compatibility wiht 3,4,5 digits prices
   
   if(Digits>=4) Punto = 0.0001;
   else Punto = 0.01;

//----Gestione TimeFrame, =1 fino a 4h, =2 oltre
if (Period()<=240) TF=1;
else TF=2;
Cross=Symbol();

  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
 //---Stampa informazioni su CHART
   void PrintInfo;
   {
   bool setupBAR;
   string cmt="";
      cmt = "========================";
      cmt =  cmt + "\nAccount Name: [ " + AccountName() + " ]";            
      cmt =  cmt + "\nAccount Leverage: [ " + DoubleToStr( AccountLeverage(), 0 ) + " ]";      
      cmt =  cmt + "\nMin Lot: [ " + DoubleToStr( MarketInfo(Symbol(),MODE_MINLOT), 3 ) + " ]";      
      cmt =  cmt + "\nLot Step: [ " + DoubleToStr( MarketInfo(Symbol(),MODE_LOTSTEP), 3 ) + " ]";      
      cmt =  cmt + "\nCurrent Profit: [ " + DoubleToStr(AccountEquity()-AccountBalance(),2) + " ]";
      cmt =  cmt + "\nAccount Balance: [ " + DoubleToStr(AccountBalance(),2) + " ]";
      cmt =  cmt + "\nAccount Equity: [ " + DoubleToStr(AccountEquity(),2) + " ]";      
      cmt =  cmt + "\n========================";
      Comment(cmt);
      }

//---Indicatori      
   double Atr=iATR(NULL,0,20,0);
   double fastMA=iMA(NULL,0,20,0,MODE_SMA,PRICE_CLOSE,0);
   double slowMA=iMA(NULL,0,40,0,MODE_SMA,PRICE_CLOSE,0);
   double Adx=iADX(NULL,0,14,PRICE_CLOSE,MODE_MAIN,0);

//---Funzione Buffer
  double buffer;
  if (TF==1) buffer=2*Punto;
  else buffer=0.001*Close[0];
  


//--- verifica la presenza di ordini
  int  ordtot=OrdersTotal()-1;   
   for(i=ordtot;i>=0;i--){   
      OrderSelect(i,SELECT_BY_POS);
      //--- c'è un ordine di questo EA     
      if(OrderMagicNumber()==MagicNumber && OrderSymbol()==Cross) Gestisci();
   }      
   
   
//--- Se setup bar esiste setupBAR=true, altrimenti false  

   if (Low[1]>fastMA && Low[1]>slowMA && Close[1]>Open[1] && Close[1]>(High[1]-Low[1])*0.7 && High[1]<High[iHighest(Symbol(),0,MODE_HIGH,5,1)] && (Close[1]-Open[1])<1.5*Atr && Adx>25) 
     {setupBAR = true;}
   else{setupBAR = false;}

//--- Se il targetprofit non viene raggiunto entro 5 candele, la posizione si chiude al close della 5°  
   double prezzo;
   
   
   if(OrderType()==OP_BUY) prezzo=Ask;
   else prezzo=Bid;
   
//---Gestione stoploss. Prima di piazzarlo in reale ricordarsi di cambiare 10 pips con MarketInfo(Symbol(),MODE_STOPLEVEL)
   double StopLoss=20*Punto;
   if(Close[1]-(Low[1]-buffer)<15*Punto)
   {StopLoss=Low[1]-15*Punto;}
   else StopLoss=(Low[1]-buffer);


//--- Controllo numero ordini
   double Spread=Bid-Ask;
   ordtot=OrdersTotal();
   int ticket;
//---Gestione TrailingStop. La variabile TrailingStop è external. Trailing è il nuovo livello di stoploss per ordini con trailingstop 
   double TSTP=TrailingStop*Punto;
  // double Trailing;
   
//---Gestione ordini e modifica di trailingstop e targetprofit 
   if(ordtot<NPosMax)
     {
       if (setupBAR==true && !New_Bar())
         {
           ticket=OrderSend(Symbol(),OP_BUY,Lotti/2,prezzo,3,StopLoss,prezzo+Atr,"Momentum Method",MagicNumber,0);
             OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
               
            ticketTL=OrderSend(Symbol(),OP_BUY,Lotti/2,prezzo,3,prezzo-TSTP,0,"Momentum Method",MagicNumber,0);
            OrderSelect(ticketTL,SELECT_BY_TICKET,MODE_TRADES);
           
           

         }
   }
   
}

 //*** gestisce gli ordini aperti
int Gestisci(){
   static double trl;
   double przopen= OrderOpenPrice();
   double sl= OrderStopLoss();
   double tp= OrderTakeProfit();
   double lotti= OrderLots();
   datetime open=OrderOpenTime();
  
   
   // ordine BUY
   if(OrderType()==OP_BUY){
      double prezzo=Bid;
   
      // dopo 5 candele chiude l'ordine
      if(Time[0]>open+(TF*60)*4){
         if(!OrderClose(OrderTicket(),lotti,prezzo,3,Yellow))
            Print("Errore chiusura totale OP_BUY # "+GetLastError());
         return(0);
      }
      
      // porta l'ordine in breakeven
      if(sl<przopen){
         if((Bid-przopen)>=BE)
            if(!OrderModify(OrderTicket(),przopen,przopen,tp+BE,0)) 
               Print("Errore modifica Breakeven BUY # "+GetLastError());                                                                     
         return(0);
      }
      
      // chiude la prima parte dell'ordine         
      if(lotti==Lotti){
         if((tp-BE)<=Bid){
            if(!OrderClose(OrderTicket(),lotti/2,prezzo,3,Yellow))
               Print("Errore 1^ chiusura OP_BUY # "+GetLastError());
            else trl=Bid-TrailingStop;   
         }         
         return(0);
      }
      
      // gestisce il trailing
      if(Bid<=trl){
         if(!OrderClose(OrderTicket(),lotti,prezzo,3,Yellow))
            Print("Errore 2^ chiusura OP_BUY # "+GetLastError());
      }else 
      if((Bid-TrailingStop)>trl) trl=Bid-TrailingStop;      
      return(0);                 
   }   
 } 
                 
   
//---Controlla se è nata una nuova candela
bool  New_Bar(){                                           
    if (Time_0 != Time[0])                                  
      {
      New_Bar = 1; 
      NoTradeFlag=false;                                             
      Time_0 = Time[0]; 
      }   
}
  
 
The strategy tester can only buy at the current price, regardless of how the EA is coded. Remember that the bars are of BID price. A long position starts from the ASK price. I would suggest the spread is quite high for that simulation.
 

Did you make this picture with backtesting after the market had closed ?

In that case look to the spread of your broker this moment....

 
Thanks both.. I did the backtest when markets were still open. How can i fix this?
 
lemming78:
Thanks both.. I did the backtest when markets were still open. How can i fix this?

make a printstatement to see what is your spread " double Spread=Bid-Ask; "
Print("Spread ",Spread);
 
I may have found the problem. In the expert properties in the backtest section the spread is 100... so 10 pips, but i can't modify it...
 
yes i tried also with your strategy devries, but it returns 0.001. So 10 pips...
 

There are tools to set the spread, they have been mentioned recently . . .

https://www.mql5.com/en/forum/138405 and https://www.mql5.com/en/forum/138459 you can get SpreadGenerator here: SpreadGenerator the instructions are in the script, open in MetaEditor and read carefully.

 
Thanks, another question. Why is it closing anyway positions in the next bar? Stoploss has not been reached yet.
 
lemming78:
Thanks, another question. Why is it closing anyway positions in the next bar? Stoploss has not been reached yet.
Why is it closing orders ? what does it say in the History ?
 

Solved that problem too, there was an error in the code.

Last thing and then i fixed this ea..

Everytime the setupbar condition is true it opens too many positions (300-400)... how to fix this? There's no difference in putting an

double ordtot=OrdersTotal();
if(ordtot<NPosMax){blabla}

or not...

i tried also with a for

for(ordtot=0;ordtot<NPosMax;ordtot++)

but with no results... I temporary solved writing 0 instead of MagicNumber, but the ea needs it...

 for(ordtot=0;ordtot<NPosMax;ordtot++){    
      /* if (setupBARb==true && !New_Bar())
         {
           ticket=OrderSend(Symbol(),OP_BUY,Lotti/2,prezzo,3,Low[1]-buffer,prezzo+Atr,"Momentum Method",0,0);
             OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
                           
            ticketTL=OrderSend(Symbol(),OP_BUY,Lotti/2,prezzo,3,Low[1]-buffer,0,"Momentum Method",0,0);
            OrderSelect(ticketTL,SELECT_BY_TICKET,MODE_TRADES);}*/
       if (setupBARs==true && !New_Bar()) 
         
         {    
           ticket=OrderSend(Symbol(),OP_SELL,Lotti/2,prezzo,3,prezzo+StopLoss*Punto,prezzo-Atr,"Momentum Method",MagicNumber,0,Green);
             OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
             
             
                           
            /*ticketTL=OrderSend(Symbol(),OP_SELL,Lotti/2,prezzo,3,0,0,"Momentum Method",0,0);
            OrderSelect(ticketTL,SELECT_BY_TICKET,MODE_TRADES);*/} 
        
        }
   }
Reason: