Need EA to have a Take Profit at the current candle close - page 2

 
Thanks much

 

Hello. I have e made efforts to try and add some MQL5 Structures that i will use for the trade modification after reading the page that you last referred to me Vlad.

ts quite informative and i have used those Mql5 structures to try and code for my TakeProfit.

But its still not showing (TP)on the chart after opening the trade.

I think there must be a minor mistake i am not doing right. There is still 1 error but m learning ;)

//+------------------------------------------------------------------+
//|                                                            1.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
//---
extern bool      useProfitToClose       = true;
extern double    profitToClose          = 1200;

//---
#include  <Trade\Trade.mqh>
#include  <Trade\SymbolInfo.mqh>
//---
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//--- input parameters
input int      TakeProfit=110;
input group             "Position size management (lot calculation)"
input double   InpLots              = 0.25;        // Lots
input group             "Additional features"
input ulong    InpDeviation         = 10;          // Deviation
input ulong    InpMagic             = 201;         // Magic number
//---
datetime m_prev_bars                = 0 ;           // "0" -> D'1970.01.01 00:00';
//--- Other parameters
int TP;   // To be used for Take Profit values
double  OrderTakeProfit();
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   return (INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(m_symbol.Name(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
//--- check the number of 'BUY' positions for the current symbol and with the specified 'Magic number'
   ulong tickets_buy[];
   int position_exist_buy=PositionExist(m_symbol.Name(),POSITION_TYPE_BUY,InpMagic,tickets_buy);
   if(position_exist_buy>0)
      return;
//--- check the number of 'SELL' positions for the current symbol and with the specified 'Magic number'
   ulong tickets_sell[];
   int position_exist_sell=PositionExist(m_symbol.Name(),POSITION_TYPE_SELL,InpMagic,tickets_sell);
   if(position_exist_sell>0)
      return;
//--- Define some MQL5 Structures we will use for our trade
   MqlTick latest_price;     // To be used for getting recent/latest price quotes
   MqlTradeRequest mrequest;  // To be used for sending our trade requests
   MqlTradeResult mresult;    // To be used to get our trade results
   MqlRates mrate[];         // To be used to store the prices, volumes and spread of each bar
   ZeroMemory(mrequest);     // Initialization of mrequest structure
//--- MqlTick is a structure used for storing the latest prices of symbols. 
   struct MqlTick
  {
   datetime     time;          // Time of the last prices update
   double       bid;           // Current Bid price
   double       ask;           // Current Ask price
   double       last;          // Price of the last deal (Last)
   ulong        volume;        // Volume for the current Last price
  };
//--- MqlTradeRequest is used to perform all trade requests for a trade operation. Contains all fields necessary to perform a trade deal/modification
   struct MqlTradeRequest
  {
   ENUM_TRADE_REQUEST_ACTIONS    action;       // Trade operation type
   ulong                         magic;        // Expert Advisor ID (magic number)
   ulong                         order;        // Order ticket
   string                        symbol;       // Trade symbol
   double                        volume;       // Requested volume for a deal in lots
   double                        price;        // Price
   double                        TP;           // Take Profit level of the order
   ulong                         deviation;    // Maximal possible deviation from the requested price
   string                        comment;       // Order comment
  };
//--- MqlTradeResult result of any trade operation is returned as a special predefined structure of MqlTradeResult type
   struct MqlTradeResult
  {
   uint     retcode;          // Operation return code
   ulong    deal;             // Deal ticket, if it is performed
   ulong    order;            // Order ticket, if it is placed
   double   volume;           // Deal volume, confirmed by broker
   double   price;            // Deal price, confirmed by broker
   double   bid;              // Current Bid price
   double   ask;              // Current Ask price
   string   comment;          // Broker comment to operation (by default it is filled by the operation description)
  };
//--- MqlRates; The Price (Open, Close, High, Low), Time, Volumes of each bar and spread for a symbol is stored in this structure
   struct MqlRates
  {
   datetime time;         // Period start time
   double   open;         // Open price
   double   high;         // The highest price of the period
   double   low;          // The lowest price of the period
   double   close;        // Close price
   long     tick_volume;  // Tick volume
   int      spread;       // Spread
   long     real_volume;  // Trade volume
  };
//---Now modifying Take profit
   mrequest.action = TRADE_ACTION_MODIFY;                                // immediate order execution
   mrequest.price = NormalizeDouble(latest_price.ask,_Digits);          // latest ask price
   mrequest.tp = NormalizeDouble(latest_price.ask + TP*_Point,_Digits); // Take Profit
   mrequest.symbol = _Symbol;                                         // currency pair
   mrequest.deviation=10;                                            // Deviation from current price
//---
   m_trade.Buy(InpLots,m_symbol.Name()); 
//---
  }
//---- MODIFY TP
  {
  m_trade.PositionModify(InpLots,m_symbol.Name,TP);
  }
//+------------------------------------------------------------------+
Files:
 

Hi Vladimir. I have been trying to fuse this code for taking profit with this candle trading EA but its still not inserting my tp.

I have been testing it on indices on binary.com

1. When i use PositionsTotal, the EA no longer opens additional trades. its opening only 1 (I want it to continue opening on each next candle)

2. I am not sure where exactly i am doing it right to take profit, otherwise i followed "Simple Advisor with Stop Loss and Take Profit" procedure.]

3. i might need again to change this, how best can i do it to suit the indices decimal ?

Need EA to have a Take Profit at the current candle close - Stop Loss - Expert Advisors and Automated Trading - MQL5 programming forum
pips=0,     // Pips (1.00045-1.00055=1 pips)
points=1,   // Points (1.00045-1.00055=10 points)

The main pressing issue is placing Take profit please help me...


//+------------------------------------------------------------------+
//|                                                            1.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
//---
#include  <Trade\Trade.mqh>
#include  <Trade\SymbolInfo.mqh>
//---
CTrade         m_trade;                            // object of CTrade class
CSymbolInfo    m_symbol;                           // object of CSymbolInfo class
//--- input parameters
input ushort InpTakeProfit          = 1100;         // Take profit, in Points (9544.584 - 9545.654=1070 points)
input group             "Position size management (lot calculation)"
input double   InpLots              = 0.25;        // Lots
input group             "Additional features"
input ulong    InpDeviation         = 10;          // Deviation
input ulong    InpMagic             = 201;         // Magic number
//---
datetime m_prev_bars                = 0 ;           // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   return (INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(m_symbol.Name(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
//--- check the number of 'BUY' positions for the current symbol and with the specified 'Magic number'
   ulong tickets_buy[];
   int position_exist_buy=PositionExist(m_symbol.Name(),POSITION_TYPE_BUY,InpMagic,tickets_buy);
   if(position_exist_buy>0)
      return;
//--- check the number of 'SELL' positions for the current symbol and with the specified 'Magic number'
   ulong tickets_sell[];
   int position_exist_sell=PositionExist(m_symbol.Name(),POSITION_TYPE_SELL,InpMagic,tickets_sell);
   if(position_exist_sell>0)
      return;
//---
   if(PositionsTotal()==0)
     {
      MqlTick tick;
      if(SymbolInfoTick(Symbol(),tick))
        {
         double tp=(InpTakeProfit==0.0)?0.0:tick.ask+InpTakeProfit*Point();
//---
    m_trade.Buy(0.25,m_symbol.Name(),tp);
        }
     }
  }
//+------------------------------------------------------------------+
Files:
1._tp.mq5  7 kb
 
Jaybee66 :

Hi Vladimir. I have been trying to fuse this code for taking profit with this candle trading EA but its still not inserting my tp .

***

Where is it seen? I don’t believe if there is no confirmation: why did you decide that TakeProfit was not exposed? Position opened, but TakeProfit was not set?

Please first check your code on the "EURUSD" symbol on the "MetaQuotes-Demo" demo server.

 

I also recommend reading the help: CTrade: Buy

bool  Buy(
   double        volume,          // position volume
   const string  symbol=NULL,     // symbol
   double        price=0.0,       // execution price
   double        sl=0.0,          // stop loss price
   double        tp=0.0,          // take profit price
   const string  comment=""       // comment
   )

Pay attention to the SEQUENCE of the variables. Your code should be like this:

//+------------------------------------------------------------------+
//|                                                            1.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.001"
#property description "On every new bar we open a 'BUY' position with the specified TakeProfit"
//---
#include  <Trade\Trade.mqh>
#include  <Trade\SymbolInfo.mqh>
//---
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//--- input parameters
input group             "Trading settings"
input uint     InpTakeProfit        = 46;          // Take Profit
input group             "Position size management (lot calculation)"
input double   InpLots              = 0.25;        // Lots
input group             "Additional features"
input ulong    InpDeviation         = 10;          // Deviation
input ulong    InpMagic             = 201;         // Magic number
//---
double   m_take_profit              = 0.0;         // Take Profit                -> double
datetime m_prev_bars                = 0 ;          // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   m_take_profit              = InpTakeProfit               * m_symbol.Point();
//---
   return (INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(m_symbol.Name(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
//---
   MqlTick tick;
   if(SymbolInfoTick(Symbol(),tick))
     {
      double tp=(InpTakeProfit==0.0)?0.0:tick.ask+InpTakeProfit*Point();
      m_trade.Buy(InpLots,Symbol(),tick.ask,0.0,tp);
     }
   else
      m_prev_bars=0;
//---
  }
//+------------------------------------------------------------------+

Documentation on MQL5: Standard Library / Trade Classes / CTrade / Buy
Documentation on MQL5: Standard Library / Trade Classes / CTrade / Buy
  • www.mql5.com
Successful completion of the Buy(...) method does not always mean successful execution of the trade operation. It is necessary to check the result of trade request (trade server return code) using ResultRetcode() and value returned by ResultDeal().
Files:
1.mq5  6 kb
 
Vladimir Karputov:

I also recommend reading the help: CTrade: Buy

Pay attention to the SEQUENCE of the variables. Your code should be like this:

Thank you. I have to practice n read more on sequence. Otherwise let me try it out
 
Thanks much for the help throughout the EA programing process Vladimir. Its working perfectly. I am still doing more back testing otherwise it requires monitoring. Thanks once again. i will continue leaning how best to improve it.
 
Vladimir Karputov #:

I also recommend reading the help: CTrade: Buy

Pay attention to the SEQUENCE of the variables. Your code should be like this:

Hi Vlad. Please can you do this code for SELL. I tried to do this many times, but I can't set Take Profit