Как начать работу с MQL5 - страница 36

 
daengrani # :

Дорогой Владимир,

Я поместил модифицировать отложенный код в OnChartEvent...


Они очень отзывчивые.

Отлично! Хорошее решение.

 

Работа с классом CiDEMA

Код

//+------------------------------------------------------------------+
//|                                     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);
  }
//+------------------------------------------------------------------+

Результат

Работа с классом CiDEMA

Рис. 1. Работа с классом CiDEMA

Файлы:
 

Получение стоп-лосса и тейк-профита для позиции из истории торговли

Код:

Шаг 1: цикл до нуля

//--- 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

Шаг 2: находим первую сделку НЕ'DEAL_ENTRY_IN' и запоминаем дату

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

Такой подход экономит память - в следующий раз мы будем запрашивать историю торговли с этой сохраненной даты.

 
Vladimir Karputov 'DEAL_ENTRY_IN' и запомнить дату

Такой подход экономит память - в следующий раз мы будем запрашивать историю торгов с этой сохраненной даты.

уважаемый Владимир,

Как получить последний лот из последней позиции (открытой советником с магическим номером), которая была закрыта частично?

 
daengrani # :

дорогой Владимир,

Как получить последний лот из последней позиции (открытой советником с магическим номером), которая была закрыта частично?

Вы упустили много деталей: какой тип торгового счета, как была закрыта часть позиции...

Рекомендую воспользоваться скриптом History Deals and Orders (версия 1.007 доступна ТОЛЬКО в русской части CodeBase) - так вы поймете, в каком направлении двигаться.

 

Как использовать пользовательский индикатор в советнике

Код: 'iCustom AMA сглаженное значение RSI (fl) на chart.mq5'

Возьмем здесь пользовательский индикатор: AMA smoothed RSI - floating levels.

ВНИМАНИЕ: индикатор должен быть помещен в папку [data folder]\MQL5\Indicators\AMA smoothed RSI (fl).mq5, а затем индикатор должен быть скомпилирован (кнопка Complile в 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
 

Пример: класс CLabel, Panel

Код: 'CLabel Panel Example.mq5'

Это пример панели, на которой создан объект класса CLabel. Цена 'ASK' отображается на каждом тике объекта.

//+------------------------------------------------------------------+
//|                                         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);
  }
//+------------------------------------------------------------------+


Результат:

Пример панели CLabel

Файлы:
 
Комментарии, не относящиеся к данной теме, были перемещены в раздел "Сообщения не по теме".
 

Полное или частичное закрытие

Код: 'Полное или частичное закрытие.mq5'

Код ищет позиции по заданному символу (' Close positions 'Symbol ') и по заданному Magic (' Close positions 'Magic number' ). Два варианта работы:

  1. если'Close ...' равно'Full', то будут закрыты позиции, объем которых равен'Full lots'
  2. если 'Close ...' равно 'Partial' , то будет закрыта часть позиции (указанная в'Partial lots').

Код не имеет никаких защит и проверок - если позиция не может быть закрыта, будет выведено сообщение об ошибке.

//+------------------------------------------------------------------+
//|                                      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 


Здравствуйте Владимир я добавил функцию macd в своего робота. но она не работает. нет ошибки. Я хочу, чтобы функция закрывала позицию, если разница между линией macd и сигнальной линией составляет 0,05. Мой робот прилагается. Вы можете проверить его? Спасибо.

Файлы:
imacd_modif.mq5  18 kb
Причина обращения: