초보자의 질문 MQL5 MT5 MetaTrader 5 - 페이지 1318

 
Kira27 :

질문을 복제하겠습니다. 그렇지 않으면 그들이 눈치채지 못했을 수 있습니다.))) 이 모든 방법을 사용하려면 어느 클래스에서 클래스를 상속해야 하는지 알려주세요

자신의 클래스 내부에 객체를 생성 하지 않고 자체 클래스 내부의 거래 클래스?

상속은 클래스를 만드는 것을 의미합니다.

 

안녕하세요!
EA를 만드는 데 사용하고 싶은 mql5로 작성된 표시기가 있습니다.
Expert Advisor에서 생성할 때 필요한 버퍼를 찾을 수 없어 아예 존재하지 않는 것 같습니다.
나는 이것을 이렇게 한다:

  {
//--- indicator buffers mapping 
   SetIndexBuffer ( 2 ,BuyBuffer, INDICATOR_DATA );
   ResetLastError (); 

double    handle3 = 0 ; 
double    handle4 = 0 ;
double    UP = 0 ;
double    DW = 0 ;

for ( int i= 1 ; i< 11 ; i++)
   {
      UP = iCustom ( NULL , 0 , "StepMA_NRTR" ,Length,Kv,StepSize,Percentage,Switch,Shift, 2 ,i); 
      DW = iCustom ( NULL , 0 , "StepMA_NRTR" ,Length,Kv,StepSize,Percentage,Switch,Shift, 3 ,i); 
 
       if (handle3== 0 )   
       if (UP != EMPTY_VALUE )
      handle3= 1 ;

       if (handle4== 0 )   
       if (UP != EMPTY_VALUE )
      handle4= 1 ;
      
       if (handle3> 0 && handle4)
       break ;      
   }  
   
Comment ( DoubleToString (handle3, Digits ())+ "\n" + DoubleToString (handle3, Digits ()));
   return ( INIT_SUCCEEDED );
  }

iCustom 라인을 어떻게 변경하고 보완하더라도 로그에 계속 같은 내용이 기록됩니다.

2021.06.26 17:59:42.251 프로바 (EURUSD,M15) 1.00000

그리고 코멘트에서: 1.00000 그리고 다시 1.00000

이해를 도와주세요. 고문을 만드는 데 적합합니까, 아니면 마무리해야 합니까, 아니면 일반적으로 제가 뭔가 잘못하고 있습니까?


파일:
StepMA_NRTR.mq5  13 kb
 

MT5에서는 다르게 사용됩니다. 예제는 도움말을 참조하십시오.

아이커스텀

지정된 사용자 지정 표시기의 핸들을 반환합니다 .

https://www.mql5.com/ru/docs/indicators/icustom

Документация по MQL5: Технические индикаторы / iCustom
Документация по MQL5: Технические индикаторы / iCustom
  • www.mql5.com
iCustom - Технические индикаторы - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Aleksei Stepanenko :

MT5에서는 다르게 사용됩니다. 예제는 도움말을 참조하십시오.

아이커스텀

지정된 사용자 지정 표시기의 핸들을 반환합니다 .

https://www.mql5.com/ru/docs/indicators/icustom

나는 이미 이 문서를 읽었지만 어디에.... , 또는 버퍼와 캔들 번호를 삽입하는 방법을 잘 이해하지 못했습니다.

저는 이제 막 프로그램을 시작하고 있으며 저를 관대하게 대해 주시기 바랍니다.

나는 이것이 추가 기능이 필요하다고 의심하기 시작했습니다.

 int copy= CopyBuffer (MA_handle, 0 , 0 ,rates_total,Label1Buffer); 

무엇을 .... 어디서 .... 그리고 어떻게 .... 설명해주세요.

 
Sprut 185 :

안녕하세요!
EA를 만드는 데 사용하고 싶은 mql5로 작성된 표시기가 있습니다.
Expert Advisor에서 생성할 때 필요한 버퍼를 찾을 수 없어 아예 존재하지 않는 것 같습니다.
나는 이것을 이렇게 한다:

iCustom 라인을 어떻게 변경하고 보완하더라도 로그에 계속 같은 내용이 기록됩니다.

2021.06.26 17:59:42.251 프로바 (EURUSD,M15) 1.00000

그리고 코멘트에서: 1.00000 그리고 다시 1.00000

이해를 도와주세요. 고문을 만드는 데 적합합니까, 아니면 마무리해야 합니까, 아니면 일반적으로 제가 뭔가 잘못하고 있습니까?


코드:

 //+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   double up_buffer[],dn_buffer[],buy_buffer[],sell_buffer[];
   ArraySetAsSeries (up_buffer, true );
   ArraySetAsSeries (dn_buffer, true );
   ArraySetAsSeries (buy_buffer, true );
   ArraySetAsSeries (sell_buffer, true );
   int start_pos= 0 ,count= 3 ;
   if (!iGetArray(handle_iCustom, 0 ,start_pos,count,up_buffer) ||
      !iGetArray(handle_iCustom, 1 ,start_pos,count,dn_buffer) ||
      !iGetArray(handle_iCustom, 2 ,start_pos,count,buy_buffer) ||
      !iGetArray(handle_iCustom, 3 ,start_pos,count,sell_buffer))
       return ;
//---
   string text= " | UpBuffer | DnBuffer | BuyBuffer | SellBuffer" + "\n" ;
   for ( int i= 0 ; i<count; i++)
     {
      text=text+ "#" + IntegerToString (i)+ " | " + DoubleToString ((up_buffer[i]== EMPTY_VALUE ? 0.0 :up_buffer[i]), Digits ())
           + " | " + DoubleToString ((dn_buffer[i]== EMPTY_VALUE ? 0.0 :dn_buffer[i]), Digits ())
           + " | " + DoubleToString ((buy_buffer[i]== EMPTY_VALUE ? 0.0 :buy_buffer[i]), Digits ())
           + " | " + DoubleToString ((sell_buffer[i]== EMPTY_VALUE ? 0.0 :sell_buffer[i]), Digits ())+ "\n" ;
     }
   Comment (text);
  }

결과:


파일:
 
Sprut 185 :

안녕하세요!
EA를 만드는 데 사용하고 싶은 mql5로 작성된 표시기가 있습니다.

여기 블라인드가 있습니다. 작동하는 것 같습니다! (노란색 버퍼가 있는 곳)

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\

손절매도 필요하다는 것이 밝혀졌습니다. (왜 즉시 닫혔는지 이해할 수 없음) 손절매 를 추가했습니다.

BTCUSDM1 3

BTCUSDM1 4

 //+------------------------------------------------------------------+
//|                                                    Sprut 185.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link        " https://www.mql5.com "
#property version    "1.00"
#define   UNO_MAGIC 2344701
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
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
//---
enum PRICE_MODE
  {
   HighLow,     // High/Low
   CloseClose   // Close/Close
  };
//---
input group       "---- : StepMA_NRTR:  ----"
input int         Length        = 10 ;       // Volty Length
input double      Kv            = 1.0 ;     // Sensivity Factor
input int         StepSize      = 0 ;       // Constant Step Size (if need)
input double      Percentage    = 0 ;       // Percentage of Up/Down Moving
input PRICE_MODE Switch        = HighLow; // High/Low Mode Switch (more sensitive)
input int         Shift         = 0 ;       // Shift
input group       "---- : Parameters:  ----"
input uint        InpStopLoss   = 90 ;       // : Stop Loss
input uint        InpTakeProfit = 36 ;       // : Take Profit
input double      InpLots       = 0.1 ;     // : Lots
input bool        InpClOp       = true ;     // : Close opposite
//---
int       price_uno;           //
double    m_stop_loss   = 0.0 ; // Stop Loss
double    m_take_profit = 0.0 ; // Take Profit
datetime m_last_open   = 0 ;   // "0" -> D'1970.01.01 00:00';
int StepMA_NRTR_Handle;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ( void )
  {
//--- initialize common information
   if (!m_symbol.Name( Symbol ()))             // sets symbol name
       return ( false );
   RefreshRates();
   m_trade.SetExpertMagicNumber(UNO_MAGIC); // magic
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol( Symbol ());
//--- 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_stop_loss   = InpStopLoss*m_adjusted_point;
   m_take_profit = InpTakeProfit*m_adjusted_point;
//--- set default deviation for trading in adjusted points
   m_trade.SetDeviationInPoints( 3 *digits_adjust);
//---- получение хендла индикатора StepMA_NRTR
   StepMA_NRTR_Handle= iCustom ( NULL , 0 , "StepMA_NRTR" ,Length,Kv,StepSize,Percentage,Switch,Shift);
   if (StepMA_NRTR_Handle== INVALID_HANDLE )
       Print ( " Не удалось получить хендл индикатора StepMA_NRTR" );
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ( void )
  {
//--- refresh rates
   if (!m_symbol.RefreshRates())
       return ;
//---
   if (!SearchTradingSignalsOpen())
     {
       return ;
     }
  }
//+------------------------------------------------------------------+
//| Check for open position conditions                               |
//+------------------------------------------------------------------+
bool CheckForOpenBuy( void )
  {
   bool res= false ;
//--- check for long position (BUY) possibility
   double price=m_symbol.Ask();
   double tp   =m_symbol.Bid()+m_take_profit;
   double sl   =m_symbol.Bid()-m_stop_loss;
//--- check for free money
   if (m_account.FreeMarginCheck( Symbol (), ORDER_TYPE_BUY ,InpLots,price)< 0.0 )
       printf ( "We have no money. Free Margin = %f" ,m_account.FreeMargin());
   else
     {
       //--- open position
       if (m_trade.PositionOpen( Symbol (), ORDER_TYPE_BUY ,InpLots,price,sl,tp))
         printf ( "Position by %s to be opened" , Symbol ());
       else
        {
         printf ( "Error opening BUY position by %s : '%s'" , Symbol (),m_trade.ResultComment());
         printf ( "Open parameters : price=%f,SL=%f,TP=%f" ,price,sl,tp);
        }
     }
//--- in any case we must exit from expert
   res= true ;
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for open position conditions                               |
//+------------------------------------------------------------------+
bool CheckForOpenSell( void )
  {
   bool res= false ;
//--- check for short position (SELL) possibility
   double price=m_symbol.Bid();
   double tp   =m_symbol.Ask()-m_take_profit;
   double sl   =m_symbol.Ask()+m_stop_loss;
//--- check for free money
   if (m_account.FreeMarginCheck( Symbol (), ORDER_TYPE_SELL ,InpLots,price)< 0.0 )
       printf ( "We have no money. Free Margin = %f" ,m_account.FreeMargin());
   else
     {
       //--- open position
       if (m_trade.PositionOpen( Symbol (), ORDER_TYPE_SELL ,InpLots,price,sl,tp))
         printf ( "Position by %s to be opened" , Symbol ());
       else
        {
         printf ( "Error opening SELL position by %s : '%s'" , Symbol (),m_trade.ResultComment());
         printf ( "Open parameters : price=%f,SL=%f,TP=%f" ,price,sl,tp);
        }
     }
//--- in any case we must exit from expert
   res= true ;
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for close position conditions                              |
//+------------------------------------------------------------------+
void CheckForCloseBuy( void )
  {
//--- close position
   ClosePositions( POSITION_TYPE_BUY );
//---
  }
//+------------------------------------------------------------------+
//| Check for close position conditions                              |
//+------------------------------------------------------------------+
void CheckForCloseSell( void )
  {
//--- close position
   ClosePositions( POSITION_TYPE_SELL );
//---
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if (!m_symbol.RefreshRates())
     {
       return ( false );
     }
//--- protection against the return value of "zero"
   if (m_symbol.Ask()== 0 || m_symbol.Bid()== 0 )
     {
       return ( false );
     }
//---
   return ( true );
  }
//+------------------------------------------------------------------+
//| Check Freeze and Stops levels                                    |
//+------------------------------------------------------------------+
void FreezeStopsLevels( double &freeze, double &stops)
  {
//--- check Freeze and Stops levels
   double coeff=( double ) 1 ;
   if (!RefreshRates() || !m_symbol.Refresh())
       return ;
//--- FreezeLevel -> for pending order and modification
   double freeze_level=m_symbol.FreezeLevel()*m_symbol. Point ();
   if (freeze_level== 0.0 )
       if ( 1 > 0 )
         freeze_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;
//--- StopsLevel -> for TakeProfit and StopLoss
   double stop_level=m_symbol.StopsLevel()*m_symbol. Point ();
   if (stop_level== 0.0 )
       if ( 1 > 0 )
         stop_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;
//---
   freeze=freeze_level;
   stops=stop_level;
//---
   return ;
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions( const ENUM_POSITION_TYPE pos_type)
  {
   double freeze= 0.0 ,stops= 0.0 ;
   FreezeStopsLevels(freeze,stops);
   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 ()==m_symbol.Name() && m_position.Magic()==UNO_MAGIC)
             if (m_position.PositionType()==pos_type)
              {
               if (m_position.PositionType()== POSITION_TYPE_BUY )
                 {
                   bool take_profit_level=((m_position.TakeProfit()!= 0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=freeze) || m_position.TakeProfit()== 0.0 );
                   bool stop_loss_level=((m_position.StopLoss()!= 0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=freeze) || m_position.StopLoss()== 0.0 );
                   if (take_profit_level && stop_loss_level)
                     if (!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                         Print ( __FILE__ , " " , __FUNCTION__ , ", ERROR: " , "BUY PositionClose " ,m_position.Ticket(), ", " ,m_trade.ResultRetcodeDescription());
                 }
               if (m_position.PositionType()== POSITION_TYPE_SELL )
                 {
                   bool take_profit_level=((m_position.TakeProfit()!= 0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=freeze) || m_position.TakeProfit()== 0.0 );
                   bool stop_loss_level=((m_position.StopLoss()!= 0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=freeze) || m_position.StopLoss()== 0.0 );
                   if (take_profit_level && stop_loss_level)
                     if (!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                         Print ( __FILE__ , " " , __FUNCTION__ , ", ERROR: " , "SELL PositionClose " ,m_position.Ticket(), ", " ,m_trade.ResultRetcodeDescription());
                 }
               PlaySound ( "ok.wav" );
              }
  }
//+------------------------------------------------------------------+
//| Filling the indicator buffers from the indicator                 |
//+------------------------------------------------------------------+
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))
     {
       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)
     {
       return ( false );
     }
   return (result);
  }
//+------------------------------------------------------------------+
//| Search trading signals                                           |
//+------------------------------------------------------------------+
bool SearchTradingSignalsOpen( void )
  {
//--- we work only at the time of the birth of new bar
   datetime time_0= iTime ( Symbol (), Period (), 0 );
   if (time_0==m_last_open)
       return ( true );
   m_last_open=time_0;
//--- we work only at the time of the birth of new bar
   double StepMA_NRTR[],StepMA_NRTRS[];
   bool StNRUp,StNRDn;
   ArraySetAsSeries (StepMA_NRTR, true );
   ArraySetAsSeries (StepMA_NRTRS, true );
   int start_pos= 0 ,count= 3 ;
   if (!iGetArray(StepMA_NRTR_Handle, 0 ,start_pos,count,StepMA_NRTR)||
      !iGetArray(StepMA_NRTR_Handle, 1 ,start_pos,count,StepMA_NRTRS))
     {
       return ( false );
     }
//+------------------------------------------------------------------+
   StNRUp=StepMA_NRTR[ 0 ]<StepMA_NRTRS[ 0 ];
//---
   StNRDn=StepMA_NRTR[ 0 ]>StepMA_NRTRS[ 0 ];
//+------------------------------------------------------------------+
//--- BUY Signal
   if (StNRUp)
     {
       if (InpClOp)
         CheckForCloseSell();
       Sleep ( 1000 );
       if (price_uno< 0 )
         CheckForOpenBuy();
      price_uno=+ 1 ;
       return ( true );
     }
//--- SELL Signal
   if (StNRDn)
     {
       if (InpClOp)
         CheckForCloseBuy();
       Sleep ( 1000 );
       if (price_uno> 0 )
         CheckForOpenSell();
      price_uno=- 1 ;
       return ( true );
     }
//---
   return ( true );
  }
//+------------------------------------------------------------------+


 
Sprut 185 :

나는 이것이 추가 기능이 필요하다고 의심하기 시작했습니다.

예 모든 것이 맞습니다. OnInit에서 표시기를 연결하고 거기에 매개변수를 설정하고 핸들을 가져옵니다. 그리고 더 나아가 CopyBuffer를 사용하십시오.


https://www.mql5.com/ru/docs/series/copybuffer

Документация по MQL5: Доступ к таймсериям и индикаторам / CopyBuffer
Документация по MQL5: Доступ к таймсериям и индикаторам / CopyBuffer
  • www.mql5.com
CopyBuffer - Доступ к таймсериям и индикаторам - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
SanAlex :

여기 블라인드가 있습니다. 작동하는 것 같습니다! (노란색 버퍼가 있는 곳)

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\

당신도 손절매가 필요하다는 것이 밝혀졌습니다 - (왜 즉시 닫혔는지 이해할 수 없음) 손절매 를 추가했습니다



매우 감사합니다 !!!

당신은 모든 것을 잘 블라인드했지만 고문의 완전히 다른 알고리즘에 관심이 있습니다. 다음 사용자 지정 옵션과 함께 간단한 마틴게일(그리드)을 사용하고 싶습니다.

 input group "======== МАРТИН ========"; 
input int      MMType        = 1 ;        // 1 - вкл. , 2 - выкл.
input double   Multiplikator = 1.667 ;    // множитель следующего лота
input double   Step          = 150.0 ;    // Расстояние между ордерами
input group "==== МАНИ МЕНЕДЖМЕНТ ====; 
input bool     LotConst      = true ;     // фиксированный - true , или от  баланса - false
input group "-: фиксированный лот :--"; 
input double   Lot           = 0.01 ;     // первый фиксированный лот, если МАРТИН включен
input group "---: лот от баланса :---"; 
input double   RiskPercent   = 30.0 ;     // первый лот в процентах от баланса, если МАРТИН включен
input group "== ПРИБЫЛЬ В ПУНКТАХ ==="; 
input double   TakeProfit    = 56.0 ;     // параметры тейкпрофита в пунктах
input group "========= Шаг =========="; 
input double   Step          = 150.0 ;    // шаг в пунктах между ордерами
input group "===== ОГРАНИЧИТЕЛЬ =====";  
input int      MaxTrades     = 15 ;       // Максимальное количество ордеров одного направления
input group "=== ПРОСКАЛЬЗОВАНИЕ ====";  
input double   Slippage      = 5.0 ;      // Допустимое проскальзывание на новостях в пунктах
input group "== МАГИЧЕСКИЙ  НОМЕР ===";  
input int      Magic         = 1111111 ; // Идентификатор ордера (Магик №)

, 그러나 내가 위에 넣은 표시기를 추가하십시오. 그리고 그것을 트리거로 사용하십시오(거짓 - 우리는 SHORT에서만 작동하고 참 - 우리는 LONG에서만 작동합니다).

나는 이 지표가 MovingAverages처럼 작동하기 때문에 선택했지만 메뉴의 이익 설정을 사용하여 추세 전용 EA 트리거로 사용할 수 있는 몇 가지 스무딩 필터와 가격 반전 포인트가 있습니다.

그리고 테이크가 종료되자마자 추세가 끝나고 전환될 때까지 같은 방향(추세와 함께)으로 다음 주문을 엽니다. 그럼에도 불구하고 추세를 따르지 않는 주문이 나타나면(현재 추세가 한 상태에서 다른 상태로 변경되면 메뉴의 설정과 함께 Martin을 사용하십시오.

그러한 고문을 작성하는 데 도움이 되고자 하는 소망이 있다면 매우 감사할 것입니다.

이제 주제:
내가 알기로는 칠면조 자체에 대한 내 코드에는 표시기 버퍼 가 아니라 버퍼 배열이 있으며 이를 어드바이저의 표시기 버퍼로 가져왔습니다.
제가 제대로 이해했다면 써주세요.


 
Sprut 185 :

이제 주제:

내가 알기로는 칠면조 자체에 대한 내 코드에는 표시기 버퍼 가 아니라 버퍼 배열이 있으며 이를 어드바이저의 표시기 버퍼로 가져왔습니다.
제가 제대로 이해했다면 써주세요.


독학해서 설명할 수 없습니다. 필요한 기능만 선택했습니다. 여기 저기 저쪽으로 압니다.

기본적으로 Vladimir Karputov 의 코드에서 모든 기능을 복사합니다. 정말 감사합니다!!! - 질문이 있으면 그가 당신에게 말할 것입니다.

Vladimir Karputov
Vladimir Karputov
  • 2021.06.25
  • www.mql5.com
Профиль трейдера
 
SanAlex :

내가 알기로는 필터링 할 지표가 필요합니다!?

이 필터를 통해 전문가를 통과해야 합니다.

당신은 나를 잘 이해하지 못했습니다!
사유: