Download MetaTrader 5

Basic EA, stop loss/ Take Profit not triggered

To add comments, please log in or register
jackyan22
49
jackyan22  

Hi everyone, I just modified my first EA from a tutorial. Everything went smoothly, it compiled with no errors, and it places trades! (yay!) However the STP and TKP values are never triggered in the strategy tester (which means that all trades are closed at the end of the experiment). I've looked through the code carefully (keep in mind that I'm a new programmer), I couldn't find the answer. Any help would be greatly appreciated. Thank you.

//+------------------------------------------------------------------+
//|                                                        First.mq5 |
//|                        Copyright 2012, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
//--- input parameters
input int      StopLoss=20;
input int      TakeProfit=30;
input int      Lot=1;
input int      EA_Magic=12345;
int STP, TKP;
double open_price;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- 
   STP = StopLoss;
   TKP = TakeProfit;
   if(_Digits==5 || _Digits==3)
     {
      STP = STP*10;
      TKP = TKP*10;
     }
     return(0);
  }
//---

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer

      
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
 {
  MqlTick last_tick;
  MqlTradeRequest mrequest;
  MqlTradeResult mresult;
  MqlRates mrate[];
  ZeroMemory(mrequest);
  if(!SymbolInfoTick(_Symbol,last_tick))
     {
      Alert("Error getting the latest price quote - error:",GetLastError(),"!!");
      return;
     }
   if(CopyRates(_Symbol,_Period,0,1,mrate)<0)
     {
      Alert("Error copying rates/history data - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }
/*
  bool buy_opened = false;
   if(PositionSelect(_Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         buy_opened=true;  //It is a Buy
        }
     }
*/
  open_price=mrate[0].open;
  
  bool Buy_condition_1=((open_price - last_tick.ask)>0.00148);
  if (Buy_condition_1)
/*
  {

   if(buy_opened)
      {
       Alert("We already have a Buy Position!!!");
            return;    // Don't open a new Buy Position
      }
*/
  ZeroMemory(mrequest);
  mrequest.action =  TRADE_ACTION_DEAL;
  mrequest.price = NormalizeDouble(last_tick.ask,Digits());
  mrequest.sl = NormalizeDouble(last_tick.ask - STP*_Point,_Digits);
  mrequest.tp = NormalizeDouble(last_tick.ask + TKP*_Point,_Digits);
  mrequest.symbol = _Symbol;
  mrequest.volume = Lot;
  mrequest.magic = EA_Magic; 
  mrequest.type = ORDER_TYPE_BUY;
  mrequest.type_filling = ORDER_FILLING_FOK;
  mrequest.deviation=100;
  OrderSend(mrequest,mresult);
  if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError());
            ResetLastError();           
            return;
           }
  return;
  }
  


//--
  
  
Files:
First.mq5 4 kb
meisme
39
meisme  

Hello,

I have tested your code on strategy tester, it was working properly.  STP and TKP were triggered as expected.

But i am curious with this line:

if (Buy_condition_1)

Perhaps you missed the opening and closing brackets for this conditional?

Regards,

jackyan22
49
jackyan22  
meisme:

Hello,

I have tested your code on strategy tester, it was working properly.  STP and TKP were triggered as expected.

But i am curious with this line:

Perhaps you missed the opening and closing brackets for this conditional?

Regards,


Thank you for your response. Are you sure SL and TP were triggered? And thank you for pointing out the brackets. This EA is riddled with errors but I'm just trying to get the basics down :). I just added the brackets and the SL and TP were still not triggered. Here's a screen shot. Also, I've encountered another small problem which is not illustrated in the code here. No matter what I change the variable "Lot" to, it is always 1 in strategy tester. I overcame this by adding a static number for mrequest.volume.  Thank you!


Lucero del Alba
20
Lucero del Alba  

Hi, same here.

I've tested that code --which I guess comes from the article Step-By-Step Guide to writing an Expert Advisor in MQL5 for Beginners, I mean, that's the one I tested-- in tons of different ways on the Strategy Tester to no avail; I can just plain remove the mrequest.sl/mrequest.tp lines, re-compile and re-test, and it won't make any difference.

I've tied searching both on the forums and the codebase, but I was rather surprised not to find a single EA with an OrderSend() in the whole codebase (in other words, not a single EA that actually trades)... looks like folks are not very enthusiastic about automatic trading around here, and I feel kind of silly asking on how to use stop losses/take profits while auto-trading; anyway, any help appreciated.

polymath
182
polymath  

Hi guys, I'm getting the same result for my_first_EA and for a lot of samples even this simple EA here:  https://www.mql5.com/en/code/103

Then I suddenly stumbled on this thread: https://www.mql5.com/en/forum/5360

here's what they said:

The only problem that remains is getting a sample of code that can create a pending order for stoploss and takeprofit with the  original trade.  

Do you guys know any code that does not require storing of our SL/TP on the side of the broker and just places a stop/limit order on our side/server?

Appreciate your reply. Thanks in advance! 

 

Simple MA Expert Advisor
  • votes: 15
  • 2010.04.27
  • Karlis Balcers | English Russian Spanish Portuguese
  • www.mql5.com
Something for those who wants to try out new Strategy Tester and don't have any EA.
polymath
182
polymath  

This problem is also related to an earlier post that I've made:  https://www.mql5.com/en/forum/7345

and this is also the same problem that's causing the big spread between the account balance and equity curve in one of my backtests:

 

I really hope someone can help me with this problem, I've been stuck with this problem for several weeks now. Maybe you could point me to a sample  code that can solve this problem?

Thanks in advance! 

WEIRD: Strategy Tester Results don't change even if parameters were changed
  • www.mql5.com
WEIRD: Strategy Tester Results don't change even if parameters were changed.
enbo lu
Moderator
1945
enbo lu  
jackyan22:

Thank you for your response. Are you sure SL and TP were triggered? And thank you for pointing out the brackets. This EA is riddled with errors but I'm just trying to get the basics down :). I just added the brackets and the SL and TP were still not triggered. Here's a screen shot. Also, I've encountered another small problem which is not illustrated in the code here. No matter what I change the variable "Lot" to, it is always 1 in strategy tester. I overcame this by adding a static number for mrequest.volume.  Thank you!


polymath:

Hi guys, I'm getting the same result for my_first_EA and for a lot of samples even this simple EA here:  https://www.mql5.com/en/code/103

Then I suddenly stumbled on this thread: https://www.mql5.com/en/forum/5360

here's what they said:

The only problem that remains is getting a sample of code that can create a pending order for stoploss and takeprofit with the  original trade.  

Do you guys know any code that does not require storing of our SL/TP on the side of the broker and just places a stop/limit order on our side/server?

Appreciate your reply. Thanks in advance! 

 

  i   met  the same problem. it seems that  the broker  don't actually take a sl/tp with the sending rder when its an ea....

   

polymath
182
polymath  
luenbo:

  i   met  the same problem. it seems that  the broker  don't actually take a sl/tp with the sending rder when its an ea....

   

Hi luenbo, did you find anything that could solve this problem or did you try something else? Did you use other approaches to set the stop loss and take profit levels?Appreciate it if you could share your findings... 

Documentation on MQL5: Standard Constants, Enumerations and Structures / Trade Constants / Order Properties
  • www.mql5.com
Standard Constants, Enumerations and Structures / Trade Constants / Order Properties - Documentation on MQL5
supercoder2006
26
supercoder2006  

Why don't you guys use stealth sl and tp orders?

To add comments, please log in or register