어드바이저를 무작위로 모으는 방법 - 페이지 42

 

Expert에 기능을 하나 더 추가하겠습니다.

때로는 필요합니다 - 선이 즉시 작동하지 않도록, 즉 막대를 가로질러 고정했을 때

https://www.mql5.com/en/forum/310846/page9#comment_11404620

https://www.mql5.com/ru/code/25309

 
Aleksandr Klapatyuk :

Expert에 기능을 하나 더 추가하겠습니다.

때로는 필요합니다 - 선이 즉시 작동하지 않도록, 즉 막대를 가로질러 고정했을 때

https://www.mql5.com/en/forum/310846/page9#comment_11404620

https://www.mql5.com/ru/code/25309

화학자처럼 -

추세선에서 - 교차하고 막대가 거기에 남아 있으면 신호가 트리거됩니다.

 input string    t10= "----- Trend Line Name ------" ;       // Trend Line Name
input string    InpNameAverage          = "AVERAGE 0" ;   // Trend Line Name Средняя
//---

시험

지표도 조정되었습니다 - 위쪽 및 아래쪽 수평선, 중간 추세선

데모 버전 - 이 표시기와 함께 작동하는 방식

스냅 사진

나는 파란색이 있는 곳에서 녹색으로 갈 것입니다. 그때가 좋을 때입니다. 그러나 특정 금액을 설정하고 Expert Advisor를 다시 시작하면

 

다른 테스트 버전

이제 지표에 3개의 추세선이 있고 전문가가 이 추세선에서 포지션을 엽니다.

 input string    t10= "----- Trend Line Name ------" ;       // Trend Line Name
input string    InpNameAverage          = "AVERAGE 0" ;   // Trend Line Name
input string    InpNameAverage0         = "TOP 0" ;       // Trend Line Name
input string    InpNameAverage1         = "LOWER 0" ;     // Trend Line Name

스냅 사진

 
Aleksandr Klapatyuk :

다른 테스트 버전

이제 지표에 3개의 추세선이 있고 전문가가 이 추세선에서 포지션을 엽니다.


여기 버전이 있습니다 - 내가 한 방법 - 손으로 그리는 추세선 에서 더 완벽하게 작동합니다.

설정 - 가지고 있는 것

 //---
input double InpLots          = 0.1 ;           // Lots
input int     InpTakeProfit    = 50 ;             // Take Profit (in pips)
input string t0= "----- Trend Line Name ------" ; // Trend Line Name
input string InpNameAverage   = "AVERAGE 0" ;   // Trend Line Name
input string InpNameAverage0  = "TOP 0" ;       // Trend Line Name
input string InpNameAverage1  = "LOWER 0" ;     // Trend Line Name
//---
 //+------------------------------------------------------------------+
//|                                                  MACD Sample.mq5 |
//|                   Copyright 2009-2017, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright    "Copyright 2009-2017, MetaQuotes Software Corp."
#property link          "http://www.mql5.com"
#property version      "5.50"
#property description "It is important to make sure that the expert works with a normal"
#property description "chart and the user did not make any mistakes setting input"
#property description "variables (Lots, TakeProfit, TrailingStop) in our case,"
#property description "we check TakeProfit on a chart of more than 2*trend_period bars"

#define MACD_MAGIC 1234502
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
input double InpLots          = 0.1 ;           // Lots
input int     InpTakeProfit    = 50 ;             // Take Profit (in pips)
input string t0= "----- Trend Line Name ------" ; // Trend Line Name
input string InpNameAverage   = "AVERAGE 0" ;   // Trend Line Name
input string InpNameAverage0  = "TOP 0" ;       // Trend Line Name
input string InpNameAverage1  = "LOWER 0" ;     // Trend Line Name
//---
datetime ExtLastINAverage         = 0 ; // "0" -> D'1970.01.01 00:00';
datetime ExtLastINAverage0        = 0 ; // "0" -> D'1970.01.01 00:00';
datetime ExtLastINAverage1        = 0 ; // "0" -> D'1970.01.01 00:00';
datetime ExtPrevBars              = 0 ; // "0" -> D'1970.01.01 00:00';
//---
int ExtTimeOut= 10 ; // time out in seconds between trade operations
//+------------------------------------------------------------------+
//| MACD Sample expert class                                         |
//+------------------------------------------------------------------+
class CSampleExpert
  {
protected :
   double             m_adjusted_point;             // point value adjusted for 3 or 5 points
   CTrade            m_trade;                       // trading object
   CSymbolInfo       m_symbol;                     // symbol info object
   CPositionInfo     m_position;                   // trade position object
   CAccountInfo      m_account;                     // account info wrapper
   //--- indicators
   int                m_handle_ema;                 // moving average indicator handle
   //--- indicator buffers
   double             m_buff_EMA[];                 // EMA indicator buffer
   //--- indicator data for processing
   double             m_ema_current;
   double             m_ema_previous;
   //---
   double             m_take_profit;

public :
                     CSampleExpert( void );
                    ~CSampleExpert( void );
   bool               Init( void );
   void               Deinit( void );
   bool               Processing( void );

protected :
   bool               InitIndicators( void );
   bool               TrendOpened( void );
   bool               TrendOpened0( void );
   bool               TrendOpened1( void );
  };
//--- global expert
CSampleExpert ExtExpert;
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CSampleExpert::CSampleExpert( void ) : m_adjusted_point( 0 ),
   m_handle_ema( INVALID_HANDLE ),
   m_ema_current( 0 ),
   m_ema_previous( 0 ),
   m_take_profit( 0 )
  {
   ArraySetAsSeries (m_buff_EMA, true );
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CSampleExpert::~CSampleExpert( void )
  {
  }
//+------------------------------------------------------------------+
//| Initialization and checking for input parameters                 |
//+------------------------------------------------------------------+
bool CSampleExpert::Init( void )
  {
//--- initialize common information
   m_symbol.Name( Symbol ());                   // symbol
   m_trade.SetExpertMagicNumber(MACD_MAGIC); // magic
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
//--- tuning for 3 or 5 digits
   int digits_adjust= 1 ;
   if (m_symbol. Digits ()== 3 || m_symbol. Digits ()== 5 )
      digits_adjust= 10 ;
   m_adjusted_point=m_symbol. Point ()*digits_adjust;
//--- set default deviation for trading in adjusted points
   m_take_profit     =InpTakeProfit*m_adjusted_point;
//--- set default deviation for trading in adjusted points
   m_trade.SetDeviationInPoints( 3 *digits_adjust);
//---
   if (!InitIndicators())
       return ( false );
//--- succeed
   return ( true );
  }
//+------------------------------------------------------------------+
//| Initialization of the indicators                                 |
//+------------------------------------------------------------------+
bool CSampleExpert::InitIndicators( void )
  {
//--- create EMA indicator and add it to collection
   if (m_handle_ema== INVALID_HANDLE )
       if ((m_handle_ema= iCustom (m_symbol.Name(), Period (), "2 Obj Volatility_StepChannel" ))== INVALID_HANDLE )
        {
         printf ( "Error creating EMA indicator" );
         return ( false );
        }
//--- succeed
   return ( true );
  }
//+------------------------------------------------------------------+
//| Check for long position opening                                  |
//+------------------------------------------------------------------+
bool CSampleExpert::TrendOpened( void )
  {
   bool res= false ;
//--- check for long position (BUY) possibility
   if ( ObjectFind ( 0 ,InpNameAverage)< 0 )
       return ( true );

   MqlRates ratesAverage[];
   ArraySetAsSeries (ratesAverage, true );
   int start_pos= 0 ,count= 3 ;
   if ( CopyRates (m_symbol.Name(), Period (),start_pos,count,ratesAverage)!=count)
       return ( false );

   if (ratesAverage[ 0 ].time==ExtLastINAverage)
       return ( true );

   double value_by_time= ObjectGetValueByTime ( 0 ,InpNameAverage,ratesAverage[ 1 ].time);
   if (value_by_time== 0.0 )
       return ( true );

   if (ratesAverage[ 1 ].open<value_by_time && ratesAverage[ 1 ].close>value_by_time)
     {
       double price=m_symbol.Ask();
       double tp   =m_symbol.Bid()+m_take_profit;
       //--- open position
       if (m_trade.PositionOpen( Symbol (), ORDER_TYPE_BUY ,InpLots,price, 0.0 ,tp))
         printf ( "Position by %s to be opened" ,m_symbol.Name());
       else
        {
         printf ( "Error opening BUY position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
         printf ( "Open parameters : price=%f,TP=%f" ,price,tp);
        }
      res= true ;
     }
   if (ratesAverage[ 1 ].open>value_by_time && ratesAverage[ 1 ].close<value_by_time)
     {
       double price=m_symbol.Bid();
       double tp   =m_symbol.Ask()-m_take_profit;
       if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_SELL ,InpLots,price, 0.0 ,tp))
         printf ( "Position by %s to be opened" ,m_symbol.Name());
       else
        {
         printf ( "Error opening SELL position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
         printf ( "Open parameters : price=%f,TP=%f" ,price,tp);
        }       //--- in any case we must exit from expert
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position opening                                  |
//+------------------------------------------------------------------+
bool CSampleExpert::TrendOpened0( void )
  {
   bool res= false ;
//--- check for long position (BUY) possibility
   if ( ObjectFind ( 0 ,InpNameAverage0)< 0 )
       return ( true );

   MqlRates ratesAverage[];
   ArraySetAsSeries (ratesAverage, true );
   int start_pos= 0 ,count= 3 ;
   if ( CopyRates (m_symbol.Name(), Period (),start_pos,count,ratesAverage)!=count)
       return ( false );

   if (ratesAverage[ 0 ].time==ExtLastINAverage0)
       return ( true );

   double value_by_time= ObjectGetValueByTime ( 0 ,InpNameAverage0,ratesAverage[ 1 ].time);
   if (value_by_time== 0.0 )
       return ( true );

   if (ratesAverage[ 1 ].open<value_by_time && ratesAverage[ 1 ].close>value_by_time)
     {
       double price=m_symbol.Ask();
       double tp   =m_symbol.Bid()+m_take_profit;
       //--- open position
       if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_BUY ,InpLots,price, 0.0 ,tp))
         printf ( "Position by %s to be opened" ,m_symbol.Name());
       else
        {
         printf ( "Error opening BUY position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
         printf ( "Open parameters : price=%f,TP=%f" ,price,tp);
        }
      res= true ;
     }
   if (ratesAverage[ 1 ].open>value_by_time && ratesAverage[ 1 ].close<value_by_time)
     {
       double price=m_symbol.Bid();
       double tp   =m_symbol.Ask()-m_take_profit;
       if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_SELL ,InpLots,price, 0.0 ,tp))
         printf ( "Position by %s to be opened" ,m_symbol.Name());
       else
        {
         printf ( "Error opening SELL position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
         printf ( "Open parameters : price=%f,TP=%f" ,price,tp);
        }       //--- in any case we must exit from expert
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position opening                                  |
//+------------------------------------------------------------------+
bool CSampleExpert::TrendOpened1( void )
  {
   bool res= false ;
//--- check for long position (BUY) possibility
   if ( ObjectFind ( 0 ,InpNameAverage1)< 0 )
       return ( true );

   MqlRates ratesAverage[];
   ArraySetAsSeries (ratesAverage, true );
   int start_pos= 0 ,count= 3 ;
   if ( CopyRates (m_symbol.Name(), Period (),start_pos,count,ratesAverage)!=count)
       return ( false );

   if (ratesAverage[ 0 ].time==ExtLastINAverage1)
       return ( true );

   double value_by_time= ObjectGetValueByTime ( 0 ,InpNameAverage1,ratesAverage[ 1 ].time);
   if (value_by_time== 0.0 )
       return ( true );

   if (ratesAverage[ 1 ].open<value_by_time && ratesAverage[ 1 ].close>value_by_time)
     {
       double price=m_symbol.Ask();
       double tp   =m_symbol.Bid()+m_take_profit;
       //--- open position
       if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_BUY ,InpLots,price, 0.0 ,tp))
         printf ( "Position by %s to be opened" ,m_symbol.Name());
       else
        {
         printf ( "Error opening BUY position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
         printf ( "Open parameters : price=%f,TP=%f" ,price,tp);
        }
      res= true ;
     }
   if (ratesAverage[ 1 ].open>value_by_time && ratesAverage[ 1 ].close<value_by_time)
     {
       double price=m_symbol.Bid();
       double tp   =m_symbol.Ask()-m_take_profit;
       if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_SELL ,InpLots,price, 0.0 ,tp))
         printf ( "Position by %s to be opened" ,m_symbol.Name());
       else
        {
         printf ( "Error opening SELL position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
         printf ( "Open parameters : price=%f,TP=%f" ,price,tp);
        }       //--- in any case we must exit from expert
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| main function returns true if any position processed             |
//+------------------------------------------------------------------+
bool CSampleExpert::Processing( void )
  {
//--- refresh rates
   if (!m_symbol.RefreshRates())
       return ( false );
//--- refresh indicators
   if ( BarsCalculated (m_handle_ema)< 2 )
       return ( false );
   if ( CopyBuffer (m_handle_ema, 0 , 0 , 2 ,m_buff_EMA)!= 2 )
       return ( false );
//   m_indicators.Refresh();
//--- to simplify the coding and speed up access
//--- data are put into internal variables
   m_ema_current    =m_buff_EMA[ 0 ];
   m_ema_previous   =m_buff_EMA[ 1 ];
//--- it is important to enter the market correctly,
//--- but it is more important to exit it correctly...
//--- first check if position exists - try to select it
//--- no opened position identified
//--- no opened position identified
   datetime time_0= iTime (m_symbol.Name(), Period (), 0 );
   if (time_0==ExtPrevBars)
       return ( true );
   ExtPrevBars=time_0;
     {
       //--- try to close or modify long position
       if (TrendOpened()||TrendOpened0()||TrendOpened1())
         return ( true );
     }
//--- exit without position processing
   return ( false );
  }
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ( void )
  {
//--- create all necessary objects
   if (!ExtExpert.Init())
       return ( INIT_FAILED );
//--- secceed
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert new tick handling function                                |
//+------------------------------------------------------------------+
void OnTick ( void )
  {
   static datetime limit_time= 0 ; // last trade processing time + timeout
//--- don't process if timeout
   if ( TimeCurrent ()>=limit_time)
     {
       //--- check for data
       if ( Bars ( Symbol (), Period ())> 2 * 0 )
        {
         //--- change limit time by timeout in seconds if processed
         if (ExtExpert.Processing())
            limit_time= TimeCurrent ()+ExtTimeOut;
        }
     }
  }
//+------------------------------------------------------------------+
Документация по MQL5: Константы, перечисления и структуры / Константы объектов / Типы объектов
Документация по MQL5: Константы, перечисления и структуры / Константы объектов / Типы объектов
  • www.mql5.com
При создании графического объекта функцией ObjectCreate() необходимо указать тип создаваемого объекта, который может принимать одно из значений перечисления ENUM_OBJECT. Дальнейшие уточнения свойств созданного объекта возможно с помощью функций по работе с графическими объектами.
파일:
0002.mq5  28 kb
 
Aleksandr Klapatyuk :

여기 버전이 있습니다 - 내가 한 방법 - 손으로 그리는 추세선 에서 더 완벽하게 작동합니다.

설정 - 가지고 있는 것

별로! 설정 중 - 어느 브로커도 등록할 수 없습니다.

스냅샷2

 
Aleksandr Klapatyuk :

여기 버전이 있습니다 - 내가 한 방법 - 손으로 그리는 추세선 에서 더 완벽하게 작동합니다.

설정 - 가지고 있는 것

좋은 지표인 것 같습니다.

설정이 없는 전문가 - 이 표시기에서 이러한 결과를 제공합니다. 2 Obj Volatility_StepChannel.mq5  

스냅샷3

 

추가됨, 위치 수 , 편도 열기

 input uint    maxLimits        = 1 ;             // Кол-во Позиции Открыть в одну сторону
input double InpLots          = 0.1 ;           // Lots
input int     InpTakeProfit    = 50 ;             // Take Profit (in pips)
파일:
0003.mq5  29 kb
 
Aleksandr Klapatyuk :

추가됨, 위치 수 , 편도 열기

중간 추세선에서 추가 - 열리면 수평선을 그리며 가격을 따라 이동하며 명령을 설정할 수 있습니다.

약간 더 많은 설정

 //---
input uint    maxLimits                   = 1 ;             // Кол-во Позиции Открыть в одну сторону
input double InpLots                     = 0.1 ;           // Lots
input int     InpTakeProfit               = 50 ;             // Take Profit (in pips)
input string t0= "----- Trend Line Name ------" ;           // Trend Line Name
input string InpNameAverage              = "AVERAGE 0" ;   // Trend Line Name
input string InpNameAverage0             = "TOP 0" ;       // Trend Line Name
input string InpNameAverage1             = "LOWER 0" ;     // Trend Line Name
input string t1= "---   Obj:Trailing Line --- " ;           // Trailing Obj:Line
input string InpObjUpName                = "BUY" ;         // Obj: TOP (Horizontal Line) ВВЕРХУ
input ENUM_TRADE_COMMAND InpTradeCommand = open_sell;     // Obj:  command:
input string InpObjDownName              = "SELL" ;         // Obj: LOWER (Horizontal Line) ВНИЗУ
input ENUM_TRADE_COMMAND InTradeCommand  = open_buy;       // Obj:  command:
input ushort InpObjTrailingStop          = 25 ;             // Obj: Trailing Stop (distance from price to object, in pips)
input ushort InpObjTrailingStep          = 5 ;             // Obj: Trailing Step, in pips (1.00045-1.00055=1 pips)
input string t2= "------ Obj: Revers Buy and Sell --" ;     // Obj: Revers Buy and Sell
input bool    ObjRevers                   = false ;         // Obj: Revers
//---

스냅샷4

파일:
0004.mq5  78 kb
 
Aleksandr Klapatyuk :

중간 추세선에서 추가 - 열리면 수평선을 그리며 가격을 따라 이동하며 명령을 설정할 수 있습니다.

약간 더 많은 설정

몇 가지 기능이 더 추가되었습니다. 추세선에서 주어진 거리에 수평선을 던질 수 있습니다.

 //---
input uint    maxLimits                   = 1 ;             // Кол-во Позиции Открыть в одну сторону
input double InpLots                     = 0.1 ;           // Lots
input int     InpTakeProfit               = 50 ;             // Take Profit (in pips)
input string t0= "----- Trend Line Name ------" ;           // Trend Line Name
input string InpNameAverage              = "AVERAGE 0" ;   // Trend Line Name
input bool    InpObjHLine                 = false ;         // Obj: HLine
input string InpNameAverage0             = "TOP 0" ;       // Trend Line Name
input bool    InpObjHLine0                = false ;         // Obj: HLine
input string InpNameAverage1             = "LOWER 0" ;     // Trend Line Name
input bool    InpObjHLine1                = false ;         // Obj: HLine
input string t1= "---   Obj:Trailing Line --- " ;           // Trailing Obj:Line
/*
input string InpObjUpNamex               = "BUYx";        // Obj: TOP (Horizontal Line) ВВЕРХУ
input string InpObjDownNamex             = "SELLx";       // Obj: LOWER (Horizontal Line) ВНИЗУ
*/
input int     InpStep                     = 15 ;             // Obj: Шаг сетки, пунктов("0" -> false)
input string InpObjUpName                = "BUY" ;         // Obj: TOP (Horizontal Line) ВВЕРХУ
input ENUM_TRADE_COMMAND InpTradeCommand = open_buy;       // Obj:  command:
input string InpObjDownName              = "SELL" ;         // Obj: LOWER (Horizontal Line) ВНИЗУ
input ENUM_TRADE_COMMAND InTradeCommand  = open_sell;     // Obj:  command:
input ushort InpObjTrailingStop          = 25 ;             // Obj: Trailing Stop (distance from price to object, in pips)
input ushort InpObjTrailingStep          = 5 ;             // Obj: Trailing Step, in pips (1.00045-1.00055=1 pips)
input string t2= "------ Obj: Revers Buy and Sell --" ;     // Obj: Revers Buy and Sell
input bool    ObjRevers                   = false ;         // Obj: Revers
//---

스냅 사진

수평선이 나타나지 않도록 0으로 설정해야 합니다.

 input int     InpStep                     = 15 ;             // Obj: Шаг сетки, пунктов("0" -> false)
input ushort InpObjTrailingStop          = 25 ;             // Obj: Trailing Stop (distance from price to object, in pips)
파일:
0005.mq5  84 kb
 
Aleksandr Klapatyuk :

몇 가지 기능이 더 추가되었습니다. 추세선에서 주어진 거리에 수평선을 던질 수 있습니다.

수평선이 나타나지 않도록 0으로 설정해야 합니다.


수평선에서 또 다른 기회를 사용

테스트하려면 이 표시기가 필요합니다. https://www.mql5.com/en/code/1114

 input string t1= "---   Obj:Trailing Line --- " ;           // Trailing Obj:Line
input string InpObjUpNamex               = "R2" ;           // Obj: TOP (Horizontal Line) ВВЕРХУ
input string InpObjDownNamex             = "S2" ;           // Obj: LOWER (Horizontal Line) ВНИЗУ
input int     InpStep                     = 15 ;             // Obj: Шаг сетки, пунктов("0" -> false)

스냅샷2

Pivot Lines TimeZone
Pivot Lines TimeZone
  • www.mql5.com
Индикатор рисует уровни Pivot, промежуточные уровни Pivot и уровни Camarilla. Уровни могут отображаться индикаторными буферами (по всей истории) и/или только текущие уровни горизонтальными линиями. DayStartHour - Час времени начала дня. DayStartMinute - Минуты времени начала дня. PivotsBufers - Отображать уровни Pivot индикаторными буферами...
파일:
0006.mq5  87 kb