Newbie Trader: My EA is not entering any buy or sell orders

 

Hello All,


I have copied a supposedly working template from MQL4 and studied the codes. First things off, the following have been checked and confirmed:

- Autotrading is ON

- Tried the template.ex4 on various brokers; gets same results.

- Clean slate, no open orders

- No server or terminal issues

- My MT4 Build is Version 4, Build 1260

- Running on different timeframes, either no change or got more bad error messages instead.


This is my first time to try to code in MQL4.  I do understand the syntax and everything though, as I am an IT engineer and a programmer on other languages;  no compilation errors, however running a backtest, it doesn't automatically enter a sell or buy up until the end. Checking the Journal, I found this peculiar message on the last part: Expert template EURUSD, H4: removed. "template" by the way, is the filename. Tried renaming it thinking maybe the filename is reserved by MQL4 - no good still.  I think I missed something even though the instructions I follow are very clear and the video tutorials I watched shows their work is running.

See attached image for the journal message. I tried other EAs and they behave the same way.


Thanks and more power. Looking forward to your responses.

Copy / Pasting the code here, with all the commented details intact, to make it more comprehensible. If you need more details peeps do let me know. I really appreciate all the help I can get. I've retired from my field to work on FOREX.


//+------------------------------------------------------------------+

//|                                                                  |

//|                               Copyright 2017, www.mql4trader.com |

//|                                                                  |

//+------------------------------------------------------------------+

#property copyright "Copyright 2017, www.mql4trader.com"



//--- input parameters

extern string    Autotraders_by ="www.mql4trader.com";



///CUSTOMIZABLE OPTIONS GO HERE///

extern int period = 300; // PERIOD  

extern int applied_price = 0;  // APPLIED PRICE (0=CLOSE,1=OPEN,2=HIGH,3=LOW,4=MEDIAN,5=TYPICAL,6=WEIGHTED          

extern int barshift  = 1;           // SHIFT (1=last bar, 2= 2 bars ago, 3= 3 bars ago ect

////



///Set Take Profit and Stoploss///(Make sure that you check the journal when strategy testing. 

//If you are getting a order modify error your stops may be to low. 

//Check the specifications of the symbol you are trading and adjust for the amount of digits used.

extern double   TakeProfit=120;

extern double   StopLoss=150;

extern double   Lots=1; ///Investment 



//Timesettings

extern string   TimeSettings="Set the hours the EA should trade";

extern int      StartHour=0;//24 hour clock. Set your start and end of day times or leave as is to trade every hour

extern int      EndHour=23;



//Slippage

extern int      Slip=10;///adjust slippage here



///Leave BarsCount as is/// This makes it so you can only place one trade per bar. 

//Otherwise it sometimems will fire off many of the same trade per bar as each tick occurs...

extern int     BarsCount=0;///leave this as is





//Lets Begin//If there are less than zero orders, we can trade//



int start(){





if (Bars>BarsCount) 





{

//////////////////

string Symb=Symbol();



////This advisor works on all charts because of the "MarketInfo" code below...



int digits=MarketInfo(Symbol(),MODE_DIGITS);

int StopMultd=10;

int Slippage=Slip*StopMultd;



///Magic Number is your orders unique id number. This way you do not open multiple orders///



int MagicNumber1=032017,MagicNumber2=042017,i,closesell=0,closebuy=0;





///Takeprofit and Stoploss settings



double  TP=NormalizeDouble(TakeProfit*StopMultd,Digits);

double  SL=NormalizeDouble(StopLoss*StopMultd,Digits);



double slb=NormalizeDouble(Ask-SL*Point,Digits);

double sls=NormalizeDouble(Bid+SL*Point,Digits);





double tpb=NormalizeDouble(Ask+TP*Point,Digits);

double tps=NormalizeDouble(Bid-TP*Point,Digits);







//-------------------------------------------------------------------+

//Check open orders

//-------------------------------------------------------------------+







if(OrdersTotal()>0){

  for(i=1; i<=OrdersTotal(); i++)          // Checking to make sure there are no open orders. Keep this set to zero unless you want the advisor to open more than one buy at a time or more than one sell at a time.

     {

      if (OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available

        {

          if(OrderMagicNumber()==MagicNumber1) {int halt1=1;}///if this magicnumber has an order open... halt!

          if(OrderMagicNumber()==MagicNumber2) {int halt2=1;}///if this magicnumber has an order open... halt!

         



        

   

          

         

          

        



        }

     }

}

////Change input parameters "StartHour" EndHour" at top of page, to adjust, if you only want to trade at certain times...



if((Hour()>=StartHour)&&(Hour()<EndHour))

{

int TradeTimeOk=1;

}

else

{ TradeTimeOk=0; }





////







//-----------------------------------------------------------------

// Indicators Section/// This is where you place indicators needed for expert advisor to work...

//-----------------------------------------------------------------



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//                                                                                                              //

// IF YOU DO NOT UNDERSTAND THIS INDICATOR, SIMPLY RUN IT THROUGH THE STRATEGY TESTER AS IS AND "OPEN CHART"... //

// NOW YOU CAN GET A BETTER IDEA OF HOW IT WORKS...                                                             //

// IT IS ALSO RECOMMENDED TO SEARCH ONLINE TO LEARN MORE ON HOW TO USE THIS INDICATOR                           //

//                                                                                                              //

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////





////Always type "double" then the "name" you want to give, then "=" , then your indicator code...

///NOTE: The strategy tester can only give results at the end of each bar on a chart. 

///This is why we use "1" as our shift instead of "0". 

///If we use 1 then the advisor makes its calculation immediatly after the last bar has closed.

///You can still use "0" , but the strategy tester will not pick up on it...





double RSI1=iRSI(NULL,0,14,0,1);



///NOTE: TO MAKE LIFE EASIER, USE THE INPUT PARAMETERS FROM TOP OF PAGE. 

///THIS ALLOWS YOU TO ADJUST SETTINGS FROM THE STRATEGY TESTER

///HERE IS THE SAME INDICATOR THAT IS NOW CUSTOMIZABLE THROUGH THE STRATEGY TESTER:



double RSI1CUSTOM=iRSI(NULL,0,period,applied_price,barshift);



//leave the first two "NULL" and "0". Null means it will trade any chart its on and 0 means it will use the chart timeframe that it is attached to.





 

 //-------------------------------------------------------------------

// Opening criteria for buy and sell orders

//-----------------------------------------------------------------------------------------------------



Comment("TEMPLATE INDICATOR AUTOTRADER");

 

//OPEN SELL// 



//USE "&&" TO ADD MORE CONDITIONS IN BRACKETS...



if((RSI1CUSTOM>70)&&(halt1!=1)&&(TradeTimeOk==1)){

int opensell=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slip,0,0,"TEMPLATE",MagicNumber1,0,Green);

 }







//OPEN BUY//



//USE "&&" TO ADD MORE CONDITIONS IN BRACKETS...

 

 if((RSI1CUSTOM<30)&&(halt2!=1)&&(TradeTimeOk==1)){

int openbuy=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slip,0,0,"TEMPLATE",MagicNumber2,0,Blue);



 }

 

 

 //-------------------------------------------------------------------------------------------------

// Closing criteria for buy and sell orders

//-------------------------------------------------------------------------------------------------



 





if(openbuy>=0||opensell>=0)





{// start



if(OrdersTotal()>=0){

  for(i=1; i<=OrdersTotal(); i++){          // Cycle searching in orders

  

      if (OrderSelect(i-1,SELECT_BY_POS)==true){ // If the next is available...



//SELL CLOSE//

if((OrderMagicNumber()==MagicNumber1)&&(RSI1<30)){

int sellclose=OrderClose(OrderTicket(),Lots,Ask,Slip,Red);

}



//BUY CLOSE//

if((OrderMagicNumber()==MagicNumber2)&&(RSI1>70)){

int buyclose=OrderClose(OrderTicket(),Lots,Bid,Slip,Red);



}





////take profit and stoploss code///Do not change this code. 

//Just change takeprofit and stoploss settings in "Input Parameters"

//If you do not need takeprofit or stoploss you can delete these 4 lines of code...

   

 if((OrderMagicNumber()==MagicNumber2)&&(OrderTakeProfit()==0)&&(OrderSymbol()==Symbol())){ int modify1=OrderModify(OrderTicket(),0,OrderStopLoss(),tpb,0,CLR_NONE); }

 if((OrderMagicNumber()==MagicNumber1)&&(OrderTakeProfit()==0)&&(OrderSymbol()==Symbol())){ int modify2=OrderModify(OrderTicket(),0,OrderStopLoss(),tps,0,CLR_NONE); }

 if((OrderMagicNumber()==MagicNumber2)&&(OrderStopLoss()==0)&&(OrderSymbol()==Symbol())){ int modify3=OrderModify(OrderTicket(),0,slb,OrderTakeProfit(),0,CLR_NONE); }

 if((OrderMagicNumber()==MagicNumber1)&&(OrderStopLoss()==0)&&(OrderSymbol()==Symbol())){ int modify4=OrderModify(OrderTicket(),0,sls,OrderTakeProfit(),0,CLR_NONE); }

    

        }

     }



}

}

}// stop /// Do Not Alter The Following Code /// 







 //----

int Error=GetLastError();

  if(Error==130){Alert("Wrong stops. Retrying."); RefreshRates();}

  if(Error==133){Alert("Trading prohibited.");}

  if(Error==2){Alert("Common error.");}

  if(Error==146){Alert("Trading subsystem is busy. Retrying."); Sleep(500); RefreshRates();}



//----



//-------------------------------------------------------------------

BarsCount=Bars;

return(0);



}

 



//+------------------------------------------------------------------+
The Fundamentals of Testing in MetaTrader 5
The Fundamentals of Testing in MetaTrader 5
  • www.mql5.com
The idea of ​​automated trading is appealing by the fact that the trading robot can work non-stop for 24 hours a day, seven days a week. The robot does not get tired, doubtful or scared, it's is totally free from any psychological problems. It is sufficient enough to clearly formalize the trading rules and implement them in the algorithms, and...
 

I didn't know that. Rookie mistake. Will note that in the future. 


Just to add, I tried/attempt to debug it, but the "Step Into" feature of the debug keeps on greying out, so I can't make a step on every line to find how the process flow.


Again, TIA.

 
tompips2018:

I didn't know that. Rookie mistake. Will note that in the future. 

Just to add, I tried/attempt to debug it, but the "Step Into" feature of the debug keeps on greying out, so I can't make a step on every line to find how the process flow.

Again, TIA.

Add this line at the top:

#property strict

Then you'll see that you have undeclared and uninitialized variables in your order opening condition checks.

 
Seng Joo Thio:

Add this line at the top:

Then you'll see that you have undeclared and uninitialized variables in your order opening condition checks.

Yes, it did show the variables that was misplaced on the declaration and corrected it. However, it still didn't work. Still not triggering the Buy or Sell I hoped. No errors in the compilation process.

 

Please remove the empty lines from your code, it's hard to read.

Replace at least this:

if((Hour()>=StartHour)&&(Hour()<EndHour))
{
int TradeTimeOk=1;
}
else
{ TradeTimeOk=0; }

with:

bool TradeTimeOk=Hour()>=StartHour && Hour()<EndHour;
There might be more things to fix.
 
tompips2018:

Yes, it did show the variables that was misplaced on the declaration and corrected it. However, it still didn't work. Still not triggering the Buy or Sell I hoped. No errors in the compilation process.

That means some of your corrections are wrong. 

Show us your revised code.

 

Rather than "fixing the error", you need to work out how you can identify the problem, before someone says "we are not here to fix your code" ;) And I'm not much more than a newbie myself...

You can tidy up the code, as others have said. Remove the empty lines and comments; take a copy first. And, look at how you can simplify the code, remove unneccessary bracket, braces etc.

Then, work out where you can place and print out test variables to ensure the code is working the way you expect....after every line, if necessary.

 
andrew:

Rather than "fixing the error", you need to work out how you can identify the problem, before someone says "we are not here to fix your code" ;) And I'm not much more than a newbie myself...

You can tidy up the code, as others have said. Remove the empty lines and comments; take a copy first. And, look at how you can simplify the code, remove unneccessary bracket, braces etc.

Then, work out where you can place and print out test variables to ensure the code is working the way you expect....after every line, if necessary.

I maybe a newbie coder, but I do practice the very things you say. Asking questions to get the root cause of the problem is the best way to get to a quicker solution, because I know there are tons of people here who are really good and are enthusiastic to teach what they know, just as I am when I know the answer to one's questions. I'm sure everyone has gone through that phase, including you. I'm not here to be spoon-fed. 

And I appreciate more the people who give the fix by setting examples instead. And there are a number of them already. Their contribution makes my life definitely a lot easier. That's the beauty of the internet. In the old days, you have to go all the way to a public library or bookstore to get just a snippet of info. Now, it's just a click of a button.

It's just that after exhausting all the efforts I made that I get stumped with my limited knowledge, hence my coming here to ask questions from those who've been through it all. And I got what I need, thanks to those helpful peeps. Hope my asking questions doesn't send the wrong message that I am lazy enough not to research on my own as well. After all, if I already knew the answers, why would I ask questions in the first place? That's the idea of this forum, right? I'm sure we are all trained to not be afraid to ask questions, aren't we? ;-)

 
Seng Joo Thio:

That means some of your corrections are wrong. 

Show us your revised code.

Hi Seng,

I didn't revised everything except your suggestions, but I decided to dump that code and instead try other working codes and start from there as suggested by others on another forum. For some reason although that code looks similar to those I got working now, it just doesn't seem to work - surely there is some line of syntax there I didn't notice that is causing it, but I'd rather not waste my time on it when I can get a better one. I'd like to thank the guy I can't remember the handlename who provided a few bits of useful code to me, thank you mi amigo, I'm using it now. :-D. But thanks for the previous advice, indeed a stricter compiling is needed to get a finer compiled result. I wasn't aware of that particular property. I'm a newbie MQL4 programmer here. Still need lots to learn. Thanks again. :-)

 
tompips2018:

I maybe a newbie coder, but I do practice the very things you say. Asking questions to get the root cause of the problem is the best way to get to a quicker solution, because I know there are tons of people here who are really good and are enthusiastic to teach what they know, just as I am when I know the answer to one's questions. I'm sure everyone has gone through that phase, including you. I'm not here to be spoon-fed. 

And I appreciate more the people who give the fix by setting examples instead. And there are a number of them already. Their contribution makes my life definitely a lot easier. That's the beauty of the internet. In the old days, you have to go all the way to a public library or bookstore to get just a snippet of info. Now, it's just a click of a button.

It's just that after exhausting all the efforts I made that I get stumped with my limited knowledge, hence my coming here to ask questions from those who've been through it all. And I got what I need, thanks to those helpful peeps. Hope my asking questions doesn't send the wrong message that I am lazy enough not to research on my own as well. After all, if I already knew the answers, why would I ask questions in the first place? That's the idea of this forum, right? I'm sure we are all trained to not be afraid to ask questions, aren't we? ;-)

Just making the point, we can solve problems sometimes by stepping away from coding and thinking more about design, knowledge and process. An old mentor once told me we should spend 80% of our time on program design, and 20% on actual coding.

Like this from lippmaje, saving maybe 3 lines of code. I had no idea you could use a boolean this way. I use this now in my coding, thanks lippmaje..

bool TradeTimeOk=Hour()>=StartHour && Hour()<EndHour;
Reason: