MQL4 및 MQL5에 대한 초보자 질문, 알고리즘 및 코드에 대한 도움말 및 토론 - 페이지 1889

 
매우 감사합니다! 나는 공부할 것이다!
 
예를 들어 MT5 터미널에서 거래 수준 을 STYLE_DOT가 아니라 STYLE_SOLID 로 만들 수 있습니까 ???
 

코드 도와주세요

만든 지표

테스터에서 잘 작동합니다

그래프에 넣어 잘못된 표시

나는 이유를 알 수 없다

 //+------------------------------------------------------------------+
//|                                                        Oscil.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"
#property indicator_separate_window
#property   indicator_buffers 5
#property indicator_plots    5

#property   indicator_color1    clrNONE
#property   indicator_color2    clrRoyalBlue
#property   indicator_color3    clrPink
#property   indicator_color4    clrAqua
#property   indicator_color5    clrYellow

#property   indicator_width1 1
#property   indicator_width2 5
#property   indicator_width3 5
#property   indicator_width4 5
#property   indicator_width5 5

double MainLine[];
double UpLine[];
double DnLine[];
double muls[];
double x,y,z;
double price;
double mulSum= 0 ;
double Pi   = 3.1415926535 ;
bool LastUp = false ;
bool GoUp   = false ;
input bool otl    = false ;
/***********Range***************/
int     Length             = 3 ;
int     MajorRangeStrength = 4 ;


double MajorRangeBuy[];
double MajorRangeSell[];


double RangePrice  = 0.0 ,
       SweepB      = 0.0 ;
int     Switch2     = 0 ,
         SwitchB     = 0 ;
double Price2BuyA  = 0.0 ;
int     Price2BuyB  = 1.0 ;
double Price2SellA = 0.0 ;
int     Price2SellB = 0.0 ;
bool    BuySwitchB  = false ,
       SellSwitchB = false ;
       
int hendlMA_1;
double MA_1[];

int hendlMA_2;
double MA_2[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit ()
  {
//--- indicator buffers mapping
   SetIndexBuffer ( 0 ,MainLine, INDICATOR_DATA );
   PlotIndexSetDouble ( 0 , PLOT_EMPTY_VALUE , 0 );
   PlotIndexSetInteger ( 0 , PLOT_DRAW_TYPE , DRAW_HISTOGRAM ); 
   ArraySetAsSeries (MainLine, true );
   
   SetIndexBuffer ( 1 ,UpLine, INDICATOR_DATA );
   PlotIndexSetDouble ( 1 , PLOT_EMPTY_VALUE , 0 );
   PlotIndexSetInteger ( 1 , PLOT_DRAW_TYPE , DRAW_HISTOGRAM ); 
   ArraySetAsSeries (UpLine, true );
   
   SetIndexBuffer ( 2 ,DnLine, INDICATOR_DATA );
   PlotIndexSetDouble ( 2 , PLOT_EMPTY_VALUE , 0 );
   PlotIndexSetInteger ( 2 , PLOT_DRAW_TYPE , DRAW_HISTOGRAM ); 
   ArraySetAsSeries (DnLine, true );
   
   SetIndexBuffer ( 3 ,MajorRangeBuy, INDICATOR_DATA );
   PlotIndexSetDouble ( 3 , PLOT_EMPTY_VALUE , 0 );
   PlotIndexSetInteger ( 3 , PLOT_DRAW_TYPE , DRAW_HISTOGRAM ); 
   ArraySetAsSeries (MajorRangeBuy, true );
   
   SetIndexBuffer ( 4 ,MajorRangeSell, INDICATOR_DATA );
   PlotIndexSetDouble ( 4 , PLOT_EMPTY_VALUE , 0 );
   PlotIndexSetInteger ( 4 , PLOT_DRAW_TYPE , DRAW_HISTOGRAM ); 
   ArraySetAsSeries (MajorRangeSell, true );
   
   hendlMA_1= iMA ( Symbol (), 0 , 1 , 0 , MODE_LWMA , PRICE_CLOSE );
   ArraySetAsSeries (MA_1, true );
   
   hendlMA_2= iMA ( Symbol (), 0 , 1 , 0 , MODE_SMMA , PRICE_CLOSE );
   ArraySetAsSeries (MA_2, true );
   
   ArrayResize (muls, 99 );
   
   mulSum = 0 ;
   
   for ( int i0 = 0 ; i0 < 98 ; i0++) { //повторяем в цикле 98 раз
       if (i0 <= 18 ) y = 1.0 * i0 / 18 ; //если это первые 18 повторений
       else y = (i0 - 18 ) * 7.0 / 79.0 + 1.0 ; //иначе
      
      x = MathCos (Pi * y);
      z = 1.0 / ( 3.0 * Pi * y + 1.0 );
       if (y <= 0.5 ) z = 1 ;
      
      muls[i0] = z * x;
      mulSum += muls[i0];
   }
   if (otl) Print ( " Распределение создано muls[20]=" ,muls[ 20 ]);
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate ( const int rates_total,
                 const int prev_calculated,
                 const datetime &time[],
                 const double &open[],
                 const double &high[],
                 const double &low[],
                 const double &close[],
                 const long &tick_volume[],
                 const long &volume[],
                 const int &spread[])
  {
//---
   if ( PeriodSeconds () < 60 * 60 || PeriodSeconds () > 10080 * 60 ) return ( 0 );
   int depth= 0 ;

   int l_ind_counted_8 = prev_calculated; //Возвращает количество баров, не измененных после последнего вызова индикатора.
   
   int bars= Bars ( Symbol (), PERIOD_CURRENT );
   if (l_ind_counted_8 < 0 ) return ( 0 );
   if (l_ind_counted_8 == 0 )
      {
         depth = bars - 98 ;
         for ( int a= 0 ;a<bars;a++)
            {
               MainLine[a] = 0 ;
               UpLine[a] = 0 ;
               DnLine[a] = 0 ;
               MajorRangeBuy[a]= 0 ;
               MajorRangeSell[a]= 0 ;
            }
      }
   if (l_ind_counted_8 > 0 )  depth = bars - l_ind_counted_8;
   if (otl) Print ( " количество баров, не измененных после последнего вызова индикатора= " ,l_ind_counted_8, "  Количество баров на текущем графике Bars=" ,bars, "  depth= " ,depth);
   if (l_ind_counted_8 < 1 ) {
       for ( int i2 = 1 ; i2 < 100 ; i2++) {
         MainLine[bars - i2] = 0 ;
         UpLine[bars - i2] = 0 ;
         DnLine[bars - i2] = 0 ;
      }
   }
   
   for ( int i1 = depth; i1 >= 0 ; i1--) 
   {
      price = 0 ;
          
           CopyBuffer (hendlMA_1, 0 , 0 ,bars,MA_1);
          
       for ( int i2 = 0 ; i2 <= 98 ; i2++) 
         {
             if (i2 + i1>=bars) break ;
            price += muls[i2] * MA_1[i2 + i1];
         }
          
       if (mulSum > 0.0 ) MainLine[i1] = price / mulSum;

     GoUp=MainLine[i1 + 1 ] > MainLine[i1] ;
     
       if (GoUp) 
      {
         if (!LastUp) DnLine[i1+ 1 ] = MainLine[i1+ 1 ];
         DnLine[i1] = MainLine[i1];
         UpLine[i1] = 0 ;
      }
         else
      {
         if (LastUp) UpLine[i1+ 1 ] = MainLine[i1+ 1 ];
         UpLine[i1] = MainLine[i1];
         DnLine[i1] = 0 ;
      }
      LastUp=GoUp; 

   } //  for (int i1

 //  return (0);

/***************** Range **********************/

   int counted_bars=prev_calculated;
   if (otl) Print ( " Range counted_bars = " , counted_bars);
   if (counted_bars< 0 ) return (- 1 );
   int position=bars-counted_bars;
   if (position< 0 ) position= 0 ;
   if (position== 0 ) position= 1 ;
   int rnglength = 250 ;
   double range = 0.0 , srange = 0.0 ;
   if (otl) Print ( " position=" ,position);
   
   for ( int pos = position; pos >= 0 ; pos--)
   { /***************** MAIN Range **********************/
      srange = 0.0 ;
       int j = 0 ;
       for ( int i= 0 ;i<rnglength;i++)
      {
         j++;
         int posr = pos + i;
         if (posr >= bars) break ; 
         srange = srange + (High(posr) - Low(posr));
      }
      range = srange / j * Length;
       int BarNumber = bars-pos; //??????????
       if (BarNumber < 0 )  BarNumber = 0 ;
          
           CopyBuffer (hendlMA_2, 0 , 0 ,bars,MA_2);
           //Print(bars," - ",pos);
       if (pos<bars)RangePrice = MA_2[pos];   //Moving Average MODE_SMMA
       else RangePrice = MA_2[pos- 1 ];

       if (BarNumber == 1 )
      {
         SweepB  = range *  MajorRangeStrength;
         Price2BuyA = RangePrice;
         Price2SellA = RangePrice;
      }     

       if (BarNumber > 1 )
      {

         if (Switch2  >  - 1 ) //проверка цикла на покупку
         {
             if (RangePrice < Price2BuyA) //если средняя цена ниже
            {
if (BuySwitchB ) MajorRangeBuy [pos +BarNumber - Price2BuyB] = 0 ;                                                                 //OUT
                           Price2BuyA = RangePrice;
               Price2BuyB = BarNumber;
               BuySwitchB = true ;
            } 
             else if (RangePrice > Price2BuyA)
            {
                            SwitchB = BarNumber - Price2BuyB;
MajorRangeBuy [pos +SwitchB] = MainLine[pos + SwitchB]* 1.0005 ;                                                                                                                           //OUT
                BuySwitchB = true ;

                               if (RangePrice - MA_2[pos + SwitchB] >= SweepB && SwitchB >= 1 )
                              {
                     Switch2 =  - 1 ;
                     Price2SellA = RangePrice;
                     Price2SellB = BarNumber;
                     SellSwitchB = false ;
                     BuySwitchB = false ;
               }
            }
         }
         if (Switch2  < 1 ) //проверка цикла на продажу
         {
             if (RangePrice  > Price2SellA )
            {
if (pos +BarNumber - Price2SellB<bars&&SellSwitchB ) MajorRangeSell [pos +BarNumber - Price2SellB] = 0 ;                                                         //OUT
                           Price2SellA = RangePrice;
               Price2SellB = BarNumber;
               SellSwitchB = true ;
                    }
                       else if (RangePrice < Price2SellA)
                    {
               SwitchB = BarNumber - Price2SellB ;

         if (pos+ SwitchB<bars)MajorRangeSell[pos + SwitchB] =MainLine[pos + SwitchB]* 1.0005 ;                                                                                                                             //OUT
                SellSwitchB = true ;             
        
                               if (pos + SwitchB<bars&&MA_2[pos + SwitchB] - RangePrice >= SweepB && SwitchB >= 1 )
                              {
                                     Switch2 = 1 ;
                     Price2BuyA = RangePrice;
                     Price2BuyB = BarNumber;
                     SellSwitchB = false ;
                     BuySwitchB = false ;
                                  }
            }
         }
      }

   //   MajorRangeSell[pos] = 0;
     //  MajorRangeBuy[pos]  = 0;  
    }
//--- return value of prev_calculated for next call
   return (rates_total);
  }
//+------------------------------------------------------------------+
//========================================================================================
double High( int index)
{   
   if (index < 0 ) return (- 1 );
   double Arr[];
   ENUM_TIMEFRAMES timeframe= PERIOD_CURRENT ;
   if ( CopyHigh ( Symbol (),timeframe, index, 1 , Arr)> 0 ) 
         return (Arr[ 0 ]);
   else return (- 1 );
}
//========================================================================================
double Low( int index)
{   
   if (index < 0 ) return (- 1 );
   double Arr[];
   ENUM_TIMEFRAMES timeframe= PERIOD_CURRENT ;
   if ( CopyLow ( Symbol (),timeframe, index, 1 , Arr)> 0 ) 
         return (Arr[ 0 ]);
   else return (- 1 );
}
 
Mikhail Rudyk # :

코드 도와주세요

만든 지표

테스터에서 잘 작동합니다

그래프에 넣어 잘못된 표시

나는 이유를 알 수 없다

원인을 찾기 위해 디버거를 사용해 보셨습니까?

 

코드 작성을 도와주세요

표시기의 조건:

고점(2)이 이전 고점(1)보다 크고 저점(2)이 이전 저점(1)보다 크면 반대 상황(고점 3 및 4)과 (저점 3 및 4)가 예상됩니다. 최대 표시(2와 3) 사이의 최대 표시에서 최대 표시를 파란색 점 형태로 설정합니다.

고점(4)이 이전 고점(3)보다 낮고 저점(4)이 이전 저점(3)보다 낮으면 반대 상황(고점 5 및 6)과 (저점 5 및 6)이 예상됩니다. 최대값(4와 5) 사이의 최소 표시에서 빨간색 점 형태로 최소 표시를 설정합니다.

죄송합니다 사진이 삽입되지 않았습니다

코드 자체:


 for ( int i=Start;i> 0 && ! IsStopped ();i--)

   {

     int a1= 0 ,b1= 0 ,a2= 0 ,b2= 0 , Stop1a= 0 , Stop1b= 0 ;

//-----------------------------------    

     if (high[i- 1 ]<high[i] && low[i- 1 ]<low[i] && Stop1a== 0 )   // условие для установки максимума и открытый доступ

     {

      Stop1a= 1 ;                                             // закрываем доступ (чтобы небыло ненужных повторений)

       for (i;i> 0 ;i--)                                       // цикл для счетчика

        {

         a1++;                                             // счетчик для функции iHighest

         if (high[i- 1 ]>high[i] && low[i- 1 ]>low[i])           // противоложное условие предыдущему

          {

           Stop1a= 0 ;                                       // открываем доступ

           b1= iHighest ( NULL , 0 , MODE_HIGH ,a1,i);             // получаем индекс максимального значения

           Max1[b1]=high[b1];                               // заполняем индикаторный массив для максимумов

           break ;                                           // прерываем цикл

          }

        }

     } 



     if (high[i- 1 ]>high[i] && low[i- 1 ]>low[i] && Stop1b== 0 )   // условие для установки минимума и открытый доступ

     {

      Stop1b= 1 ;                                             // закрываем доступ (чтобы небыло ненужных повторений)

       for (i;i> 0 ;i--)                                       //  цикл для счетчика

        {

         a2++;                                             // счетчик для функции iLowest

         if (high[i- 1 ]<high[i] && low[i- 1 ]<low[i])           // противоложное условие предыдущему

          {

           Stop1b= 0 ;                                       // открываем доступ

           b2= iLowest ( NULL , 0 , MODE_LOW ,a2,i);               // получаем индекс минимального значения

           Min1[b2]=low[b2];                               // заполняем индикаторный массив для минимумов

           break ;                                           // прерываем цикл

          }

        }

     } 
 
친애하는 전문가 여러분! 코드가 있습니다.

int 핸들 = FileOpen("2022.02.01 12-00",FILE_ANSI|FILE_WRITE|FILE_COMMON,'-'); // 쓰기 위해 열림
FileWrite(핸들,"1","643","USDCAD","[11-1.30-0.70]"); //데이터 세트 쓰기
FileSeek(핸들, 0, SEEK_SET); // 포인터를 파일의 시작 부분으로 이동했습니다(이것은 중복되지만 여전히)
파일 닫기(핸들); //파일을 닫는다
핸들 = FileOpen("2022.02.01 12-00",FILE_ANSI|FILE_SHARE_READ|FILE_COMMON,'-');//읽기 위해 열림
Print(FileTell(Handle)," ",FileReadNumber(Handle)," ",FileReadNumber(Handle));
파일 닫기(핸들); //파일을 닫는다

로그 항목에는 현재 포인터 위치, 공백, 파일에서 읽은 첫 번째 값(1), 공백, 파일에서 읽은 두 번째 값(643)이 포함되어야 합니다. 대신 다음이 기록됩니다.

6 643.0 1.0

즉, 내가 이해할 수 없는 어떤 이유에서 파일 포인터는 파일의 시작 부분이 아니라 파일에서 6바이트 떨어진 두 번째 구분 기호("-")에 있고 후속 읽기는 오른쪽에서 왼쪽으로 발생합니다. FileSeek 함수 를 사용하여 파일의 시작 부분에 대한 포인터를 재정렬하려고 시도했지만 성공하지 못했습니다.
내 지능은 무슨 일이 일어나고 있는지 이해하기에 충분하지 않습니다. 어떤 게임인지 설명 부탁드립니다.
 
Sergey Gubar # :

코드 작성을 도와주세요

표시기의 조건:

고점(2)이 이전 고점(1)보다 크고 저점(2)이 이전 저점(1)보다 크면 반대 상황(고점 3 및 4)과 (저점 3 및 4)가 예상됩니다. 최대 표시(2와 3) 사이의 최대 표시에서 최대 표시를 파란색 점 형태로 설정합니다.

고점(4)이 이전 고점(3)보다 낮고 저점(4)이 이전 저점(3)보다 낮으면 반대 상황(고점 5 및 6)과 (저점 5 및 6)이 예상됩니다. 최대값(4와 5) 사이의 최소 표시에서 빨간색 점 형태로 최소 표시를 설정합니다.

죄송합니다 사진이 삽입되지 않았습니다

코드 자체:


미래를 보지마

[i + 1 ]
 

도와주세요!

내가 기대하는 것을 얻지 못한다. 로그 파일을 읽어야 합니다.

 #define GENERIC_READ             0x80000000
#define GENERIC_WRITE           0x40000000

#define WIN32_FILE_SHARE_READ   1
#define WIN32_FILE_SHARE_WRITE   2

#define CREATE_NEW               1
#define CREATE_ALWAYS           2
#define OPEN_ALWAYS             4
#define OPEN_EXISTING           3
#define TRUNCATE_EXISTING       5

#define SEEK_FILE_BEGIN         0
#define SEEK_FILE_CURRENT       1
#define SEEK_FILE_END           2

#define INVALID_HANDLE_VALUE    - 1
#define UNICODE
#define FILE_ATTRIBUTE_NORMAL 0x80

#import "kernel32.dll"
int CreateFileW( string Filename, uint AccessMode, int ShareMode, int PassAsZero, int CreationMode, int FlagsAndAttributes, int AlsoPassAsZero);
int ReadFile( int FileHandle, ushort & Buffer[], int BufferLength, int & BytesRead[], int PassAsZero);
int SetFilePointer( int FileHandle, int Distance, int PassAsZero, int FromPosition);
int GetFileSize( int FileHandle, int PassAsZero);
int CloseHandle( int FileHandle);
#import

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnStart ()
{
   string sDate = TimeToString ( TimeCurrent ()- 86400 , TIME_DATE );
   string FileName = TerminalInfoString ( TERMINAL_DATA_PATH )+ "\\MQL4\\Logs\\" +sDate+ ".log" ;
   int FileHandle = CreateFileW(FileName, GENERIC_READ, WIN32_FILE_SHARE_READ, 0 , OPEN_EXISTING, 0 , 0 );
   SetFilePointer(FileHandle, 0 , 0 , SEEK_FILE_BEGIN);
   int szFileA = GetFileSize(FileHandle, 0 );
   ushort ReadBufferA[];
     ArrayResize (ReadBufferA, szFileA);
     int BytesReadA[ 1 ] = { 0 };
    ReadFile(FileHandle, ReadBufferA, szFileA, BytesReadA, 0 );

   string Res= ShortArrayToString (ReadBufferA, 0 , BytesReadA[ 0 ]);

   string msg= "FileHandle: " +FileHandle+ "    \n"
             "FileSize: " +szFileA+ "    \n"
             + "Res: " +Res;
   Print (msg); // 2022.02.03 04:56:43.670	test GBPJPY,M30: FileHandle: -1    FileSize: -1    Res: 

 CloseHandle(FileHandle);
}
//+------------------------------------------------------------------+
 

좋은 오후에요 여러분. 피보나치 수위를 나타내는 지표가 있습니다. 가격이 이 Fibo 그리드에서 61.8 수준에 도달할 때 이 차트에 특정 설정을 가진 다른 고문을 배치하고 버튼을 눌러 주문을 열려면 고문이 필요합니다.

아래는 버튼이 있는 표시기 및 어드바이저의 화면입니다. 버튼이 있는 Expert Advisor의 소스 코드는 없습니다.   Fibo 그리드에서 61.8 레벨 달성을 추적하기 위한 Expert Advisor는 테스터에서 작동하지 않지만 처음에는 데모에서 모든 것이 잘 작동하면 실제에 그런 무리를 둘 수 있습니다.

지표 그리기 fibo 수준 버튼이 있는 어드바이저, 왼쪽 열기를 클릭해야 합니다.


이게 정말 가능할까요? 그렇다면 이를 어떻게 말로 구현한 다음 코드로 구현해야 할까요? 설명하다     최대한 상세하고 명확하게 부탁드립니다.

 
DanilaMactep # :

좋은 오후에요 여러분. 피보나치 수위를 나타내는 지표가 있습니다. 가격이 이 Fibo 그리드에서 61.8 수준에 도달할 때 이 차트에 특정 설정을 가진 다른 고문을 배치하고 버튼을 눌러 주문을 열려면 고문이 필요합니다.

아래는 버튼이 있는 표시기 및 어드바이저의 화면입니다. 버튼이 있는 Expert Advisor의 소스 코드는 없습니다.   Fibo 그리드에서 61.8 레벨 달성을 추적하기 위한 Expert Advisor는 테스터에서 작동하지 않지만 처음에는 데모에서 모든 것이 잘 작동하면 실제에 그런 무리를 둘 수 있습니다.


정말 이런 일이 가능할까요? 그렇다면 이를 어떻게 말로 구현한 다음 코드로 구현해야 할까요? 설명하다     최대한 상세하고 명확하게 부탁드립니다.

하루의 기억이 있습니까?