How to start with MQL5 - page 36

 
daengrani # :

Dear Vladimir,

I put modify pending code at OnChartEvent...


They're very responsive.

Fine! Good decision.

 

Working with the CiDEMA class

The code

//+------------------------------------------------------------------+
//|                                     CiDEMA Values on a Chart.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.00"
//---
#include <Indicators\Trend.mqh>
CiDEMA            m_dema;           // object-indicator
//--- input parameters
input group             "DEMA"
input int                  Inp_DEMA_ma_period            = 14;             // DEMA: averaging period
input int                  Inp_DEMA_ma_shift             = 0;              // DEMA: horizontal shift
input ENUM_APPLIED_PRICE   Inp_DEMA_applied_price        = PRICE_CLOSE;    // DEMA: type of price
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- initialize indicator
   if(!m_dema.Create(Symbol(),Period(),Inp_DEMA_ma_period,Inp_DEMA_ma_shift,Inp_DEMA_applied_price))
     {
      printf(__FUNCTION__+": error initializing object");
      return(false);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   m_dema.Refresh();
   string text="";
   for(int i=0; i<3; i++)
      text=text+IntegerToString(i)+": "+DoubleToString(m_dema.Main(i),Digits()+1)+"\n";
//---
   Comment(text);
  }
//+------------------------------------------------------------------+

Result

Working with the CiDEMA class

Pic. 1. Working with the CiDEMA class

 

Get Stop Loss and Take Profit for a position from the trading history

The code:

Step 1: cycle to zero

//--- for all deals
   for(uint i=total_deals-1; i>=0; i--) // for(uint i=total_deals-1; i>=0; i--) => i #total_deals-1 - 2017, i #0 - 2022

Step 2: Finding the first deal NOT 'DEAL_ENTRY_IN' and remember the date

         datetime temp_deal_time=(datetime)deal_time;
         if(deal_entry!=DEAL_ENTRY_IN)
            from_date=(datetime)deal_time;

This approach saves memory - the next time we will request the trading history from this saved date.

 
Vladimir Karputov #:

Get Stop Loss and Take Profit for a position from the trading history

The code:

Step 1: cycle to zero

Step 2: Finding the first deal NOT 'DEAL_ENTRY_IN' and remember the date

This approach saves memory - the next time we will request the trading history from this saved date.

dear Vladimir,

How to get last lot from last position (opened by EA with magic number) that has been closed partiallly ?

 
daengrani # :

dear Vladimir,

How to get last lot from last position (opened by EA with magic number) that has been closed partiallly ?

You missed a lot of details: what type of trading account, how part of the position was closed...

I recommend using the History Deals and Orders script (version 1.007 is available ONLY from the Russian part of CodeBase) - this way you will understand in which direction to move.

 

How to use a custom indicator in an EA

Code: 'iCustom AMA smoothed RSI (fl) value on chart.mq5'

Let's take a custom indicator here: AMA smoothed RSI - floating levels.

ATTENTION: the indicator must be placed in the [data folder]\MQL5\Indicators\AMA smoothed RSI (fl).mq5 folder and then the indicator must be compiled (button Complilein MetaEditor)!

//+------------------------------------------------------------------+
//|                 iCustom AMA smoothed RSI (fl) value on chart.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property version   "1.000"
#property tester_indicator "AMA smoothed RSI (fl)"
//--- input parameters
input int                inpRsiPeriod  = 14;          // RSI period
input int                inpPeriod     = 14;          // AMA Period
input int                inpFastPeriod =  2;          // AMA Fast end period
input int                inpSlowPeriod = 30;          // AMA Slow end period
input ENUM_APPLIED_PRICE inpPrice      = PRICE_CLOSE; // Price
enum enColorChangeOn
  {
   cchange_onSlope,  // Change color on slope change
   cchange_onLevels, // Change color on outer levels cross
   cchange_onZero    // Change color on middle level cross
  };
input int                inpFlPeriod    = 25;               // Floating levels period
input double             inpFlLevelUp   = 90;               // Floating levels up %
input double             inpFlLevelDn   = 10;               // Floating levels down %
input enColorChangeOn    inpColorChange = cchange_onLevels; // Color changing mode
//---
int      handle_iCustom;                     // variable for storing the handle of the iCustom indicator
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator iMACD ([data folder]\MQL5\Indicators\AMA smoothed RSI (fl).mq5)
   handle_iCustom=iCustom(Symbol(),Period(),"AMA smoothed RSI (fl)",
                          inpRsiPeriod,
                          inpPeriod,
                          inpFastPeriod,
                          inpSlowPeriod,
                          inpPrice,
                          inpFlPeriod,
                          inpFlLevelUp,
                          inpFlLevelDn,
                          inpColorChange);
//--- if the handle is not created
   if(handle_iCustom==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the 'AMA smoothed RSI (fl)' indicator for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   if(handle_iCustom!=INVALID_HANDLE)
      IndicatorRelease(handle_iCustom);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double levu[],levm[],levd[],val[];
   ArraySetAsSeries(levu,true);
   ArraySetAsSeries(levm,true);
   ArraySetAsSeries(levd,true);
   ArraySetAsSeries(val,true);
   int start_pos=0,count=3;
   if(!iGetArray(handle_iCustom,0,start_pos,count,levu) || !iGetArray(handle_iCustom,1,start_pos,count,levm) ||
      !iGetArray(handle_iCustom,2,start_pos,count,levd) || !iGetArray(handle_iCustom,3,start_pos,count,val))
     {
      return;
     }
//---
   string text=" Upper level | Middle level | Lower level | AMA smoothed RSI"+"\n";
   for(int i=count-1; i>=0; i--)
     {
      text=text+"#"+IntegerToString(i)+
           " | "+DoubleToString(levu[i],Digits()+1)+
           " | "+DoubleToString(levm[i],Digits()+1)+
           " | "+DoubleToString(levd[i],Digits()+1)+
           " | "+DoubleToString(val[i],Digits()+1)+"\n";
     }
   Comment(text);
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
bool iGetArray(const int handle,const int buffer,const int start_pos,
               const int count,double &arr_buffer[])
  {
   bool result=true;
   if(!ArrayIsDynamic(arr_buffer))
     {
      PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__);
      return(false);
     }
   ArrayFree(arr_buffer);
//--- reset error code
   ResetLastError();
//--- fill a part of the iBands array with values from the indicator buffer
   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);
   if(copied!=count)
     {
      //--- if the copying fails, tell the error code
      PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d",
                  __FILE__,__FUNCTION__,count,copied,GetLastError());
      //--- quit with zero result - it means that the indicator is considered as not calculated
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+
AMA smoothed RSI - floating levels
AMA smoothed RSI - floating levels
  • www.mql5.com
AMA smoothed RSI - floating levels
 

Example: class CLabel, Panel

Code: 'CLabel Panel Example.mq5'

This is an example of a panel on which an object of the CLabel class is created. The 'ASK' price is displayed on each tick in the object.

//+------------------------------------------------------------------+
//|                                         CLabel Panel Example.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.001"
#property description "Show Ask price on CLabel object"
//--- input parameters
input int      Input1=9;
#include <Controls\Dialog.mqh>
#include <Controls\Label.mqh>
//+------------------------------------------------------------------+
//| defines                                                          |
//+------------------------------------------------------------------+
//--- indents and gaps
#define INDENT_LEFT                         (11)      // indent from left (with allowance for border width)
#define INDENT_TOP                          (11)      // indent from top (with allowance for border width)
#define INDENT_RIGHT                        (11)      // indent from right (with allowance for border width)
#define INDENT_BOTTOM                       (11)      // indent from bottom (with allowance for border width)
#define CONTROLS_GAP_X                      (5)       // gap by X coordinate
#define CONTROLS_GAP_Y                      (5)       // gap by Y coordinate
//--- for buttons
#define BUTTON_WIDTH                        (100)     // size by X coordinate
#define BUTTON_HEIGHT                       (20)      // size by Y coordinate
//--- for the indication area
#define EDIT_HEIGHT                         (20)      // size by Y coordinate
//--- for group controls
#define GROUP_WIDTH                         (150)     // size by X coordinate
#define LIST_HEIGHT                         (179)     // size by Y coordinate
#define RADIO_HEIGHT                        (56)      // size by Y coordinate
#define CHECK_HEIGHT                        (93)      // size by Y coordinate
//+------------------------------------------------------------------+
//| Class CControlsDialog                                            |
//| Usage: main dialog of the Controls application                   |
//+------------------------------------------------------------------+
class CControlsDialog : public CAppDialog
  {
private:
   CLabel            m_label;                         // CLabel object
public:
                     CControlsDialog(void);
                    ~CControlsDialog(void);
   //--- create
   virtual bool      Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
   //--- chart event handler
   virtual bool      OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);
   //--- Change text
   virtual void      ChangeText(const string text) {m_label.Text(text);}

protected:
   //--- create dependent controls
   bool              CreateLabel(void);
   //--- handlers of the dependent controls events
   void              OnClickLabel(void);

  };
//+------------------------------------------------------------------+
//| Event Handling                                                   |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CControlsDialog)

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
EVENT_MAP_END(CAppDialog)
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CControlsDialog::CControlsDialog(void)
  {
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CControlsDialog::~CControlsDialog(void)
  {
  }
//+------------------------------------------------------------------+
//| Create                                                           |
//+------------------------------------------------------------------+
bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
  {
   if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
      return(false);
//--- create dependent controls
   if(!CreateLabel())
      return(false);
//--- succeed
   return(true);
  }
//+------------------------------------------------------------------+
//| Create the "CLabel"                                              |
//+------------------------------------------------------------------+
bool CControlsDialog::CreateLabel(void)
  {
//--- coordinates
   int x1=INDENT_RIGHT;
   int y1=INDENT_TOP+CONTROLS_GAP_Y;
   int x2=x1+100;
   int y2=y1+20;
//--- create
   if(!m_label.Create(m_chart_id,m_name+"Label",m_subwin,x1,y1,x2,y2))
      return(false);
   if(!m_label.Text("Label123456"))
      return(false);
   if(!Add(m_label))
      return(false);
   Comment(m_label.Text());
//--- succeed
   return(true);
  }
//+------------------------------------------------------------------+
//| Global Variables                                                 |
//+------------------------------------------------------------------+
CControlsDialog ExtDialog;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create application dialog
   if(!ExtDialog.Create(0,"Controls",0,40,40,380,344))
      return(INIT_FAILED);
//--- run application
   ExtDialog.Run();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy dialog
   ExtDialog.Destroy(reason);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   MqlTick STick;
   if(SymbolInfoTick(Symbol(),STick))
     {
      ExtDialog.ChangeText(DoubleToString(STick.ask,Digits()));
     }
  }
//+------------------------------------------------------------------+
//| Expert chart event function                                      |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,         // event ID
                  const long& lparam,   // event parameter of the long type
                  const double& dparam, // event parameter of the double type
                  const string& sparam) // event parameter of the string type
  {
   ExtDialog.ChartEvent(id,lparam,dparam,sparam);
  }
//+------------------------------------------------------------------+


Result:

CLabel Panel Example

Files:
 
Comments that do not relate to this topic, have been moved to "Off Topic Posts".
 

Full or partial closure

Code: 'Full or partial closure.mq5'

The code looks for positions by the given symbol (' Close positions 'Symbol ') and by the given Magic (' Close positions 'Magic number' '). Two work options:

  1. if 'Close ...' is equal to 'Full' positions will be closed whose volume is equal to 'Full lots'
  2. if 'Close ...' is equal to 'Partialpart of the position (specified in 'Partial lots') will be closed

The code does not have any protections and checks - if the position cannot be closed, an error message will be printed.

//+------------------------------------------------------------------+
//|                                      Full or partial closure.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.001"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
//---
#property script_show_inputs
//+------------------------------------------------------------------+
//| Enum Full Or Partial                                             |
//+------------------------------------------------------------------+
enum ENUM_FULL_OR_PARTIAL
  {
   full=0,        // Full
   partial=1,     // Partial
  };
//--- input parameters
input string               InpSymbol         = "EURUSD";       // Close positions 'Symbol'
input ulong                InpMagic          = 200;            // Close positions 'Magic number'
input ENUM_FULL_OR_PARTIAL InpFullOrPartial  = full;           // Close ...
input double               InpFullLots       = 0.6;            // Full lots
input double               InpPartialLots    = 0.2;            // Partial lots
input ulong                InpMagicEA        = 379013688;      // 'Full or partial closure' 'Magic number'
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
//---
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==InpSymbol && m_position.Magic()==InpMagic)
           {
            if(InpFullOrPartial==full)
              {
               if(CompareDoubles(m_position.Volume(),InpFullLots))
                  if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                     Print(__FILE__," ",__FUNCTION__,", ERROR Close ... Full: ","CTrade.PositionClose ",m_position.Ticket());
              }
            else
              {
               if(m_position.Volume()>InpPartialLots)
                  if(!m_trade.PositionClosePartial(m_position.Ticket(),InpPartialLots)) // close a position by the specified m_symbol
                     Print(__FILE__," ",__FUNCTION__,", ERROR Close ... Partial: ","CTrade.PositionClose ",m_position.Ticket());
              }
           }
  }
//+------------------------------------------------------------------+
//| Compare doubles                                                  |
//+------------------------------------------------------------------+
bool CompareDoubles(double number1,double number2)
  {
   if(NormalizeDouble(number1-number2,8)==0)
      return(true);
   else
      return(false);
  }
//+------------------------------------------------------------------+
 
Vladimir Karputov 


hi Vladimir I added macd feature to my robot. but it is not working. no eror. The feature I want is to close the position if the difference between the macd line and the signal line is 0.05. My robot is attached. can you check it? thanks

Files:
imacd_modif.mq5  18 kb