StopLoss and TakeProfit not triggering

 
#include <Trade/Trade.mqh>

CTrade trade;

input int stoploss = 5;
input int takeprofit = 3;

int candleG;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
      candleG = 1;
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
      if(isNewDay()){
         candleG = 1;
      }
      
      if(isNewBar()){
         candleG++;      
         
         if(candleG == 5){
            
            double price = normalizePrice(iOpen(NULL, PERIOD_CURRENT, 0));
            double tp = price + takeprofit;
            double sl = price - stoploss;
            
            bool ticket = trade.Buy(1, _Symbol, price, sl, tp, "[BUY]");           
            
            if(ticket > 0){
               Print("Success! Ticket: ", trade.ResultDeal());
            } else {
               Print("Error code: ", GetLastError());
            }           
         }
      }             

  }
//+------------------------------------------------------------------+

bool isNewDay(){
   datetime currentTime = iTime(Symbol(), PERIOD_CURRENT, 0);
   datetime previousTime = iTime(Symbol(), PERIOD_CURRENT, 1);
   
   MqlDateTime mqlCurrentTime;
   MqlDateTime mqlPreviousTime;
   TimeToStruct(currentTime, mqlCurrentTime);
   TimeToStruct(previousTime, mqlPreviousTime);
   
   if(mqlCurrentTime.day == mqlPreviousTime.day){
      return false;
   } else {
      return true;
   }
}

bool isNewBar(){
   static datetime last_time=0;
   datetime lastbar_time=(datetime)SeriesInfoInteger(Symbol(),Period(),SERIES_LASTBAR_DATE);
   if(last_time==0){
      last_time=lastbar_time;
      return(false);
   }
   if(last_time!=lastbar_time){
      last_time=lastbar_time;
      return(true);
   }
   return(false);
}

double normalizePrice(double price){
   double tick_size = SymbolInfoDouble ( _Symbol , SYMBOL_TRADE_TICK_SIZE );
   
   if(tick_size == 0.0){
   return(NormalizeDouble(price, _Digits));
   }
   
   return(NormalizeDouble(MathRound(price / tick_size) * tick_size, _Digits));
}

I have this simple code above.

For some reason the stop loss and take profit from 
bool ticket = trade.Buy(1, _Symbol, price, sl, tp, "[BUY]");
is not triggering as the .png shows.

Can anyone help me see what i have done wrong?

Thanks in advance!

----------------------- UPDATE ---------------------------------

I tried the code below but still get the same situation

if(candleG == 5){
            double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
            double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);
            
            double tp = Bid + takeprofit;
            double sl = Bid - stoploss;
            
            bool ticket = trade.Buy(1, _Symbol, Ask, sl, tp, "[BUY]");           
            
            if(ticket > 0){
               Print("Success! Ticket: ", trade.ResultDeal());
            } else {
               Print("Error code: ", GetLastError());
            }           
         }
Extract profit down to the last pip
Extract profit down to the last pip
  • www.mql5.com
The article describes an attempt to combine theory with practice in the algorithmic trading field. Most of discussions concerning the creation of Trading Systems is connected with the use of historic bars and various indicators applied thereon. This is the most well covered field and thus we will not consider it. Bars represent a very artificial entity; therefore we will work with something closer to proto-data, namely the price ticks.
Files:
file.PNG  102 kb
 
Your topic has been moved to the section: Expert Advisors and Automated Trading — In the future, please consider which section is most appropriate for your query.
 
Matheus Freire:

I have this simple code above.

For some reason the stop loss and take profit from  is not triggering as the .png shows.

Can anyone help me see what i have done wrong?

Thanks in advance!

Buy at Ask

Sell at Bid

Why use Open Price?

 
Chioma Obunadike #:

Buy at Ask

Sell at Bid

Why use Open Price?

Thanks for replying me!

I'm newbie so i'm learning yet.

Well, the strategy i want to do requires the order send with the open price right after a specif candle.

I thought that i could send any price to trade.Buy with the SL and TP i have set according to the open price.

if it's not too much trouble, could you give me an example or provide a link to it?

I put an update section on my first post with a try to do what you told.

Again, thank you very much!

 

In might be best for you to place your question in the Portuguese forum.

You are dealing with a symbol and exchange that has a special and peculiar behaviour which is unique to Brazil.

Most of the traders here don't have any experience with Brazilian markets or those unique conditions.

Brazilian traders/codes will be able to offer better advice based on their experiences on the same market.

Fórum MQL5
Fórum MQL5
  • www.mql5.com
MQL5: Fórum sobre sistemas de negociação automatizados e testes de estratégia
 
I believe the take profit order acts as a limit order. This means that the take profit order is only triggered when the current price matches the take profit price exactly. If the price of the symbol goes past the take profit price, the take profit order will not be triggered.
 

I am not sure which assets you are working with but let’s assume it is currency pairs 

your takeprofit is 5 and current price is 1.0015 

which means you want trade to close when price is = 5+1.0015 = 6.0015, Not feasible… 

Use this instead 

if(candleG == 5){
            double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
            double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);
            
            double tp = Ask + takeprofit*_Point; //NOTE I used Ask for Buys and Bid for Sells 
            double sl = Ask - stoploss*_Point;
            
            bool ticket = trade.Buy(1, _Symbol, Ask, sl, tp, "[BUY]");           
            
            if(ticket > 0){
               Print("Success! Ticket: ", trade.ResultDeal());
            } else {
               Print("Error code: ", GetLastError());
            }           
         }
 
Stephen Fabrico #: I believe the take profit order acts as a limit order. This means that the take profit order is only triggered when the current price matches the take profit price exactly. If the price of the symbol goes past the take profit price, the take profit order will not be triggered.

Wrong, that is not what a limit order does. It means that price or better.

 
Chioma Obunadike #: Use this instead 
            double tp = Ask + takeprofit*_Point; //NOTE I used Ask for Buys and Bid for Sells 
            double sl = Ask - stoploss*_Point;
  1. Floating point has an infinite number of decimals, it's you were not understanding floating point and that some numbers can't be represented exactly. (like 1/10.)
              Double-precision floating-point format - Wikipedia, the free encyclopedia

    See also The == operand. - MQL4 programming forum (2013)

  2. Print out your values to the precision you want with DoubleToString - Conversion Functions - MQL4 Reference.

  3. SL/TP (stops) need to be normalized to tick size (not Point) — code fails on non-currencies.
              On 5Digit Broker Stops are only allowed to be placed on full pip values. How to find out in mql? - MQL4 programming forum #10 (2011)

    And abide by the limits Requirements and Limitations in Making Trades - Appendixes - MQL4 Tutorial and that requires understanding floating point equality Can price != price ? - MQL4 programming forum (2012)

  4. Open price for pending orders need to be adjusted. On Currencies, Point == TickSize, so you will get the same answer, but it won't work on non-currencies. So do it right.
              Trailing Bar Entry EA - MQL4 programming forum (2013)
              Bid/Ask: (No Need) to use NormalizeDouble in OrderSend - MQL4 programming forum (2012)

  5. Lot size must also be adjusted to a multiple of LotStep and check against min and max. If that is not a power of 1/10 then NormalizeDouble is wrong. Do it right.
              (MT4 2013)) (MT5 2022))

  6. MathRound() and NormalizeDouble() are rounding in a different way. Make it explicit.
              MT4:NormalizeDouble - MQL5 programming forum (2017)
              How to Normalize - Expert Advisors and Automated Trading - MQL5 programming forum (2017)

  7. Prices you get from the terminal are already correct (normalized).

  8. PIP, Point, or Tick are all different in general.
              What is a TICK? - MQL4 programming forum (2014)

 
William Roeder #:
  1. Floating point has an infinite number of decimals, it's you were not understanding floating point and that some numbers can't be represented exactly. (like 1/10.)
              Double-precision floating-point format - Wikipedia, the free encyclopedia

    See also The == operand. - MQL4 programming forum (2013)

  2. Print out your values to the precision you want with DoubleToString - Conversion Functions - MQL4 Reference.

  3. SL/TP (stops) need to be normalized to tick size (not Point) — code fails on non-currencies.
              On 5Digit Broker Stops are only allowed to be placed on full pip values. How to find out in mql? - MQL4 programming forum #10 (2011)

    And abide by the limits Requirements and Limitations in Making Trades - Appendixes - MQL4 Tutorial and that requires understanding floating point equality Can price != price ? - MQL4 programming forum (2012)

  4. Open price for pending orders need to be adjusted. On Currencies, Point == TickSize, so you will get the same answer, but it won't work on non-currencies. So do it right.
              Trailing Bar Entry EA - MQL4 programming forum (2013)
              Bid/Ask: (No Need) to use NormalizeDouble in OrderSend - MQL4 programming forum (2012)

  5. Lot size must also be adjusted to a multiple of LotStep and check against min and max. If that is not a power of 1/10 then NormalizeDouble is wrong. Do it right.
              (MT4 2013)) (MT5 2022))

  6. MathRound() and NormalizeDouble() are rounding in a different way. Make it explicit.
              MT4:NormalizeDouble - MQL5 programming forum (2017)
              How to Normalize - Expert Advisors and Automated Trading - MQL5 programming forum (2017)

  7. Prices you get from the terminal are already correct (normalized).

  8. PIP, Point, or Tick are all different in general.
              What is a TICK? - MQL4 programming forum (2014)

You must be a genius of some sort. How you analyze each code line by line is A-M-A-Z-I-N-G
 
First of all, my thanks to everyone who assisted me.

William, what an analysis! Thanks!

Chioma, thank you so much for trying to help me from the beginning.

Well I found a solution and it was simpler than I thought:

As Fernando mentioned, my symbol is peculiar to Brazil, so all I had to do is change the currency in the tester properties.

My sincere apologies for the newbie question.

Again, thank you all for the spectacular answers.
Reason: