MQL5 마법사: 미결 포지션의 후행 모듈을 만드는 방법
소개
MetaTrader 5에는 거래 아이디어를 빠르게 확인할 수 있는 강력한 도구가 있습니다. 이것은 거래 전략 MQL5 마법사 생성기입니다. Expert Advisors의 소스 코드를 자동으로 생성하기 위한 MQL5 마법사의 사용은 "MQL5 마법사: 프로그래밍 없이 Expert Advisors 생성" 문서에 설명되어 있습니다. 코드 생성 시스템의 개방성은 거래 신호, 자금 관리 시스템 및 후행 모듈의 사용자 정의 클래스로 표준 클래스를 보완할 수 있습니다.
이 글에서는 MQL5 마법사에서 추가 사용을 위해 후행 개방 위치의 모듈을 작성하는 원칙을 설명합니다.
MQL5 마법사를 사용하여 생성된 Expert Advisor는 다음 네 가지 기본 클래스를 기반으로 합니다.
그림 1. 기본 클래스의 구조 CExpert.
CExpert 클래스(또는 하위 클래스)는 거래 로봇의 주요 "엔진"입니다. CExpert 클래스의 인스턴스는 CExpertSignal, CExpertMoney 및 CExpertTrailing 클래스(또는 해당 하위 클래스)의 인스턴스를 포함합니다.
- CExpertSignal - 거래 신호의 주요 생성기입니다. CExpert 클래스에 포함된 CExpertSignal 서브클래스의 인스턴스는 Expert Advisor에게 시장 진입 가능성, 진입 레벨 및 내부 알고리즘을 기반으로 한 보호 주문 설정에 대한 정보를 제공합니다. 거래 작업 수행에 대한 최종 결정은 Expert Advisor이 내립니다. "MQL5 마법사: 거래 신호 모듈을 만드는 방법" 글에서 거래 신호 모듈을 작성하는 방법에 대해 읽을 수 있습니다.
- CExpertMoney는 자금과 위험을 관리하는 주요 시스템입니다. CExpertMoney 서브클래스의 인스턴스는 개설될 포지션의 양과 배치될 보류 주문을 계산합니다. 볼륨에 대한 최종 결정은 Expert Advisor입니다. 자금 및 위험 관리 모듈의 개발 원칙은 "MQL5 마법사: 자금 및 위험 관리 모듈을 만드는 방법" 문서에 설명되어 있습니다.
- CExpertTrailing은 열린 포지션을 추적하는 주요 모듈입니다. CExpertTrailing 서브클래스의 인스턴스는 포지션의 보호 명령을 수정해야 하는 경우 Expert Advisor에게 알려줍니다. 주문 수정에 대한 최종 결정은 Expert Advisor가 합니다.
그 외에도 다음 클래스 인스턴스는 CExpert 클래스의 멤버입니다.
- CExpertTrade(거래 작업 수행용)
- CIIndicators(Expert Advisor 작업에 사용되는 지표 및 시계열 관리용)
- CSymbolInfo(심볼에 대한 정보 가져오기)
- CAAccountInfo(거래 계정 상태에 대한 정보 가져오기)
- CPositionInfo (포지션에 대한 정보 가져오기)
- CORderInfo(대기 중인 주문에 대한 정보 가져오기)
또한 이 텍스트에서 "Expert Advisor"이라고 할 때 하위 클래스의 CExpert 클래스 인스턴스를 의미합니다.
CExpert 클래스와 작업 과정에 대한 자세한 설명은 별도의 글에서 설명하겠습니다.
1. 기본 클래스 CExpertTrailing
CExpertTrailing은 다음 공개 위치 모듈의 기초입니다. "우주"와 상호작용하기 위해 CExpertTrailing 클래스에는 공개 가상 메소드 세트가 있습니다.
초기화 | 기술 |
가상 초기화 | 클래스 인스턴스의 초기화는 모듈의 데이터와 EA의 데이터의 동기화를 제공합니다. |
가상 검증 설정 | 설정된 매개변수의 유효성 검사 |
가상 초기 지표 | 거래 신호 생성기 작동에 필요한 모든 지표 및 시계열 생성 및 초기화 |
포지션 변경 신호 |
|
스탑 오더에 대한 새로운 가격 결정과 함께 롱 포지션 수정을 위한 신호 생성 | |
스탑 오더에 대한 새로운 가격 결정과 함께 매도 포지션 수정을 위한 신호 생성 |
방법 설명
1.1. 초기화 방법
1.1.1 초기화
Init() 메소드는 Expert Advisor에 클래스 인스턴스를 추가한 직후 자동 호출됩니다. 메소드를 재정의할 필요가 없습니다.
virtual bool Init(CSymbolInfo* symbol, ENUM_TIMEFRAMES period, double adjusted_point);
1.1.2 검증 설정
ValidationSettings() 메소드는 모든 매개변수를 설정한 후 Expert Advisor에서 호출됩니다. 설정 설정이 있는 경우 메소드를 재정의해야 합니다.
virtual bool ValidationSettings();
재정의된 메소드는 모든 매개변수가 올바른 경우 true를 반환해야 합니다(사용에 적합). 매개변수 중 하나라도 유효하지 않으면 매개변수는 false를 반환해야 합니다(더 이상의 작업은 불가능함).
1.1.3 초기 지표
InitIndicators() 메소드는 필요한 모든 지표와 시계열을 만들고 초기화합니다. 모든 매개변수가 설정되고 검증된 후 Expert Advisor에서 호출됩니다. 거래 신호 생성자가 하나 이상의 지표 또는 시계열을 사용하는 경우 이 방법을 재정의해야 합니다.
virtual bool InitIndicators(CIndicators* indicators);
지표 및/또는 시계열은 해당 표준 라이브러리를 통해 사용해야 합니다. 모든 지표 및/또는 시계열의 포인터는 Expert Advisor 지표 컬렉션에 추가되어야 합니다(포인터가 매개변수로 전달됨).
재정의된 메소드는 지표 및/또는 시계열을 사용한 모든 조작이 성공한 경우 true를 반환해야 합니다(사용하기에 적합함). 지표 및/또는 시계열을 사용하여 하나 이상의 작업이 실패한 경우 메소드는 false를 반환해야 합니다(더 이상의 작업은 불가능함).
1.2. 위치 변경 신호 확인 방법
1.2.1 CheckTrailingStopLong
CheckTrailingStopLong() 메소드는 손절매 주문(필요한 경우 이익실현 주문도 포함)의 새 가격을 정의하여 매수 포지션 수정 신호를 생성합니다. 롱 포지션을 수정할 필요가 있는지 여부를 결정하기 위해 Expert Advisor가 명령을 내리게 됩니다. 롱 포지션 수정 신호를 생성하려는 경우 재정의해야 합니다.
virtual bool CheckTrailingStopLong(CPositionInfo* position,double& sl,double& tp)
이 방법은 롱 포지션의 수정 조건을 확인하는 알고리즘을 구현해야 합니다. 조건이 충족되면 sl 변수(필요한 경우 tp도 포함)에 적절한 값이 할당되어야 하고 메소드는 true를 반환해야 합니다. sl 및 tp 변수에 대한 링크는 매개변수로 전달되어야 합니다. 조건이 충족되지 않으면 메소드는 false를 반환해야 합니다.
1.2.2 CheckTrailingStopShort
CheckTrailingStopShort() 메소드는 매도 포지션 수정 신호를 생성하여 손절매 주문(필요한 경우 이익실현 주문도 포함)의 새 가격을 결정합니다. 숏 포지션 수정이 필요한지 여부를 결정하기 위해 Expert Advisor가 명령을 내리게 됩니다. 숏 포지션 수정 신호를 생성하려면 이 메소드를 재정의해야 합니다.
virtual bool CheckTrailingStopShort(CPositionInfo* position,double& sl,double& tp)
메소드는 숏 포지션을 수정하기 위해 조건을 확인하는 알고리즘을 구현해야 합니다. 조건이 충족되면 sl 변수(필요한 경우 tp도 포함)에 적절한 값이 할당되어야 하고 메소드는 true를 반환해야 합니다. sl 및 tp 변수에 대한 링크는 매개변수로 전달되어야 합니다. 조건이 충족되지 않으면 메소드는 false를 반환해야 합니다.
2. 열린 포지션를 따르기 위한 나만의 모듈 작성
이제 기본 클래스 CExpertTrailing의 구조를 검토한 후 열린 포지션을 따르기 위한 고유한 모듈을 만들 수 있습니다.
위에서 언급한 바와 같이 CExpertTrailing 클래스는 공개 가상 "로프"의 집합입니다. 이 메소드를 사용하면 Expert Advisor가 보호 명령 수정의 필요성에 대한 후행 열린 포지션 모듈의 의견을 알 수 있습니다.
따라서 우리의 주요 목표는 CExpertTrailing 클래스에서 파생된 열린 포지션을 따르고 적절한 가상 메소드를 재정의하여 필요한 알고리즘을 구현하기 위한 자체 클래스를 만드는 것입니다.
우리의 두 번째 목표(그만큼 중요하지 않음)는 MQL5 Wizard에 클래스를 "보이게" 만드는 것입니다. 하지만, 먼저.
2.1. 거래 신호 생성기 클래스 생성
시작합시다.
먼저 mqh 확장자를 가진 포함 파일을 생성합니다(예: 동일한 MQL5 마법사 사용).
파일 메뉴에서 "만들기"를 선택하고(또는 Ctrl+N 키 조합을 누름) 포함된 파일의 생성을 나타냅니다.
그림 2. MQL5 마법사를 사용하여 포함 파일을 작성하십시오.
파일이 후행 열린 위치의 모듈로 MQL5 Wizard에 의해 "감지"되도록 하려면 Include\Expert\ 폴더에 파일을 생성해야 합니다.
표준 라이브러리에서 휴지통을 제거하려면 Include\Expert\Trailing\MyTrailing 폴더를 생성합니다. 여기에서 МQL5 마법사에서 다음 매개변수를 지정하여 SampleTrailing.mqh 파일을 생성합니다.
그림 3. 포함 파일의 포지션을 설정합니다.
MQL5 Wizard 작업의 결과로 다음과 같은 패턴이 나타납니다.
//+------------------------------------------------------------------+ //| SampleTrailing.mqh | //| Copyright 2010, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2010, MetaQuotes Software Corp." #property link "https://www.mql5.com" //+------------------------------------------------------------------+ //| defines | //+------------------------------------------------------------------+ // #define MacrosHello "Hello, world!" // #define MacrosYear 2010 //+------------------------------------------------------------------+ //| DLL imports | //+------------------------------------------------------------------+ // #import "user32.dll" // int SendMessageA(int hWnd,int Msg,int wParam,int lParam); // #import "my_expert.dll" // int ExpertRecalculate(int wParam,int lParam); // #import //+------------------------------------------------------------------+ //| EX5 imports | //+------------------------------------------------------------------+ // #import "stdlib.ex5" // string ErrorDescription(int error_code); // #import //+------------------------------------------------------------------+
다음은 "수동" 작업일 뿐입니다. 불필요한 부분을 제거하고 필요한 것을 추가하십시오(표준 라이브러리의 ExpertTrailing.mqh 파일 및 현재 비어 있는 클래스 설명 포함).
//+------------------------------------------------------------------+ //| SampleTrailing.mqh | //| Copyright 2010, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2010, MetaQuotes Software Corp." #property link "https://www.mql5.com" //+------------------------------------------------------------------+ //| include files | //+------------------------------------------------------------------+ #include <Expert\ExpertTrailing.mqh> //+------------------------------------------------------------------+ //| Class CSampleTrailing. | //| Purpose: Class for trailing of open positions. | //| Is derived from the CExpertTrailing class. | //+------------------------------------------------------------------+ class CSampleTrailing : public CExpertTrailing { }; //+------------------------------------------------------------------+
이제 알고리즘을 선택해야 합니다.
후행 오픈 포지션 모듈의 기초로 다음 알고리즘을 사용하겠습니다. 가격이 지정된 거리만큼 필요한 방향으로 이동하는 경우 중지 주문을 무손실 수준으로 이동합니다. 이것을 우리 파일에 반영하십시오.
//+------------------------------------------------------------------+ //| SampleTrailing.mqh | //| Copyright 2010, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2010, MetaQuotes Software Corp." #property link "https://www.mql5.com" //+------------------------------------------------------------------+ //| include files | //+------------------------------------------------------------------+ #include <Expert\ExpertTrailing.mqh> //+------------------------------------------------------------------+ //| Class CSampleTrailing. | //| Purpose: Class for trailing of open positions by | //| moving the Stop order "to the loseless level". | //| Is derived from the CExpertTrailingclass. | //+------------------------------------------------------------------+ class CSampleTrailing : public CExpertTrailing { }; //+------------------------------------------------------------------+
아니요, 보호 명령 수정에 대한 결정을 내리는 데 필요한 데이터를 정의합시다. 우리의 경우 - 포인트로 수정된 위치의 이익입니다.
다음 열린 위치에 대한 모듈 설정 매개변수 목록을 정의합니다. 두 개의 매개변수가 필요합니다.
- Stop 주문을 무손실 수준으로 이동하는 것을 제안하는 데 필요한 포지션 이익 포인트 수.
- 무손실 수준, 즉 이동된 정지 주문으로 고정한 이익 포인트 수입니다.
모듈의 설정은 클래스의 보호된 데이터 멤버에 저장됩니다. 설정에 대한 액세스는 적절한 공개 방법을 통해 구현됩니다.
다음 변경 사항을 파일에 포함시켜봅시다:
//+------------------------------------------------------------------+ //| SampleTrailing.mqh | //| Copyright 2010, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2010, MetaQuotes Software Corp." #property link "https://www.mql5.com" //+------------------------------------------------------------------+ //| include files | //+------------------------------------------------------------------+ #include <Expert\ExpertTrailing.mqh> //+------------------------------------------------------------------+ //| Class CSampleTrailing. | //| Purpose: Class for trailing of open positions | //| by moving Stop order to a lossless level. | //| Is derived from the CExpertTrailing class. | //+------------------------------------------------------------------+ class CSampleTrailing : public CExpertTrailing { protected: int m_profit; //threshold level of profit int m_stop_level; // lossless level public: //--- methods of setting adjustable parameters void Profit(int value) { m_profit=value; } void StopLevel(int value) { m_stop_level=value; } }; //+------------------------------------------------------------------+
조정 가능한 매개변수를 기본값으로 초기화하려면 클래스 생성자를 추가해야 합니다.
설정을 확인하려면 가상 메소드 ValidationSettings를 재정의합니다(기본 클래스에 대한 설명에 따름).
클래스 설명:
//+------------------------------------------------------------------+ //| SampleTrailing.mqh | //| Copyright 2010, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2010, MetaQuotes Software Corp." #property link "https://www.mql5.com" //+------------------------------------------------------------------+ //| include files | //+------------------------------------------------------------------+ #include <Expert\ExpertTrailing.mqh> //+------------------------------------------------------------------+ //| Class CSampleTrailing. | //| Purpose: Class for trailing of open positions | //| by moving Stop order to a lossless level. | //| Is derived from the CExpertTrailing class. | //+------------------------------------------------------------------+ class CSampleTrailing : public CExpertTrailing { protected: int m_profit; // threshold level of profit int m_stop_level; // lossless level public: CSampleTrailing(); //--- methods of setting adjustable parameters void Profit(int value) { m_profit=value; } void StopLevel(int value) { m_stop_level=value; } //--- method of validating the adjustable parameters virtual bool ValidationSettings(); }; //+------------------------------------------------------------------+
ValidationSettings() 메소드 구현:
//+------------------------------------------------------------------+ //| Validation of adjustable parameters. | //| INPUT: no. | //| OUTPUT: true if parameter are correct, false - if not. | //| REMARK: no. | //+------------------------------------------------------------------+ bool CSampleTrailing::ValidationSettings() { if(!CExpertTrailing::ValidationSettings()) return(false); //--- check wheter the Init method is called if(m_symbol==NULL) return(false); //--- check parameters if((m_profit-m_stop_level)*m_adjusted_point<=m_symbol.StopsLevel()*m_symbol.Point() && m_profit!=0.0) { printf(__FUNCTION__+": threshold level of profit must be greater than the level of setting of orders"); return(false); } //--- ok return(true); }
모든 준비 작업이 완료되었습니다.
알고리즘을 다시 자세히 살펴보겠습니다.
1. 다음 조건이 충족되면 롱 포지션 수정 신호가 나타납니다.
- 모듈 설정의 매개변수는 포지션을 수정해야 함을 의미합니다(Profit=0으로 설정하면 수정이 수행되지 않음).
- 포지션은 아직 수정되지 않았습니다(정지 주문은 무손실 수준으로 이동되지 않음).
- 위치의 이익이 매개변수에 설정된 임계값 수준을 초과했습니다.
이 경우 설정에 따라 중지 순서를 수정하도록 제안합니다. 이를 위해 가상 메소드 CheckTrailingStopLong을 재정의하고 해당 기능으로 채우십시오.
2. 숏 포지션 수정 신호는 다음 조건이 충족될 때 나타납니다.
- 모듈 설정의 매개변수는 포지션을 수정해야 함을 의미합니다(Profit=0으로 설정하면 수정이 수행되지 않음).
- 포지션은 아직 수정되지 않았습니다(정지 주문은 무손실 수준으로 이동되지 않음).
- 위치의 이익이 매개변수에 설정된 임계값 수준을 초과했습니다.
이 경우 설정에 따라 중지 순서를 수정하도록 제안합니다. 이를 위해 가상 메소드 CheckTrailingStopShort를 재정의하고 해당 기능으로 채우십시오.
클래스 설명:
class CSampleTrailing : public CExpertTrailing { protected: int m_profit; // threshold level of profit int m_stop_level; // lossless level public: CSampleTrailing(); //--- methods of setting adjustable parameters void Profit(int value) { m_profit=value; } void StopLevel(int value) { m_stop_level=value; } //--- method of validation of adjustable parameters virtual bool ValidationSettings(); //--- methods of generation of position modification signals virtual bool CheckTrailingStopLong(CPositionInfo* position,double& sl,double& tp); virtual bool CheckTrailingStopShort(CPositionInfo* position,double& sl,double& tp); };
CheckTrailingStopLong 및 CheckTrailingStopShort 메소드 구현:
//+------------------------------------------------------------------+ //| Check for modification of stop orders of a long position. | //| INPUT: position - pointer to a position object, | //| sl - link for a new price of stop loss order, | //| tp - link for a new price of take profit order. | //| OUTPUT: true if condition is satisfied, false - if not. | //| REMARK: no. | //+------------------------------------------------------------------+ bool CSampleTrailing::CheckTrailingStopLong(CPositionInfo* position,double& sl,double& tp) { //--- check of pointer if(position==NULL) return(false); //--- check of parameter if(m_profit==0.0) return(false); //--- already in a lossless zone? double open=position.PriceOpen(); if(position.StopLoss()>=open) return(false); //--- check of profit sl=EMPTY_VALUE; tp=EMPTY_VALUE; if(m_symbol.Bid()-open>m_profit*m_adjusted_point) sl=m_symbol.NormalizePrice(open+m_stop_level*m_adjusted_point); //--- return(sl!=EMPTY_VALUE); } //+------------------------------------------------------------------+ //| Check for modification of stop orders of a short position. | //| INPUT: position - pointer to a position object, | //| sl - link to a new price of stop loss order, | //| tp - link to a new price of take profit order. | //| OUTPUT: true if condition is satisfied, false - if not. | //| REMARK: нет. | //+------------------------------------------------------------------+ bool CSampleTrailing::CheckTrailingStopShort(CPositionInfo* position,double& sl,double& tp) { //--- check of pointer if(position==NULL) return(false); //--- check of parameter if(m_profit==0.0) return(false); //--- already in a lossless zone? double open=position.PriceOpen(); if(position.StopLoss()<=open) return(false); //--- check of profit sl=EMPTY_VALUE; tp=EMPTY_VALUE; if(open-m_symbol.Ask()>m_profit*m_adjusted_point) sl=m_symbol.NormalizePrice(open-m_stop_level*m_adjusted_point); //--- return(sl!=EMPTY_VALUE); }
2.2. MQL5 Wizard를 위해 생성된 거래 신호 클래스에 대한 설명 작성
이제 두 번째 문제를 해결합니다. 열린 포지션을 추적하는 우리 모듈은 거래 전략 MQL5 Wizard 생성자가 "인식"해야 합니다.
첫 번째 필수 조건을 완료했습니다. MQL5 마법사가 "찾을" 위치에 파일을 배치했습니다. 하지만 이것만으로는 충분하지 않습니다. MQL5 마법사는 파일을 "찾아야" 할 뿐만 아니라 "인식"해야 합니다. 이렇게 하려면 MQL5 마법사의 원본 텍스트에 클래스 설명자를 추가해야 합니다.
이러한 규칙을 고려해봅시다.
1. 주석 블록은 다음 줄로 시작해야 합니다.
// wizard description start //+------------------------------------------------------------------+ //| Description of the class |
2. 다음 줄은 "//| Title=<Text> |" 형식의 텍스트 설명자(신호를 선택할 때 MQL5 마법사에서 볼 수 있음)입니다. 텍스트가 한 줄에 비해 너무 크면 그 뒤에 한 줄을 더 추가할 수 있습니다(그러나 그 이상은 아님). </p>
우리의 경우 다음을 얻습니다.
//| Title=Signal on the crossing of a price and the MA | //| entering on its back movement |
3. 그런 다음 "//| Type=<Type> |" 형식으로 지정된 클래스 유형의 줄이 나옵니다. <Type> 필드에는 신호 값이 있어야 합니다(신호 외에도 MQL5 마법사는 다른 유형의 클래스를 알고 있습니다).
쓰다:
//| Type=Trailing |
4. "//| Name=<Name> |" 형식의 다음 줄 신호의 짧은 이름입니다(전문가의 전역 변수 이름을 생성하기 위해 MQL5 마법사에서 사용됨).
우리는 다음을 얻습니다.
//| Name=BreakEven |
5. 클래스의 이름은 설명의 중요한 요소입니다. "//| Class=<ClassNameа> |" 형식의 줄에서 <ClassName> 매개변수는 클래스 이름과 일치해야 합니다.
//| Class=CSampleTrailing |
6. 이 줄은 작성하지 않았지만 반드시 있어야 합니다(언어 참조 섹션에 대한 링크임).
//| Page= |
7. 또한 모듈 설정의 매개변수에 대한 설명이 있습니다.
이것은 행의 집합입니다(행의 수는 매개변수의 수와 같습니다).
각 줄의 형식은 "//| Parameter=<NameOfMethod>,<TypeOfParameter>,<DefaultValue> |"입니다.
다음은 매개변수 세트입니다.
//| Parameter=Profit,int,20 | //| Parameter=StopLevel,int,0 |
8. 주석 블록은 다음 줄로 끝나야 합니다.
//+------------------------------------------------------------------+ // wizard description end
소스 코드에 디스크립터를 추가해 보겠습니다.
//+------------------------------------------------------------------+ //| SampleTrailing.mqh | //| Copyright 2010, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2010, MetaQuotes Software Corp." #property link "https://www.mql5.com" //+------------------------------------------------------------------+ //| include files | //+------------------------------------------------------------------+ #include <Expert\ExpertTrailing.mqh> // wizard description start //+------------------------------------------------------------------+ //| Description of the class | //| Title=Moving a position to a lossless level | //| Type=Trailing | //| Name=BreakEven | //| Class=CSampleTrailing | //| Page= | //| Parameter=Profit,int,20 | //| Parameter=StopLevel,int,0 | //+------------------------------------------------------------------+ // wizard description end //+------------------------------------------------------------------+ //| Class CSampleTrailing. | //| Purpose: Class for trailing of open positions | //| by moving Stop order to a lossless level. | //| Is derived from the CExpertTrailing class. | //+------------------------------------------------------------------+ class CSampleTrailing : public CExpertTrailing { protected: int m_profit; // threshold level of profit int m_stop_level; // lossless level public: CSampleTrailing(); //--- method of setting adjustable parameters void Profit(int value) { m_profit=value; } void StopLevel(int value) { m_stop_level=value; } //--- method of validation of adjustable settings virtual bool ValidationSettings(); //--- methods of generation of position modification signals virtual bool CheckTrailingStopLong(CPositionInfo* position,double& sl,double& tp); virtual bool CheckTrailingStopShort(CPositionInfo* position,double& sl,double& tp); }; //+------------------------------------------------------------------+ //| Constructor CSampleTrailing. | //| INPUT: no. | //| OUTPUT: no. | //| REMARK: no. | //+------------------------------------------------------------------+ void CSampleTrailing::CSampleTrailing() { //--- setting default values m_profit =20; m_stop_level=0; } //+------------------------------------------------------------------+ //| Check of adjustable parameters. | //| INPUT: no. | //| OUTPUT: true if the parameters are correct, false if not. | //| REMARK: no. | //+------------------------------------------------------------------+ bool CSampleTrailing::ValidationSettings() { //--- what if the Init has not been called? if(m_symbol==NULL) return(false); //--- check of parameters if((m_profit-m_stop_level)*m_adjusted_point<=m_symbol.StopsLevel()*m_symbol.Point() && m_profit!=0.0) { printf(__FUNCTION__+": threshold level of profit must be greater than the level of setting stop orders"); return(false); } //--- ok return(true); } //+------------------------------------------------------------------+ //| Check for modification of stop orders of a long position. | //| INPUT: position - pointer to a position object, | //| sl - link for a new price of stop loss order, | //| tp - link for a new price of take profit order. | //| OUTPUT: true if condition is satisfied, false if not. | //| REMARK: no. | //+------------------------------------------------------------------+ bool CSampleTrailing::CheckTrailingStopLong(CPositionInfo* position,double& sl,double& tp) { //--- check of pointer if(position==NULL) return(false); //--- check of parameters if(m_profit==0.0) return(false); //--- already in a lossless zone? double open=position.PriceOpen(); if(position.StopLoss()>=open) return(false); //--- check of profit sl=EMPTY_VALUE; tp=EMPTY_VALUE; if(m_symbol.Bid()-open>m_profit*m_adjusted_point) sl=m_symbol.NormalizePrice(open+m_stop_level*m_adjusted_point); //--- return(sl!=EMPTY_VALUE); } //+------------------------------------------------------------------+ //| Check for modification of stop orders of a short position. | //| INPUT: position - pointer to a position object, | //| sl - link for a new price of stop loss order, | //| tp - link for a new take profit order. | //| OUTPUT: true if condition is satisfied, false if not. | //| REMARK: no. | //+------------------------------------------------------------------+ bool CSampleTrailing::CheckTrailingStopShort(CPositionInfo* position,double& sl,double& tp) { //--- check of pointer if(position==NULL) return(false); //--- check of parameters if(m_profit==0.0) return(false); //--- already in a lossless zone? double open=position.PriceOpen(); if(position.StopLoss()<=open) return(false); //--- check of profit sl=EMPTY_VALUE; tp=EMPTY_VALUE; if(open-m_symbol.Ask()>m_profit*m_adjusted_point) sl=m_symbol.NormalizePrice(open-m_stop_level*m_adjusted_point); //--- return(sl!=EMPTY_VALUE); } //+------------------------------------------------------------------+
그게 전부입니다. 후행 모듈을 사용할 준비가 되었습니다.
거래 전략 MQL5 마법사 생성기가 우리 모듈을 사용할 수 있으려면 MetaEditor를 다시 시작해야 합니다(MQL5 마법사는 시작할 때만 Include\Expert 폴더를 검색합니다).
MetaEditor를 다시 시작한 후 생성된 열린 위치 관리 모듈을 MQL5 마법사에서 사용할 수 있습니다.
그림 5. MQL5 마법사에서 열린 포지션을 관리하는 생성된 모듈입니다.
이제 열린 포지션을 관리하기 위한 모듈의 매개변수 설명 섹션에 지정된 입력 매개변수를 사용할 수 있습니다.
그림 6. MQL5 마법사에서 생성된 열린 포지션 관리 모듈의 입력 매개변수입니다.
구현된 거래 전략의 입력 매개변수의 최상의 값은 MetaTrader 5 터미널의 Strategy Tester를 사용하여 찾을 수 있습니다.
결론
MQL5 마법사의 거래 전략 생성기는 거래 아이디어 테스트를 크게 단순화합니다. 생성된 전문가의 코드는 표준 라이브러리의 거래 전략 클래스를 기반으로 하며, 이는 거래 신호 클래스, 자금 및 위험 관리 클래스 및 포지션 지원 클래스의 특정 구현을 생성하는 데 사용됩니다.
이 글에서는 가격이 포지션 방향으로 갈 때 손절매 수준을 무손실 영역으로 이동하여 미결 포지션을 관리하는 자체 클래스의 거래 전략 생성기 MQL5 Wizard를 작성하고 연결하는 방법에 대해 설명합니다. 거래 시 손실을 줄이기 위해. 또한 MQL5 마법사에 대해 생성된 클래스 설명의 구조 및 형식에 대해서도 알려줍니다.
MetaQuotes 소프트웨어 사를 통해 러시아어가 번역됨.
원본 기고글: https://www.mql5.com/ru/articles/231