English Русский 中文 Español Deutsch 日本語 Português Français Italiano Türkçe
MQL5 마법사: EA가 모든 가격으로 보류 중인 주문을 열도록 가르치는 방법

MQL5 마법사: EA가 모든 가격으로 보류 중인 주문을 열도록 가르치는 방법

MetaTrader 5 | 3 9월 2021, 09:51
143 0
Vladimir Karputov
Vladimir Karputov

소개

MQL5 마법사를 사용하여 생성된 Expert Advisor는 현재 가격에서 고정된 거리에서만 보류 중인 주문을 열 수 있습니다. 이는 시장 상황이 변경되는 경우(예: 시장 변동성 변경) Expert Advisor가 새로운 매개변수로 다시 실행되어야 함을 의미합니다.

이것은 많은 거래 시스템에 적합하지 않습니다. 대부분의 경우 보류 중인 주문의 가격 수준은 거래 시스템에 의해 동적으로 결정됩니다. 그리고 현재 가격과의 거리는 끊임없이 변화하고 있습니다. 이 글에서는 MQL5 마법사를 사용하여 생성된 Expert Advisor를 수정하여 현재 가격에서 다양한 거리에서 보류 중인 주문을 열 수 있도록 하는 방법에 대해 설명합니다.


1. MQL5 마법사를 사용하여 생성된 Expert Advisor에서 보류 중인 주문을 여는 메커니즘

생성된 Expert Advisor의 헤더에는 아래와 같이 거의 동일한 코드가 있습니다.

//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
//--- inputs for expert
input string             Expert_Title="ExpertMySignalEnvelopes.mq5";      // Document name
ulong                    Expert_MagicNumber        =3915;        // 
bool                     Expert_EveryTick          =false;       // 
//--- inputs for main signal
input int                Signal_ThresholdOpen      =10;          // Signal threshold value to open [0...100]
input int                Signal_ThresholdClose     =10;          // Signal threshold value to close [0...100]
input double             Signal_PriceLevel         =0.0;         // Price level to execute a deal
input double             Signal_StopLevel          =85.0;        // Stop Loss level (in points)
input double             Signal_TakeLevel          =195.0;       // Take Profit level (in points)
input int                Signal_Expiration         =0;           // Expiration of pending orders (in bars)
input int                Signal_Envelopes_PeriodMA =13;          // Envelopes(13,0,MODE_SMA,...) Period of averaging
input int                Signal_Envelopes_Shift    =0;           // Envelopes(13,0,MODE_SMA,...) Time shift
input ENUM_MA_METHOD     Signal_Envelopes_Method   =MODE_SMA;    // Envelopes(13,0,MODE_SMA,...) Method of averaging
input ENUM_APPLIED_PRICE Signal_Envelopes_Applied  =PRICE_CLOSE; // Envelopes(13,0,MODE_SMA,...) Prices series
input double             Signal_Envelopes_Deviation=0.2;         // Envelopes(13,0,MODE_SMA,...) Deviation
input double             Signal_Envelopes_Weight   =1.0;         // Envelopes(13,0,MODE_SMA,...) Weight [0...1.0]
//--- inputs for money
input double             Money_FixLot_Percent      =10.0;        // Percent
input double             Money_FixLot_Lots         =0.1;         // Fixed volume
//+------------------------------------------------------------------+

Signal_PriceLevel 매개변수를 확인하세요. 기본적으로 Expert Advisor는 Signal_PriceLevel=0으로 생성됩니다. 이 매개변수는 현재 가격으로부터의 거리를 정의합니다. 0이면 현재 시장 가격으로 주문이 열립니다. 보류 중인 주문을 열려면 Signal_PriceLevel 매개변수에 대해 0이 아닌 값을 설정해야 합니다. 즉, Signal_PriceLevel은 음수와 양수 모두일 수 있습니다.

Signal_PriceLevel의 값은 일반적으로 상당히 큰 숫자입니다. 음수 값과 양수 값의 차이는 다음과 같습니다.

Signal_PriceLevel=-50:

그림 1. Signal_PriceLevel=-50

그림 1. Signal_PriceLevel=-50

Signal_PriceLevel=50:

그림 2. Signal_PriceLevel=50

그림 2. Signal_PriceLevel=50

따라서 Signal_PriceLevel=-50이면 현재 가격보다 낮은 가격으로 보류 중인 주문이 열리고 Signal_PriceLevel=50이면 보류 중인 주문이 현재 가격보다 좋은 가격으로 오픈합니다.

이 버전의 Expert Advisor는 매도 중지 (Sell Stop) 및 매수 중지 (Buy Stop) 주문을 엽니다.


2. 보류 중인 주문을 여는 가격과 거리에 대한 데이터는 어디에 저장합니까?

먼저 아래 그림을 살펴본 다음 주석으로 이동해 보겠습니다.

그림 3. 현재 가격과의 거리 데이터 저장

그림 3. 현재 가격과의 거리 데이터 저장

위 그림의 해석.

Expert Advisor MQL5 마법사를 사용하여 생성된 Expert Advisor입니다.

  • CExpert 클래스의 ExtExpert 개체는 글로벌 수준의 Expert Advisor에서 선언됩니다. 
  • 그런 다음 Expert Advisor의 OnInit() 함수에서 개체의 신호 에 대한 포인터를 선언합니다. CExpertSignal 클래스와 signal 개체는 new 연산자를 사용하여 즉시 생성됩니다.
  • OnInit() 함수에 있는 동안 ExtExpert 개체의 InitSignal 함수를 호출하고 signal 개체를 초기화합니다.
  • OnInit() 함수에 있는 동안 Signal_PriceLevel을 가져오는 signal 개체의 PriceLevel 함수를 호출합니다. 매개변수.

따라서 현재 가격으로부터의 거리가 저장되고 Expert Advisor에서 선언된 Signal_PriceLevel 매개변수는 CExpertSignal 클래스입니다.

CExpertSignal 클래스는 현재 가격으로부터의 거리 값을 보호된 클래스 범위로 선언된 m_price_level 변수에 저장합니다.

class CExpertSignal : public CExpertBase
  {
protected:
   //--- variables
   double            m_base_price;     // base price for detection of level of entering (and/or exit?)
   //--- variables for working with additional filters
   CArrayObj         m_filters;        // array of additional filters (maximum number of fileter is 64)
   //--- Adjusted parameters
   double            m_weight;         // "weight" of a signal in a combined filter
   int               m_patterns_usage; // bit mask of  using of the market models of signals
   int               m_general;        // index of the "main" signal (-1 - no)
   long              m_ignore;         // bit mask of "ignoring" the additional filter
   long              m_invert;         // bit mask of "inverting" the additional filter
   int               m_threshold_open; // threshold value for opening
   int               m_threshold_close;// threshold level for closing
   double            m_price_level;    // level of placing a pending orders relatively to the base price
   double            m_stop_level;     // level of placing of the "stop loss" order relatively to the open price
   double            m_take_level;     // level of placing of the "take profit" order relatively to the open price
   int               m_expiration;     // time of expiration of a pending order in bars


3. MQL5 마법사를 사용하여 생성된 Expert Advisor의 구조

Expert Advisor는 기능이 다른 여러 블록으로 구성됩니다.


그림 4. Expert Advisor의 구조 

그림 4. Expert Advisor의 구조

위 그림의 해석:

  • Expert 자문은 MQL5 마법사를 사용하여 생성된 Expert 자문입니다.
  • CExpert는 거래 전략 구현을 위한 기본 클래스입니다.
  • CExpertSignal은 거래 신호 생성기를 만들기 위한 기본 클래스입니다.
  • filter0 ... filtern은 거래 신호 생성기, CExpertSignal 클래스 자손입니다. 우리의 거래 시스템Envelopes 지표의 거래 신호 생성기를 기반으로 하지만 생성기 내의 신호가 수정되었다는 점에 유의해야 합니다. 우리는 섹션 7에서 이러한 변경 사항에 대해 이야기할 것입니다.


4. Expert Advisor 블록 수정 권장

MQL5 Wizard를 사용하여 생성된 Expert Advisor의 구조에서 알 수 있듯이 기본 클래스 블록이 있습니다. 기본 클래스는 표준 라이브러리의 일부입니다.

클래스 자체는 다른 기본 클래스의 자손이며 차례로 하나 이상의 기본 클래스로 구성됩니다. 아래에서 CExpertCExpertSignal이라는 두 클래스 코드의 처음 몇 줄을 찾을 수 있습니다.

//+------------------------------------------------------------------+
//|                                                       Expert.mqh |
//|                   Copyright 2009-2013, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#include "ExpertBase.mqh"
#include "ExpertTrade.mqh"
#include "ExpertSignal.mqh"
#include "ExpertMoney.mqh"
#include "ExpertTrailing.mqh"
//+------------------------------------------------------------------+
.
.
.
class CExpert : public CExpertBase

그리고

//+------------------------------------------------------------------+
//|                                                 ExpertSignal.mqh |
//|                   Copyright 2009-2013, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#include "ExpertBase.mqh"
.
.
.
class CExpertSignal : public CExpertBase

기본 클래스의 수정에 대해 강력히 반대합니다.

  1. MetaEditor가 업데이트되면 기본 클래스에 대한 모든 변경 사항이 무시되고 기본 클래스가 초기 상태로 복원됩니다.
  2. 이 경우 상속이 더 적절할 것입니다. 그러나 그런 다음 전체 표준 라이브러리를 수정해야 합니다.

대신에 Expert Advisor 및 거래 신호 생성기 모듈의 블록을 수정하는 것이 가장 좋습니다. 특히 거래 시스템에 이미 하나의 수정된 모듈인 거래 신호 생성기 Envelopes 지표가 사용중이기 때문이죠.

이제 해결되었습니다. 즉, 우린 Expert Advisor 블록과 거래 신호 생성기 블록을 변경할 것입니다.


5. 구현 논리

포인터는 Expert Advisor에서 거래 신호 생성기로 전달됩니다.

이를 위해 보호된 범위의 변수를 추가로 선언하고 Expert Advisor의 포인터를 내부 변수에 저장하는 를 작성해야 합니다.


  그림 5. 구현 논리

그림 5. 구현 논리


6. 거래 시스템

차트 기간은 D1입니다. 사용할 지표는 평균 주기가 13인 Envelopes와 지수 평균법입니다. Expert Advisor가 열 수 있는 주문 유형은 매도 중지 (Sell Stop)매수 중지 (Buy Stop)입니다.

이전 바가 강세였다면 매도 중지 주문을 설정했습니다. 이전 바가 약세였다면 매수 중지 주문을 설정했습니다. 다시 말해서, 우리는 철수를 희망하게 된 것입니다.

그림 6. 거래 시스템

그림 6. 거래 시스템

거래 시스템에서 요구하는 거래 신호를 생성하기 위해 거래 신호 생성기 SignalEnvelopes.mqh의 표준 모듈이 수정되었습니다.

여기에서 표준 라이브러리의 모든 거래 신호 생성기를 사용할 수 있습니다.


7. 거래 신호 생성기 수정. 바 가격 얻기

시작하겠습니다. 내 프로그램을 MQL5 저장소에 저장하는 것을 선호한다고 말씀드리고 싶습니다.

거래 신호 생성기 수정을 시작하기 위해 가장 먼저 해야 할 일은 빈 포함 파일을 만들고 파일에서 모든 것을 삭제한 다음 Envelopes 지표의 표준 거래 신호 생성기의 전체 내용을 붙여넣는 것입니다.

By default the trading signal generator must be located under ...MQL5\Include\Expert\Signal. 기본적으로 거래 신호 생성기는 ...MQL5\Include\Expert\Signal 아래에 있어야 합니다.

그림 7. MySignals 폴더 만들기

그림 7. MySignals 폴더 만들기

다음으로 MQL5 마법사를 사용하여 포함 파일을 생성합니다.

MetaEditor의 파일 메뉴에서 '새로 만들기'를 선택한 다음 '파일 포함(*.mqh)'을 선택합니다.

그림 8. MQL5 마법사. 포함 파일 만들기

그림 8. MQL5 마법사. 포함 파일 만들기

신호 생성기 클래스의 이름은 MySignalEnvelopes입니다.

그리고 다음 위치에 있습니다. Include\Expert\MySignals\MySignalEnvelopes. 지정해보겠습니다.

그림 9. MQL5 마법사. 포함 파일의 위치

그림 9. MQL5 마법사. 포함 파일의 위치

'마침'을 클릭하면 MQL5 마법사가 빈 템플릿을 생성합니다.

그런 다음 생성된 MySignalEnvelopes.mqh 파일을 MQL5 Storage에 추가해야 합니다.

그림 10. MQL5 스토리지. 파일 추가

그림 10. MQL5 스토리지. 파일 추가

파일이 추가되면 MQL5 Storage에 변경 사항을 커밋해야 합니다.

그림 11. MQL5 스토리지. 변경 사항 커밋

그림 11. MQL5 스토리지. 변경 사항 커밋

위의 단계를 완료하면 거래 신호 생성기를 수정할 수 있습니다.

생성기는 \Include\Expert\Signal\SignalEnvelopes.mqh 파일을 기반으로 하므로 파일의 전체 내용을 복사하여 원본 헤더만 남기고 생성기 파일에 붙여넣습니다.

//+------------------------------------------------------------------+
//|                                            MySignalEnvelopes.mqh |
//|                              Copyright © 2013, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2013, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#include <Expert\ExpertSignal.mqh>
// wizard description start
//+------------------------------------------------------------------+
//| Description of the class                                         |
//| Title=Signals of indicator 'Envelopes'                           |
//| Type=SignalAdvanced                                              |
//| Name=Envelopes                                                   |
//| ShortName=Envelopes                                              |
//| Class=CSignalEnvelopes                                           |
//| Page=signal_envelopes                                            |
//| Parameter=PeriodMA,int,45,Period of averaging                    |
//| Parameter=Shift,int,0,Time shift                                 |
//| Parameter=Method,ENUM_MA_METHOD,MODE_SMA,Method of averaging     |
//| Parameter=Applied,ENUM_APPLIED_PRICE,PRICE_CLOSE,Prices series   |
//| Parameter=Deviation,double,0.15,Deviation                        |
//+------------------------------------------------------------------+
// wizard description end
//+------------------------------------------------------------------+
//| Class CSignalEnvelopes.                                          |
//| Purpose: Class of generator of trade signals based on            |
//|          the 'Envelopes' indicator.                              |
//| Is derived from the CExpertSignal class.                         |
//+------------------------------------------------------------------+
class CSignalEnvelopes : public CExpertSignal
  {
protected:
   CiEnvelopes       m_env;            // object-indicator
   //--- adjusted parameters
   int               m_ma_period;      // the "period of averaging" parameter of the indicator
   int               m_ma_shift;       // the "time shift" parameter of the indicator
   ENUM_MA_METHOD    m_ma_method;      // the "method of averaging" parameter of the indicator
   ENUM_APPLIED_PRICE m_ma_applied;    // the "object of averaging" parameter of the indicator
   double            m_deviation;      // the "deviation" parameter of the indicator
   double            m_limit_in;       // threshold sensitivity of the 'rollback zone'
   double            m_limit_out;      // threshold sensitivity of the 'break through zone'
   //--- "weights" of market models (0-100)
   int               m_pattern_0;      // model 0 "price is near the necessary border of the envelope"
   int               m_pattern_1;      // model 1 "price crossed a border of the envelope"

public:
                     CSignalEnvelopes(void);
                    ~CSignalEnvelopes(void);
   //--- methods of setting adjustable parameters
   void              PeriodMA(int value)                 { m_ma_period=value;        }
   void              Shift(int value)                    { m_ma_shift=value;         }
   void              Method(ENUM_MA_METHOD value)        { m_ma_method=value;        }
   void              Applied(ENUM_APPLIED_PRICE value)   { m_ma_applied=value;       }
   void              Deviation(double value)             { m_deviation=value;        }
   void              LimitIn(double value)               { m_limit_in=value;         }
   void              LimitOut(double value)              { m_limit_out=value;        }
   //--- methods of adjusting "weights" of market models
   void              Pattern_0(int value)                { m_pattern_0=value;        }
   void              Pattern_1(int value)                { m_pattern_1=value;        }
   //--- method of verification of settings
   virtual bool      ValidationSettings(void);
   //--- method of creating the indicator and timeseries
   virtual bool      InitIndicators(CIndicators *indicators);
   //--- methods of checking if the market models are formed
   virtual int       LongCondition(void);
   virtual int       ShortCondition(void);

protected:
   //--- method of initialization of the indicator
   bool              InitMA(CIndicators *indicators);
   //--- methods of getting data
   double            Upper(int ind)                      { return(m_env.Upper(ind)); }
   double            Lower(int ind)                      { return(m_env.Lower(ind)); }
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CSignalEnvelopes::CSignalEnvelopes(void) : m_ma_period(45),
                                           m_ma_shift(0),
                                           m_ma_method(MODE_SMA),
                                           m_ma_applied(PRICE_CLOSE),
                                           m_deviation(0.15),
                                           m_limit_in(0.2),
                                           m_limit_out(0.2),
                                           m_pattern_0(90),
                                           m_pattern_1(70)
  {
//--- initialization of protected data
   m_used_series=USE_SERIES_OPEN+USE_SERIES_HIGH+USE_SERIES_LOW+USE_SERIES_CLOSE;
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CSignalEnvelopes::~CSignalEnvelopes(void)
  {
  }
//+------------------------------------------------------------------+
//| Validation settings protected data.                              |
//+------------------------------------------------------------------+
bool CSignalEnvelopes::ValidationSettings(void)
  {
//--- validation settings of additional filters
   if(!CExpertSignal::ValidationSettings())
      return(false);
//--- initial data checks
   if(m_ma_period<=0)
     {
      printf(__FUNCTION__+": period MA must be greater than 0");
      return(false);
     }
//--- ok
   return(true);
  }
//+------------------------------------------------------------------+
//| Create indicators.                                               |
//+------------------------------------------------------------------+
bool CSignalEnvelopes::InitIndicators(CIndicators *indicators)
  {
//--- check pointer
   if(indicators==NULL)
      return(false);
//--- initialization of indicators and timeseries of additional filters
   if(!CExpertSignal::InitIndicators(indicators))
      return(false);
//--- create and initialize MA indicator
   if(!InitMA(indicators))
      return(false);
//--- ok
   return(true);
  }
//+------------------------------------------------------------------+
//| Initialize MA indicators.                                        |
//+------------------------------------------------------------------+
bool CSignalEnvelopes::InitMA(CIndicators *indicators)
  {
//--- check pointer
   if(indicators==NULL)
      return(false);
//--- add object to collection
   if(!indicators.Add(GetPointer(m_env)))
     {
      printf(__FUNCTION__+": error adding object");
      return(false);
     }
//--- initialize object
   if(!m_env.Create(m_symbol.Name(),m_period,m_ma_period,m_ma_shift,m_ma_method,m_ma_applied,m_deviation))
     {
      printf(__FUNCTION__+": error initializing object");
      return(false);
     }
//--- ok
   return(true);
  }
//+------------------------------------------------------------------+
//| "Voting" that price will grow.                                   |
//+------------------------------------------------------------------+
int CSignalEnvelopes::LongCondition(void)
  {
   int result=0;
   int idx   =StartIndex();
   double close=Close(idx);
   double upper=Upper(idx);
   double lower=Lower(idx);
   double width=upper-lower;
//--- if the model 0 is used and price is in the rollback zone, then there is a condition for buying
   if(IS_PATTERN_USAGE(0) && close<lower+m_limit_in*width && close>lower-m_limit_out*width)
      result=m_pattern_0;
//--- if the model 1 is used and price is above the rollback zone, then there is a condition for buying
   if(IS_PATTERN_USAGE(1) && close>upper+m_limit_out*width)
      result=m_pattern_1;
//--- return the result
   return(result);
  }
//+------------------------------------------------------------------+
//| "Voting" that price will fall.                                   |
//+------------------------------------------------------------------+
int CSignalEnvelopes::ShortCondition(void)
  {
   int result  =0;
   int idx     =StartIndex();
   double close=Close(idx);
   double upper=Upper(idx);
   double lower=Lower(idx);
   double width=upper-lower;
//--- if the model 0 is used and price is in the rollback zone, then there is a condition for selling
   if(IS_PATTERN_USAGE(0) && close>upper-m_limit_in*width && close<upper+m_limit_out*width)
      result=m_pattern_0;
//--- if the model 1 is used and price is above the rollback zone, then there is a condition for selling
   if(IS_PATTERN_USAGE(1) && close<lower-m_limit_out*width)
      result=m_pattern_1;
//--- return the result
   return(result);
  }
//+------------------------------------------------------------------+

이제 우리는 코드의 일부를 수정하는 작업을 할 것입니다.

혼동을 피하기 위해 수정된 코드는 강조 표시됩니다.

//+------------------------------------------------------------------+
//|                                                     MySignal.mqh |
//|                              Copyright © 2013, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+

수정된 코드는 거래 신호 생성기에 복사하여 붙여넣어야하는 코드입니다. 이러한 강조 표시가 코드를 더 잘 이해하는 데 도움이 되기를 바랍니다.

우리는 거래 신호 생성기의 자체 클래스를 작성하기 때문에 그 이름은 기본 클래스의 이름과 달라야 합니다. 따라서 전체 코드에서 CSignalEnvelopes를 CMySignalEnvelopes로 바꿉니다.

그림 12. 클래스 이름 바꾸기

그림 12. 클래스 이름 바꾸기

거래 신호 생성기 클래스가 해당 이름으로 MQL5 마법사에 표시되도록 하려면 설명 블록에서 클래스 이름을 변경하십시오.

//| Title=Signals of indicator 'Envelopes'                           |

에게

//| Title=Signals of indicator 'MySignalEnvelopes'                   |

MA 기간 값 변경

//| Parameter=PeriodMA,int,45,Period of averaging                    |

~ 13(이것은 내 제안일 뿐이며 원하는 값을 설정할 수 있음)

//| Parameter=PeriodMA,int,13,Period of averaging                    |

또한 Deviation 매개변수도 수정합니다.

//| Parameter=Deviation,double,0.15,Deviation                        |

더 큰 값을 설정하여

//| Parameter=Deviation,double,1.15,Deviation                        |

구현 로직에 따르면 메인 신호에 대한 포인터를 저장할 내부 변수를 선언해야 합니다.

이것은 내부 변수여야 하므로(거래 신호 생성기 클래스 범위 내에서만) 다음 코드 블록에 추가됩니다.

protected:
   CiEnvelopes       m_env;          // object-indicator
   //--- adjusted parameters
   int               m_ma_period;    // the "period of averaging" parameter of the indicator
   int               m_ma_shift;     // the "time shift" parameter of the indicator
   ENUM_MA_METHOD    m_ma_method;     // the "method of averaging" parameter of the indicator
   ENUM_APPLIED_PRICE m_ma_applied;    // the "object of averaging" parameter of the indicator
   double            m_deviation;    // the "deviation" parameter of the indicator
   //--- "weights" of market models (0-100)
   int               m_pattern_0;      // model 0
   CExpertSignal    *m_signal;         // storing the pointer to the main signal

또한 코드에서 불필요한 변수를 삭제했습니다. 

주 신호에 대한 포인터를 저장하는 방법은 '주 신호에 대한 포인터를 설정하는 방법'이라는 다른 코드 블록에서 선언됩니다. 여기서도 관련 없는 몇 가지 방법을 삭제했습니다.

public:
                     CMySignalEnvelopes(void);
                    ~CMySignalEnvelopes(void);
   //--- methods of setting adjustable parameters
   void              PeriodMA(int value)                 { m_ma_period=value;        }
   void              Shift(int value)                    { m_ma_shift=value;         }
   void              Method(ENUM_MA_METHOD value)        { m_ma_method=value;        }
   void              Applied(ENUM_APPLIED_PRICE value)   { m_ma_applied=value;       }
   void              Deviation(double value)             { m_deviation=value;        }
   //--- methods of adjusting "weights" of market models
   void              Pattern_0(int value)                { m_pattern_0=value;        }
   //--- method of verification of settings
   virtual bool      ValidationSettings(void);
   //--- method of creating the indicator and timeseries
   virtual bool      InitIndicators(CIndicators *indicators);
   //--- methods of checking if the market models are formed
   virtual int       LongCondition(void);
   virtual int       ShortCondition(void);
   //--- method of setting the pointer to the main signal
   virtual bool      InitSignal(CExpertSignal *signal=NULL);

이제 생성자에서 일부 수정된 매개변수를 지정하고 더 이상 필요하지 않은 변수를 삭제하겠습니다.

//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CMySignalEnvelopes::CMySignalEnvelopes(void) : m_ma_period(13),
                                               m_ma_shift(0),
                                               m_ma_method(MODE_SMA),
                                               m_ma_applied(PRICE_CLOSE),
                                               m_deviation(1.15),
                                               m_pattern_0(50)  

이 시점에서 거래 시스템에 따라 거래 신호 생성 로직을 수정할 수 있습니다.

매수 신호를 담당하는 코드 블록:

int CMySignalEnvelopes::LongCondition(void)
  {
   int result=0;
   int idx   =StartIndex();
   double close=Close(idx);
   double upper=Upper(idx);
   double lower=Lower(idx);
   double width=upper-lower;
//--- if the model 0 is used and price is in the rollback zone, then there is a condition for buying
   if(IS_PATTERN_USAGE(0) && close<lower+m_limit_in*width && close>lower-m_limit_out*width)
      result=m_pattern_0;
//--- if the model 1 is used and price is above the rollback zone, then there is a condition for buying
   if(IS_PATTERN_USAGE(1) && close>upper+m_limit_out*width)
      result=m_pattern_1;
//--- return the result
   return(result);
  }

필요한 변경 사항에 따라 아래와 같이 표시됩니다.

int CMySignalEnvelopes::LongCondition(void) //---buy
  {
   int result=0;
   int idx   =StartIndex();
   double open=Open(idx);
   double close=Close(idx);
   double prlevel;
      if(IS_PATTERN_USAGE(0) && close<open)
        {
         prlevel=GetPriceLevelStopp(open,Open(0));
         m_signal.PriceLevel(prlevel);
         result=m_pattern_0;
        }
//--- return the result
   return(result);
  }

매도 신호를 담당하는 코드 블록:

int CMySignalEnvelopes::ShortCondition(void)
  {
   int result  =0;
   int idx     =StartIndex();
   double close=Close(idx);
   double upper=Upper(idx);
   double lower=Lower(idx);
   double width=upper-lower;
//--- if the model 0 is used and price is in the rollback zone, then there is a condition for selling
   if(IS_PATTERN_USAGE(0) && close>upper-m_limit_in*width && close<upper+m_limit_out*width)
      result=m_pattern_0;
//--- if the model 1 is used and price is above the rollback zone, then there is a condition for selling
   if(IS_PATTERN_USAGE(1) && close<lower-m_limit_out*width)
      result=m_pattern_1;
//--- return the result
   return(result);
  }

필요한 변경 사항에 따라 아래와 같이 표시됩니다.

int CMySignalEnvelopes::ShortCondition(void) //---sell
  {
   int result  =0;
   int idx     =StartIndex();
   double open=Open(idx);
   double close=Close(idx);
   double prlevel;
      if(IS_PATTERN_USAGE(0) && close>open)
        {
         prlevel=GetPriceLevelStopp(Open(0),open);
         m_signal.PriceLevel(prlevel);
         result=m_pattern_0;
        }
//--- return the result
   return(result);
  }


8. 신호 코드 블록에 대한 몇 가지 설명

특정 신호에 대한 필수 조건이 충족되면 현재 가격과의 거리 값인 '20' 또는 '15'와 같은 숫자를 반환하는 GetPriceLevelStopp 를 호출합니다.

그런 다음 m_signal 개체의 PriceLevel 를 호출합니다(대기 주문 수준 가격을 결정하기 위한 거리를 설정함). m_signal은 주 신호에 대한 포인터를 저장하는 CExpertSignal 클래스 개체임을 상기해야 합니다.

GetPriceLevelStopp 의 코드는 다음과 같습니다.

double CMySignalEnvelopes::GetPriceLevelStopp(double price_0,double min)
  {
   double level;
   double temp;
   temp-=(price_0-min)/PriceLevelUnit();
   level=NormalizeDouble(temp,0);
   return(level);
  }

클래스 헤더에서 이 를 선언해야 합니다.

protected:
   //--- method of initialization of the indicator
   bool              InitMA(CIndicators *indicators);
   //--- methods of getting data
   double            Upper(int ind)                      { return(m_env.Upper(ind)); }
   double            Lower(int ind)                      { return(m_env.Lower(ind)); }
   double            GetPriceLevelStopp(double price,double min);
  };

우리가 필요로 하는 또 다른 방법은 메인 신호에 대한 포인터를 내부 변수에 전달하는 방법입니다.

bool CMySignalEnvelopes::InitSignal(CExpertSignal *signal)
  {
   m_signal=signal;
   return(true);
  }

 그런 다음 MQL5 마법사에서 Expert Advisor를 만들고 여기에 신호 모듈 'MySignalEnvelopes'를 포함해야 합니다.

또한 MQL5 마법사를 사용하여 생성된 Expert Advisor의 코드에 InitSignal 호출을 추가해야 합니다.

//--- Set filter parameters
   filter0.PeriodMA(Signal_Envelopes_PeriodMA);
   filter0.Shift(Signal_Envelopes_Shift);
   filter0.Method(Signal_Envelopes_Method);
   filter0.Applied(Signal_Envelopes_Applied);
   filter0.Deviation(Signal_Envelopes_Deviation);
   filter0.Weight(Signal_Envelopes_Weight);
   filter0.InitSignal(signal);
//...

Expert Advisor의 작동을 더 잘 시각화하기 위해 짧은 비디오를 제공했습니다.

MQL5 Wizard를 사용하여 생성한 Expert Advisor의 코드와 시그널 모듈의 코드는 글에 첨부되어 있습니다.

아래에서 Expert Advisor의 테스트 결과를 볼 수 있습니다. EURUSD 및 USDJPY에 대해 테스트 기간 2013.01.01 - 2013.09.01, 기간 - D1, 손절매 수준 = 85, 이익실현 수준 = 195 매개변수로 테스트되었습니다.

그림 13. D1에서 EURUSD 테스트

그림 13. D1에서 EURUSD 테스트

그림 14. D1에서 USDJPY 테스트

그림 14. D1에서 USDJPY 테스트


결론

우리는 현재 가격에서 어떤 거리에서도 보류 주문을 설정할 수 있는 기능의 구현을 위해 거래 신호 모듈의 코드를 수정하는 방법을 보았습니다. 이는 이전 바 또는 이동 평균 값의 마감 또는 오픈 가격일 수 있습니다. 많은 옵션이 있습니다. 중요한 것은 보류 중인 주문에 대해 시작 가격을 설정할 수 있다는 것입니다.

이 글은 우리가 메인 시그널에 대한 포인터에 액세스하는 방법을 보여주었고 따라서 CExpertSignal 클래스 메소드에 액세스할 수 있습니다. 나는 이 글이 보류 중인 명령으로 거래하는 거래자에게 유용할 것이라고 믿습니다.


MetaQuotes 소프트웨어 사를 통해 러시아어가 번역됨.
원본 기고글: https://www.mql5.com/ru/articles/723

사용 가능한 기술 칵테일로 MQL5 고객을 놀래켜보세요! 사용 가능한 기술 칵테일로 MQL5 고객을 놀래켜보세요!
MQL5는 프로그래머가 MetaTrader 환경 내에서 원하는 모든 작업을 수행할 수 있는 매우 완전한 기능 세트와 객체 지향 API를 제공합니다. 그러나 웹 기술은 오늘날 매우 다재다능한 도구로, 매우 구체적인 작업을 수행해야 하거나 고객을 뭔가 다른 것으로 놀라게 하고 싶거나 특정 MT5 Standard Library를 마스터할 시간이 충분하지 않은 경우에 도움이 될 수 있습니다. 오늘의 연습에서는 놀라운 기술 칵테일을 만드는 동시에 개발 시간을 관리할 수 있는 방법에 대한 실용적인 예를 안내해드립니다.
자동 뉴스 거래자 구축 자동 뉴스 거래자 구축
이것은 처음부터 간단한 OO EA를 빌드하는 방법을 보여주고 객체 지향 프로그래밍에 대한 몇 가지 팁을 제공한 또 다른 MQL5 OOP 클래스 글의 연속입니다. 오늘은 뉴스를 거래할 수 있는 EA를 개발하는 데 필요한 기술적인 기본 사항을 보여 드리겠습니다. 제 목표는 계속해서 OOP에 대한 아이디어를 제공하고 파일 시스템으로 작업하는 이 일련의 글에서 새로운 주제를 다루는 것입니다.
선형 거래 시스템을 강화하세요 선형 거래 시스템을 강화하세요
오늘의 글에서는 중급 MQL5 프로그래머가 소위 지수 기법을 쉽게 구현하여 선형 거래 시스템(고정 랏)에서 더 많은 이익을 얻을 수 있는 방법을 보여줍니다. 이는 그 결과 주식 곡선 성장이 포물선의 형태를 취하는 기하학적 또는 지수적이기 때문입니다. 특히, Ralph Vince가 개발한 고정 분수 위치 크기 조정의 실용적인 MQL5 변형을 구현합니다.
MQL5 마법사 및 Hlaiman EA 생성기를 사용하여 신경망 EA 생성 MQL5 마법사 및 Hlaiman EA 생성기를 사용하여 신경망 EA 생성
이 글에서는 MQL5 Wizard 및 Hlaiman EA Generator를 사용하여 신경망 EA를 자동으로 생성하는 방법을 설명합니다. 이론적인 정보 전체를 배우고 코드를 작성하지 않고도 신경망 작업을 쉽게 시작할 수 있는 방법을 보여줍니다.