Basic Parabolic SAR EA for MT4

To add comments, please log in or register
Alirzen
138
Alirzen  

Hi. I want to build a Basic Parabolic SAR EA and after I write the code and start a backtest, it doesn't work the way it should, or better to say the way i want it to do.

Well i want to open a new trade at the reverse point and also close the last trade too.

here's my code:

void OnTick()

  {

     double sar1 = iSAR(NULL, 0, 0.1, 0.2, 1);

     double sar2 = iSAR(NULL, 0, 0.1, 0.2, 0);

     if (sar1>Open[1] && sar2<Open[0] && OrdersTotal()==0)

     { 

     if (OP_SELL)

      {

      OrderClose(OrderTicket(),0.1,Ask,5,clrNONE);

      }

      OrderSend (_Symbol,OP_BUY,0.1,Ask,5,0,0,NULL,0,0,clrGreen);

      }

     if (sar1<Open[1] && sar2>Open[0] && OrdersTotal()==0)

     {

     if (OP_BUY)

      {

      OrderClose(OrderTicket(),0.1,Bid,5,clrNONE);

      }

      OrderSend (_Symbol,OP_SELL,0.1,Bid,5,0,0,NULL,0,0,clrRed);

     }

  }

Anybody can help me?


P.S. I'm not good at programming very much!

Keith Watford
Moderator
20419
Keith Watford  
 if (OP_SELL)
 if (OP_BUY)

Makes no sense, these are enums, not bools

OrderClose(OrderTicket(),0.1,Ask,5,clrNONE);

You have to select an order before you can use OrderTicket()

lippmaje
1039
lippmaje  
bool CloseMyBuyOrders()
  {
   bool ok=true;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==_Symbol && OrderMagic()==MagicID && OrderType()==OP_BUY)
        {
         if(!OrderClose(OrderTicket(),OrderLots(),Bid,5,clrNONE))
           {
            Print("order ",OrderTicket()," failed to close, error: ",GetLastError());
            ok=false;
           }
        }
     }
   return ok; // true: ok, false: error
  }
You might want to use this function to close your orders instead of if(OP_BUY)... which wouldn't work.
Roman Yablonskiy
1508
Roman Yablonskiy  
Do you really know, classical SAR has lots of missed opportunities?
Alirzen
138
Alirzen  
lippmaje:
You might want to use this function to close your orders instead of if(OP_BUY)... which wouldn't work.

Thanks for your help! I think my problem stands with the whole code, because in my backtest it doesn't buy or sell at the reverse points and also it doesn't close the last order at the second place, which I think you tried to help me with the code provided. As I said I'm not good at programming and I also couldn't find a parabolic sar expert adviser that suits my needs or an easy code that I can change it to suit my needs. If you can help me with the whole code I would be very appreciated. I don't look for a very optional code, I just want a very basic Parabolic SAR function.

Again, thank you! 

Alirzen
138
Alirzen  
Roman Yablonskiy:
Do you really know, classical SAR has lots of missed opportunities?
Well yes I guess, I kinda found it out too, but I think it's about its sensitivity; if you make it more sensitive, it won't let you down in a lower time frame. Well I also think that it shouldn't be used alone and another or more indicators need to be combined with it. Also i'm new to Forex market and I want to try different strategies. But again Thanks for your comment!
lippmaje
1039
lippmaje  

Well, we can assist you in fixing the code but the job is on you. My idea to approach this is simple. 1) Build the signals, 2) Close open trades if opposite signal is set, 3) Open trade according to signal.

So we have something like this:

void OnTick()
  {
   // 1) Build signals
   double sar1 = iSAR(NULL, 0, 0.1, 0.2, 1);
   double sar2 = iSAR(NULL, 0, 0.1, 0.2, 0);
   bool buySignal  = sar1>Open[1] && sar2<Open[0];
   bool sellSignal = sar1<Open[1] && sar2>Open[0];

   // 2) Close trades on opposite signal
   if (sellSignal) CloseMyBuyTrades();
   if (buySignal)  CloseMySellTrades();

   // 3) Open trades on signal
   if (sellSignal && OrdersTotal()==0) OpenSellTrade();
   if (buySignal  && OrdersTotal()==0) OpenBuyTrade();
  }

And that's it. You'll figure out the functions. Next would be to add trailing stop and what not but that's a different story.

Note there are situations where PSAR whipsaws badly.

Alirzen
138
Alirzen  
lippmaje:

Well, we can assist you in fixing the code but the job is on you. My idea to approach this is simple. 1) Build the signals, 2) Close open trades if opposite signal is set, 3) Open trade according to signal.

So we have something like this:

And that's it. You'll figure out the functions. Next would be to add trailing stop and what not but that's a different story.

Thanks again! Well i started programming yesterday. i should've said that I'm not good at programming at all! :) i found a code on the internet that seems to work and edited it to make it basic as much as i could. but it doesn't work either. but there's no errors. 

here's the code:

extern double LotSize=0.1;             //Position size

extern int Slippage=5;                 //Slippage in pips

extern bool TradeEnabled=true;         //Enable trade

extern double PSARStep=0.1;            //PSAR Step         

extern double PSARMaxStep=0.2;        //PSAR Max Step


extern int MagicNumber=11223344;       //Magic Number to assign to the orders


//Functional variables

double ePoint;                         //Point normalized

bool CanOrder;                         //Check for risk management

bool CanOpenBuy;                       //Flag if there are buy orders open

bool CanOpenSell;                      //Flag if there are sell orders open

int OrderOpRetry=10;                   //Number of attempts to perform a trade operation

int SleepSecs=1;                       //Seconds to sleep if can't order

int MinBars=60;                        //Minimum bars in the graph to enable trading


//Functional variables to determine prices

double MinSL;

double MaxSL;

double Spread;

int Slip; 



//Variable initialization function

void Initialize(){          

   RefreshRates();

   ePoint=Point;

   Slip=Slippage;

   if (MathMod(Digits,2)==1){

      ePoint*=10;

      Slip*=10;

   }

  

   CanOrder=TradeEnabled;

   CanOpenBuy=true;

   CanOpenSell=true;

}



//Check if orders can be submitted

void CheckCanOrder(){            

   if( Bars<MinBars ){

      Print("INFO - Not enough Bars to trade");

      CanOrder=false;

   }

   OrdersOpen();

   return;

}



//Check if there are open orders and what type

void OrdersOpen(){

   for( int i = 0 ; i < OrdersTotal() ; i++ ) {

      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false ) {

         Print("ERROR - Unable to select the order - ",GetLastError());

         break;

      } 

      if( OrderSymbol()==Symbol() && OrderType() == OP_BUY) CanOpenBuy=false;

      if( OrderSymbol()==Symbol() && OrderType() == OP_SELL) CanOpenSell=false;

   }

   return;

}



//Close all the orders of a specific type and current symbol

void CloseAll(int Command){

   double ClosePrice=0;

   for( int i = 0 ; i < OrdersTotal() ; i++ ) {

      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false ) {

         Print("ERROR - Unable to select the order - ",GetLastError());

         break;

      }

      if( OrderSymbol()==Symbol() && OrderType()==Command) {

         if(Command==OP_BUY) ClosePrice=Bid;

         if(Command==OP_SELL) ClosePrice=Ask;

         double Lots=OrderLots();

         int Ticket=OrderTicket();

         for(int j=1; j<OrderOpRetry; j++){

            bool res=OrderClose(OrderTicket(),LotSize,ClosePrice,Slippage,clrRed);

            if(res){

               Print("TRADE - CLOSE - Order ",Ticket," closed at price ",ClosePrice);

               break;

            }

            else Print("ERROR - CLOSE - error closing order ",Ticket," return error: ",GetLastError());

         }

      }

   }

   return;

}



//Open new order of a given type

void OpenNew(int Command){

   RefreshRates();

   double OpenPrice=0;

   double SLPrice;

   double TPPrice;

   if(Command==OP_BUY){

      OpenPrice=Ask;

     

   }

   if(Command==OP_SELL){

      OpenPrice=Bid;

      

   }

   for(int i=1; i<OrderOpRetry; i++){

      int res=OrderSend(Symbol(),Command,LotSize,OpenPrice,Slippage,0,0,"",MagicNumber,0,Green);

      if(res){

         Print("TRADE - NEW - Order ",res," submitted: Command ",Command," Volume ",LotSize," Open ",OpenPrice," Slippage ",Slip," Stop ",SLPrice," Take ",TPPrice);

         break;

      }

      else Print("ERROR - NEW - error sending order, return error: ",GetLastError());

   }

   return;

}



//Technical analysis of the indicators

bool CrossToOpenBuy=false;

bool CrossToOpenSell=false;



void CheckPSARCross(){

   CrossToOpenBuy=false;

   CrossToOpenSell=false;

   double PSARCurr=iSAR(Symbol(),0,PSARStep,PSARMaxStep,0);

   double PSARPrev=iSAR(Symbol(),0,PSARStep,PSARMaxStep,1);

   if(PSARCurr<Close[0] && PSARPrev>Close[1]){

      CrossToOpenBuy=true;

   }

   if(PSARCurr>Close[0] && PSARPrev<Close[1]){

      CrossToOpenSell=true;

   }

}



Can you see any problem?

lippmaje
1039
lippmaje  
Please post your code in appropriate style. Check for yourself and come back if there's a problem you need to fix. The ideas discussed here so far are sound and if you need experience to tackle the details there's always the freelance section. You might want to check the error code and sleep a second before retrying, there's no sense in retrying when balance is insufficient.
William Roeder
20214
William Roeder  
Alirzen: Can you see any problem?
  1. Please edit your (original) post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
              Messages Editor

  2. Yes

Alirzen
138
Alirzen  
William Roeder:
  1. Please edit your (original) post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
              Messages Editor

  2. Yes

Hi. Thanks for your reply. I found this strategy useless. So I'll give up on it. But still thanks for your reply.

Could you please check my last topic here https://www.mql5.com/en/forum/319106? I recently built an strategy of my own, and i need to make an EA of it but i have a problem. Could you please help me?

How To Check Previous candles in EA Creation?
How To Check Previous candles in EA Creation?
  • 2019.08.01
  • www.mql5.com
Hi friends. I hope that you are fine. I built an strategy and I want to make an EA of it...
12
To add comments, please log in or register