Need help with EA.

cyxstudio

Trader
Jan 31, 2013
6
0
12
I have made at least 10 different EAs and none of them works. I = am sorta giving up trying. Anyone here that is good with this stuff would you please write an example EA so that i could learn from it.

conditions :

1. Open buy position when 2 Day RSI index is below 5 AND Ask price is above 200 Day moving average.

2. Close buy position when Ask price is above 5 Day moving average.

3. Open sell position when 2 Day RSI is above 95 AND Bid price is below 200 Day moving average

4. Close sell position when Bid price is below 5 day moving average.

picture for guidance

OJh4Zs1.jpg

WRE30Ku.jpg


My own attempt. LOL

MQL4:
//+------------------------------------------------------------------+
//|                                                My Strategy 4.mq4 |
//|                        Copyright 2013, MetaQuotes Software Corp. |
//|                                        [url]http://www.metaquotes.net[/url] |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"
 
extern double StopLoss = 40;
extern double TakeProfit = 40;
extern double Lots = 0.1;
extern double Slippage = 5;
extern double RSINow;
extern double MA200;
extern double MA5;
extern bool A1 = false;
extern bool A2 = false;
extern int Ticket;
extern int Ticket2;
 
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+ 
int init()
  {
//----
   Alert("Minimum Stop Level is " + MarketInfo(Symbol(), MODE_STOPLEVEL)); //find out minimum stop loss
 
   RSINow = iRSI(NULL, 1440, 2, PRICE_CLOSE, 0);
   MA200 = iMA(NULL, 1440, 200, 0, MODE_SMA, PRICE_CLOSE,0);
   MA5 = iMA(NULL, 1440, 5, 0, MODE_SMA, PRICE_CLOSE,0);
   Alert(RSINow);
   Alert(MA200);
   Alert(MA5);
 
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
 
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
 
 
   RSINow = iRSI(NULL, 1440, 2, PRICE_CLOSE, 0);
   MA200 = iMA(NULL, 1440, 200, 0, MODE_SMA, PRICE_CLOSE,0);
   MA5 = iMA(NULL, 1440, 5, 0, MODE_SMA, PRICE_CLOSE,0);
 
 
   //check if a long position is possible
   if (A1 == false && RSINow < 5 && Ask > MA200) {
 
   Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, Bid - ( StopLoss * Point ), Ask + ( TakeProfit * Point ));
 
   if(Ticket>0) {
            if(OrderSelect(Ticket,SELECT_BY_TICKET,MODE_TRADES)) {
               Print("BUY order opened : ",OrderOpenPrice());
               A1 = true;
           }
         if (Ticket < 0) {
         Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
   }
   }
   } 
 
 
 
   //check if a short position is possible
   if (A2 == false && RSINow > 95 && Bid < MA200) {
 
   Ticket2 = OrderSend(Symbol(), OP_BUY, Lots, Bid, Slippage, Ask + ( StopLoss * Point ), Bid - ( TakeProfit * Point ));
   if(Ticket2>0) {
            if(OrderSelect(Ticket2,SELECT_BY_TICKET,MODE_TRADES)) {
               Print("SELL order opened : ",OrderOpenPrice());
               A2 = true;
           }
         if (Ticket2 < 0) {
         Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
         }
   }
 
   } 
 
 
   //check if buy position can be closed
 
   if ((A1 == true) && (Ask > MA5)) {
   OrderClose(Ticket, Lots, Bid, Slippage, Violet);
   A1 = false;
   return(0);
   }
 
 
 
 
   //check if sell position can be closed
 
   if ((A2 == true) && (Bid < MA5)) {
   OrderClose(Ticket2, Lots, Bid, Slippage, Violet);
   A2 = false;
   return(0);
   }
 
//----
   return(0);
  }
//+------------------------------------------------------------------+
 
Last edited by a moderator:

Enivid

Administrator
Staff member
Nov 30, 2008
16,046
818
144
Odessa
www.earnforex.com
What happens when you test that EA?

Here are some hints to improve your code:
  • Use brackets around each condition inside complex "if" statements.
  • Take-profit should be based on Bid for Buy orders and on Ask for Sell orders.
  • When you OrderClose() a sell order, you need to use Ask price.
  • Use RefreshRates() before referencing Ask/Bid. It is usually enough to call it once in the beginning of the start() function.
  • If your broker uses 5 digits after dot in quotes, then your stop-loss, take-profit and slippage parameters' default values are too low.
  • And you attach it to daily chart, right?
 

cyxstudio

Trader
Jan 31, 2013
6
0
12
What happens when you test that EA?

Here are some hints to improve your code:
  • Use brackets around each condition inside complex "if" statements.
  • Take-profit should be based on Bid for Buy orders and on Ask for Sell orders.
  • When you OrderClose() a sell order, you need to use Ask price.
  • Use RefreshRates() before referencing Ask/Bid. It is usually enough to call it once in the beginning of the start() function.
  • If your broker uses 5 digits after dot in quotes, then your stop-loss, take-profit and slippage parameters' default values are too low.
  • And you attach it to daily chart, right?

when i test it. 2 problems happen . first the EA only execute buy but not sell. i have added the sell section into my script. but its impossible in 1 months backtesting period, only buy has been executed and no sell.

secondly, i am making negative profit when i backtest it. It shouldnt be so. i have seen someone writing the script for the same strategy but he made good profit.

please tell what is wrong with my code!!!
 

cyxstudio

Trader
Jan 31, 2013
6
0
12
i improed my code again. this is the latest one

Code:
//+------------------------------------------------------------------+
//|                                       RSI_strategy_cyxstudio.mq4 |
//|                                  Copyright 2013, Tjipke de Vries |
//|                                     http://forum.mql4.com/53695/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"
#include 
#include 


extern int RSIPeriod        =  2;      //number of periods for RSI
extern double UpperBound    =  95;     //set upper bound value for RSI
extern double LowerBound    =  5;      //set lower bound value for RSI

extern double Lots  = 0.1;
extern double StopLoss      = 120;       //Set the stop loss level
extern double TakeProfit    = 120;       //Set the take profit level
extern double TrailingStop = 40;
//extra settings for OrderSend
extern int        MagicNumber = 54333;
extern string     CommentEA = "RSI strategy";
extern int        Slippage.Pips    = 10;



//---
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----   
  Alert(OrdersTotal());

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
RefreshRates();
   int Ticket1;
   int Ticket2;
   bool Ticket3;
   bool Ticket4;
   
   double SL,TP;
   int Total;
   double MagicNo;
   double Slippage;
    int cnt;
   
   double pAsk = MarketInfo(Symbol(), MODE_ASK);
   double pBid = MarketInfo(Symbol(), MODE_BID);
   double MA200 = iMA(NULL, 1440, 200, 0,MODE_SMA,PRICE_CLOSE, 0);  //200 day Moving Average   
   double MA5 = iMA(NULL, 1440, 5, 0,MODE_SMA,PRICE_CLOSE, 0);      //  5 day Moving Average
   double CurrentRSI = iRSI (NULL, 0, RSIPeriod,PRICE_CLOSE ,0);
   double PrevRSI =  iRSI (NULL, 0, RSIPeriod,PRICE_CLOSE ,1);
   double LastRSI = iRSI (NULL, 0, RSIPeriod,PRICE_CLOSE ,2);
   
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   
   if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }



//Check for open orders if there are none then check for conditions to open one

      if (OrdersTotal() ==0 && LastRSI > PrevRSI && PrevRSI > CurrentRSI && CurrentRSI < LowerBound && pAsk > MA200) {    //Condition to execute buy entry
  
        Ticket1 = OrderSend(Symbol(), OP_BUY, Lots, pAsk, Slippage.Pips, pBid - ( StopLoss * Point ), pBid + ( TakeProfit * Point ), "Buy.", MagicNumber,0,Yellow);       //execute buy order
   
    if(Ticket1>0)
           {
            if(OrderSelect(Ticket1,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("BUY order opened : ",OrderOpenPrice());
            
           }
         if (Ticket1 < 0) {
         Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
   }  
  

  if (OrdersTotal() ==0 && LastRSI < PrevRSI && PrevRSI < CurrentRSI && CurrentRSI > UpperBound && pBid < MA200) {     //Condition to execute sell entry
  
       Ticket2 = OrderSend(Symbol(), OP_SELL, Lots, pBid, Slippage.Pips, pAsk + ( StopLoss * Point ), pAsk - ( TakeProfit * Point ), "Sell.",MagicNumber, 0, Yellow)  ;     //execute sell order
       if(Ticket2>0)
           {
            if(OrderSelect(Ticket2,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("SELL order opened : ",OrderOpenPrice());
           
           }
         if (Ticket2<0) {
          Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
   } 
      
      }
 


   
    int ticket=OrderTicket();
    double lots=OrderLots();
   
   
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
   
      if (OrderSelect(i, SELECT_BY_POS))
      {
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) {


         if (OrderType() == OP_BUY && pAsk > MA5)
         {
          Ticket3 = OrderClose(ticket, lots, pAsk, Slippage.Pips);
          
          if (Ticket3 == true ) {
          Print("BUY position closed", OrderClosePrice());
          }
          if (Ticket3 == false) {
          Print("Error closing BUY position", ErrorDescription(GetLastError()));
          }
          }
          
          if (OrderType() == OP_SELL && pAsk < MA5)
          {
          Ticket4 = OrderClose(ticket, lots, pAsk, Slippage.Pips);
           if (Ticket4 == true ) {
          Print("SELL position closed", OrderClosePrice());
          }
          if (Ticket4 == false) {
          Print("Error closing SELL position", ErrorDescription(GetLastError()));
          }
    }
      }
      
   }
   }
   
   
   
        
        
           return(0);
}
 

cyxstudio

Trader
Jan 31, 2013
6
0
12
What happens when you test that EA?

Here are some hints to improve your code:
  • Use brackets around each condition inside complex "if" statements.
  • Take-profit should be based on Bid for Buy orders and on Ask for Sell orders.
  • When you OrderClose() a sell order, you need to use Ask price.
  • Use RefreshRates() before referencing Ask/Bid. It is usually enough to call it once in the beginning of the start() function.
  • If your broker uses 5 digits after dot in quotes, then your stop-loss, take-profit and slippage parameters' default values are too low.
  • And you attach it to daily chart, right?

ermmm once i changed the Ask / Bid according to your posts it started making positive profit again! but there is a new error that occurred.
the error description says


OrderClose error 138
Strategy 8 EURUSD,H1: Error closing BUY positionrequote

i googled it says that adding refreshrates() would fix this error but i did add that function in my code and it still happens.
 

cyxstudio

Trader
Jan 31, 2013
6
0
12
That's because you are trying to close Buy at Ask price.

PS: Use MQL4 highlighting when you submit MQL4 code inside a post.

hmmm things getting complicated again. when i remove the close function and let takeprofit and stoploss take the coarse, the profit/loss varies according to value of stoploss/takeprofit

however when i add in a functioning closeroder code, it consistently loses money.

Code:
int ticket=OrderTicket();
    double lots=OrderLots();
   
   
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
   
      if (OrderSelect(i, SELECT_BY_POS))
      {
      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == MagicNumber)) {


         if (OrderType() == OP_BUY && [code=mql4]pBid > MA5
)
{
Ticket3 = OrderClose(ticket, lots, pBid, Slippage.Pips);

if (Ticket3 == true ) {
Print("BUY position closed", OrderClosePrice());
}
if (Ticket3 == false) {
Print("Error closing BUY position", ErrorDescription(GetLastError()));
}
}
}
}
}[/CODE]

i am wondering is there anything wrong with the part of if condition? i have read some samples they code in such a manner to determine the trend

Code:
if ((AskNow>AskPrev) && (AskPrev > AskLast)) {

should i imitate this code? how can i find Ask and Bid price of the last few bars?
 
Last edited by a moderator:

Enivid

Administrator
Staff member
Nov 30, 2008
16,046
818
144
Odessa
www.earnforex.com
hmmm things getting complicated again. when i remove the close function and let takeprofit and stoploss take the coarse, the profit/loss varies according to value of stoploss/takeprofit

however when i add in a functioning closeroder code, it consistently loses money.

i am wondering is there anything wrong with the part of if condition? i have read some samples they code in such a manner to determine the trend

Why do you expect this EA to be profitable?

should i imitate this code? how can i find Ask and Bid price of the last few bars?

There is no such thing as Ask or Bid price of the last few bars. Each bar may consist of thousands of Ask/Bid prices. MetaTrader does not store tick history. Usually, when comparing bars, you compare Close prices or some aggregate price, like typical ((H+L+C)/3).