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

 
Alexandr Sokolov :

고맙습니다! 상업적인 목적이라면?

의미에서 시장을 위해?

그런 다음 이미지와 모양에서 GUI 라이브러리를 괴물로 만들려면 :-(

기존의 것들은 나름대로 형편없지만, MQL은 복잡한 GUI를 위한 것이 아닙니다. 그의 일은 계산하고 거래하는 것입니다. 그는 이것을 위해 투옥되었습니다.

즉, 할 수 있지만 고통스럽게 어리석은 일입니다.

 

CCanvas 라이브러리를 공부하기로 결정했습니다


이해할 수 없습니다. 오류가 없고(더 정확하게는 컴파일러가 오류를 발행하지 않습니다.) 화면에도 아무 것도 없습니다. 빨간색 삼각형을 그리고 싶은데...

 #include <Canvas\Canvas.mqh>

#property copyright "Alexandr Sokolov"
#property link        "https://www.mql5.com/en/users/asokolov7"
#property version    "1.00"
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots    0
CCanvas canvas;
//-------------------------------------------------------------------------------------------------
int OnInit ()
  {
   bool a = canvas.Create( "a" , 600 , 400 , 0 );
   canvas.FillTriangle( 100 , 100 , 80 , 120 , 120 , 120 , clrRed );
   canvas.Update( true ); Alert (a);
   return ( INIT_SUCCEEDED );
  }
//-------------------------------------------------------------------------------------------------
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[])
  {
   
   return (rates_total);
  }


그리고 이것이 결국 무엇인가


 
Alexandr Sokolov :

CCanvas 라이브러리를 공부하기로 결정했습니다

 #property copyright "IgorM"
#property link        "https://www.mql5.com/ru/users/igorm"
#property version    "1.00"
#property indicator_chart_window
#property indicator_plots 0

#include <Canvas\Canvas.mqh>

CCanvas canvas;
int xtr[ 3 ] = { 2 , 100 , 198 };
int ytr[ 3 ] = { 198 , 2 , 198 };
const uint clrtr = ColorToARGB ( clrRed );

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit ()
{
   if (!canvas.CreateBitmapLabel( 0 , 0 , "canvasname" , 10 , 10 , 200 , 200 )) return ( INIT_FAILED );
   canvas.Erase();
   canvas.FillTriangle(xtr[ 0 ], ytr[ 0 ], xtr[ 1 ], ytr[ 1 ], xtr[ 2 ], ytr[ 2 ], clrtr);
   canvas.Update();
   return ( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
{
   canvas.Destroy();
}
//+------------------------------------------------------------------+
//| 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[])
{
//---

//--- return value of prev_calculated for next call
   return (rates_total);
}
//+------------------------------------------------------------------+
 
Igor Makanu :

완성된 예시 감사합니다.

어렵지 않다면 내 실수에 대해 몇 마디 말해도 될까요? 방금 사이트의 도움말을 보았고 문서에는 기능 자체에 대한 설명만 포함되어 있으며 아래에는 어떤 기능이

 
Alexandr Sokolov :

완성된 예시 감사합니다.

어렵지 않다면 내 실수에 대해 몇 마디 말할 수 있습니까? 방금 사이트의 도움말을 보았고 문서에는 기능 자체에 대한 설명만 포함되어 있으며 아래에는 어떤 기능이

기사를 읽으십시오. 많은 기성품 예제가 있습니다 https://www.mql5.com/en/search#!keyword=Canvas&module=mql5_module_articles

 

안녕하세요!!!

무익한 주문을 이익, 추첨, 티켓으로 암기하는 기능을 작성하려고 합니다.
저는 이전에 어레이로 작업하지 않았고 모델과 참조에 따라 작업했습니다.

배열의 크기 를 지정하는 위치와 방법이 명확하지 않습니다.

고칠 수 있는지 확인하십시오.

======

구조체 구조 순서

{

더블 OrProf;

더블 오르로트;

정수 OrTiK;

};

StructOrderOrBuy[];

StructOrderOrSell[];

====

무효 Cloce_No_FreeMargin()

{

이중 이익_SELL = 0;

이중 이익_BUY = 0;

더블 no_profits_BUY = 0;

더블 no_profits_SELL = 0;

이중 cur_profits_SELL = 0;

이중 cur_profits_BUY = 0;

//---

정수 보 = 0;

정수 = 0;

InitStruct_Order(OrBuy);

InitStruct_Order(OrSell);

//ArrayResize(OrBuy,bo);

//ArrayResize(OrSell,so);

for(int trade= OrdersTotal()-1; trade>= 0; trade--)

{

if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES)==false)

부서지다;

if(OrderSymbol()==Symbol() && OrderMagicNumber()==매직)

{

if(주문 유형()==OP_SELL)

{

이익_SELL+=OrderProfit()+OrderSwap()+OrderCommission();

}

if(주문유형()==OP_BUY)

{

이익_BUY+=OrderProfit()+OrderSwap()+OrderCommission();

}

//================================================== ===========

if(주문 유형()==OP_SELL)

{

cur_profits_SELL=OrderProfit()+OrderSwap()+OrderCommission();

if(cur_profits_SELL<0)

{

no_profits_SELL+=cur_profits_SELL;

OrSell[so].OrProf = OrderProfit()-OrderSwap()-OrderCommission();

OrSell[so].OrLot = OrderLots();

OrSell[so].OrTiK = OrderTicket();

그래서 ++;

Print(" 판매 유형: 이익 - ",OrBuy[bo].OrProf,": Lot - ",OrBuy[bo].OrLot,": 티켓 - ",OrBuy[bo].OrTiK);

}

}

//================================================== ===========

if(주문 유형()==OP_BUY)

{

cur_profits_BUY=OrderProfit()+OrderSwap()+OrderCommission();

if(cur_profits_BUY<0)

{

no_profits_BUY+=cur_profits_BUY;

OrBuy[bo].OrProf = OrderProfit()-OrderSwap()-OrderCommission();

OrBuy[bo].OrLot = OrderLots();

OrBuy[bo].OrTiK = OrderTicket();

보++;

Print(" BUY 유형: Profit - ",OrBuy[bo].OrProf,": Lot - ",OrBuy[bo].OrLot,": 티켓 - ",OrBuy[bo].OrTiK);

}

}

}

}

}

//+----------------------------------------------- --------------------+

//| 주문에 대한 초기화 구조 |

//+----------------------------------------------- --------------------+

무효 InitStruct_Order(StructOrder &Masiv[])

{

정수 크기 = ArrayRange(Masiv, 0);


for(int i=0; i<크기; i++)

{

Masiv[i].OrProf = 0;

Masiv[i].OrLot = 0;

Masiv[i].OrTiK = 0;

}

}

 

여기요,

시장을 위해 mq4 파일과 많은 mqh 파일로 구성된 프로젝트를 하나로 조합하는 방법을 알려주십시오.

 

친구 여러분, iCustom을 통해 Expert Advisor에서 한 줄로 구성되어 있지만 구매 및 판매를 위해 다른 색상으로 표시되는 반전 표시기를 프로그래밍할 수 있도록 도와주세요. 그는 화살이 없습니다. 색상에 대해 세 개의 버퍼가 있는 것처럼 보이지만 실제로는 마우스로 가리키면 두 색상 모두에 대해 하나의 Value1 값만 표시됩니다. 막대를 비교하고 0과 비교하려고 시도했지만 도움이되지 않습니다. 그러한 지표의 반전을 프로그래밍하는 방법, 누가 알겠습니까? 다음은 칠면조 버퍼와 그림의 초기 설정입니다. StepMA처럼 보이지만 그가 아닙니다.

 #property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 DodgerBlue
#property indicator_color2 Tomato
#property indicator_color3 Tomato
#property indicator_width1 2
#property indicator_width2 2
#property indicator_width3 2
//----
extern int     Range           = 9 ;
extern int     FastMA          = 3 ;
extern int     SlowMA          = 30 ;
extern int     filter          = 25 ;
extern int     normalizeDigits = 4 ;

extern bool    alertsOn        = false ;
extern bool    alertsOnCurrent = false ;
extern bool    alertsMessage   = true ;
extern bool    alertsSound     = true ;
extern bool    alertsEmail     = false ;
extern string soundfile       = "alert2.wav" ;


double Downa[];
double Downb[];
double trend[];
double fAMA[];
double mAMA[];
double AMA[];

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

int init()
  {
   for ( int i= 0 ; i< indicator_buffers ; i++) SetIndexStyle(i, DRAW_LINE );
   IndicatorBuffers( 6 );
   SetIndexBuffer ( 0 , fAMA); 
   SetIndexBuffer ( 1 , Downa); 
   SetIndexBuffer ( 2 , Downb); 
   SetIndexBuffer ( 3 , trend); 
   SetIndexBuffer ( 4 , mAMA);
   SetIndexBuffer ( 5 , AMA);
   return ( 0 );
}
int deinit()
{
   return ( 0 );
}

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


int start()
{
   int counted_bars = IndicatorCounted(); 
       if (counted_bars < 0 ) return (- 1 ); 
       if (counted_bars > 0 ) counted_bars--;  
         int limit= MathMin ( Bars -counted_bars, Bars - 1 );
         if (trend[limit] == - 1 ) ClearPoint(limit,Downa,Downb);

 
   
   double k1 = 2.0 / (SlowMA + 1 );
   double k2 = 2.0 / (FastMA + 1 ) - k1;
   for ( int i = limit; i>= 0 ; i--)
   {
       double sdAMA = 0 ;
       double Noise = 0 ; for ( int k= 0 ; k<Range; k++) Noise += MathAbs (Close[i+k] - Close[i+k+ 1 ]);
       double ER    = 0 ; if (Noise != 0 ) ER = MathAbs (Close[i] - Close[i+Range]) / Noise;
       double SSC   = (ER*k2+k1);
 
     
      
      AMA[i]  = AMA[i+ 1 ] + NormalizeDouble (SSC*SSC*(Close[i] - AMA[i+ 1 ]), normalizeDigits);
      mAMA[i] = AMA[i];
 
         if (filter < 1 ) fAMA[i] = mAMA[i];
         else
         {
             for (k = i; k <= i + SlowMA - 1 ; k++)  sdAMA = sdAMA + MathAbs (mAMA[k] - mAMA[k+ 1 ]);
               double dAMA  = mAMA[i] - mAMA[i+ 1 ];
               if (dAMA >= 0 )
                   if (dAMA < NormalizeDouble (filter*sdAMA/( 100 *SlowMA), 4 ) &&  High[i] <= High[Highest( NULL , 0 , MODE_HIGH , 4 , i)]+ 10 * Point )
                         fAMA[i] = fAMA[i+ 1 ];
                   else    fAMA[i] = mAMA[i];
               else
                   if ( MathAbs (dAMA) < NormalizeDouble (filter*sdAMA/( 100 *SlowMA), 4 ) && Low[i] > Low[Lowest( NULL , 0 , MODE_LOW , 4 , i)]- 10 * Point )
                        fAMA[i] = fAMA[i+ 1 ];
                   else   fAMA[i] = mAMA[i];
         }
       
      Downa[i] = EMPTY_VALUE ;
      Downb[i] = EMPTY_VALUE ;
      trend[i] = trend[i+ 1 ];
         if (fAMA[i]> fAMA[i+ 1 ]) trend[i] = 1 ;
         if (fAMA[i]< fAMA[i+ 1 ]) trend[i] =- 1 ;
         if (trend[i]==- 1 ) PlotPoint(i,Downa,Downb,fAMA);
   }
    
   //
  
      
   if (alertsOn)
   {
       if (alertsOnCurrent)
           int whichBar = 0 ;
       else      whichBar = 1 ;
       if (trend[whichBar] != trend[whichBar+ 1 ])
       if (trend[whichBar] == 1 )
            doAlert( "buy" );
       else   doAlert( "sell" );       
   }
   return ( 0 );
}

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


void doAlert( string doWhat)
{
   static string    previousAlert= "nothing" ;
   static datetime previousTime;
   string message;
   
       if (previousAlert != doWhat || previousTime != Time[ 0 ]) {
          previousAlert  = doWhat;
          previousTime   = Time[ 0 ];

           //
           //
          

          message =   StringConcatenate ( Symbol (), " at " ,TimeToStr( TimeLocal (), TIME_SECONDS ), " AMA STL_Color " ,doWhat);
             if (alertsMessage) Alert (message);
             if (alertsEmail)   SendMail ( StringConcatenate ( Symbol (), " AMA STL_Color " ),message);
             if (alertsSound)   PlaySound (soundfile);
      }
}
      
//------------------------------------------------------------------
//
//------------------------------------------------------------------


void ClearPoint( int i, double & first[], double & second[])
{
   if ((second[i]  != EMPTY_VALUE ) && (second[i+ 1 ] != EMPTY_VALUE ))
        second[i+ 1 ] = EMPTY_VALUE ;
   else
       if ((first[i] != EMPTY_VALUE ) && (first[i+ 1 ] != EMPTY_VALUE ) && (first[i+ 2 ] == EMPTY_VALUE ))
          first[i+ 1 ] = EMPTY_VALUE ;
}
void PlotPoint( int i, double & first[], double & second[], double & from[])
{
   if (first[i+ 1 ] == EMPTY_VALUE )
       if (first[i+ 2 ] == EMPTY_VALUE ) 
            { first[i]  = from[i]; first[i+ 1 ]  = from[i+ 1 ]; second[i] = EMPTY_VALUE ; }
       else   { second[i] = from[i]; second[i+ 1 ] = from[i+ 1 ]; first[i]  = EMPTY_VALUE ; }
   else      { first[i]  = from[i]; second[i]   = EMPTY_VALUE ; }
} 

 
zig2003 :

친구 여러분, iCustom을 통해 Expert Advisor에서 한 줄로 구성되어 있지만 구매 및 판매를 위해 다른 색상으로 표시되는 반전 표시기를 프로그래밍할 수 있도록 도와주세요. 그는 화살이 없습니다. 색상에 대해 세 개의 버퍼가 있는 것처럼 보이지만 실제로는 마우스로 가리키면 두 색상 모두에 대해 하나의 Value1 값만 표시됩니다. 막대를 비교하고 0과 비교하려고했지만 도움이되지 않습니다. 그러한 지표의 반전을 프로그래밍하는 방법, 누가 알겠습니까? 다음은 칠면조 버퍼와 그림의 초기 설정입니다. StepMA처럼 보이지만 그가 아닙니다.


버튼을 사용하여 코드를 붙여넣으 세요. &quot;MQL5 코드 삽입&quot; 버튼

 
zig2003 :

친구 여러분, iCustom을 통해 Expert Advisor에서 한 줄로 구성되어 있지만 구매 및 판매를 위해 다른 색상으로 표시되는 반전 표시기를 프로그래밍할 수 있도록 도와주세요. 그는 화살이 없습니다. 색상에 대해 세 개의 버퍼가 있는 것처럼 보이지만 실제로는 마우스로 가리키면 두 색상 모두에 대해 하나의 Value1 값만 표시됩니다. 막대를 비교하고 0과 비교하려고했지만 도움이되지 않습니다. 그러한 지표의 반전을 프로그래밍하는 방법, 누가 알겠습니까? 다음은 칠면조 버퍼와 그림의 초기 설정입니다. StepMA처럼 보이지만 그가 아닙니다.


예시

DRAW_COLOR_LINE 라이트 예시

DRAW_COLOR_LINE에 기반한 표시기. 두 개의 표시기 버퍼 - 하나는 값(' ColorLineBuffer ')이고 다른 하나는 색상(' ColorLineColors ')입니다.

 //+------------------------------------------------------------------+ 
//|                                         DRAW_COLOR_LINE Lite.mq5 | 
//|                        Copyright 2016, MetaQuotes Software Corp. | 
//|                                             https://www.mql5.com | 
//+------------------------------------------------------------------+ 
#property copyright "Copyright 2011, MetaQuotes Software Corp." 
#property link        "https://www.mql5.com" 
#property version    "1.00" 

#property description "An indicator to demonstrate DRAW_COLOR_LINE" 
#property description "It draws a line on Close price in colored pieces of 20 bars each" 
#property description "The width, style and color of the line parts are changed randomly" 
#property description "every N ticks" 

#property indicator_chart_window 
#property indicator_buffers 2 
#property indicator_plots    1 
//--- plot ColorLine 
#property indicator_label1    "ColorLine" 
#property indicator_type1    DRAW_COLOR_LINE 
//--- Define 5 colors for coloring each bar (they are stored in the special array) 
#property indicator_color1    clrBlue , clrRed // (Up to 64 colors can be specified) 
#property indicator_style1    STYLE_SOLID 
#property indicator_width1    3 
//--- A buffer for plotting 
double          ColorLineBuffer[];
//--- A buffer for storing the line color on each bar 
double          ColorLineColors[];
//+------------------------------------------------------------------+ 
//| Custom indicator initialization function                         | 
//+------------------------------------------------------------------+ 
int OnInit ()
  {
//--- Binding an array and an indicator buffer 
   SetIndexBuffer ( 0 ,ColorLineBuffer, INDICATOR_DATA );
   SetIndexBuffer ( 1 ,ColorLineColors, INDICATOR_COLOR_INDEX );
//---
   ArraySetAsSeries (ColorLineBuffer, true );
   ArraySetAsSeries (ColorLineColors, true );
//--- 
   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[])
  {
   ArraySetAsSeries (close, true );
   if (prev_calculated== 0 )
     {
       for ( int i= 0 ;i<rates_total;i++)
         ColorLineBuffer[i]=close[i];
     }
//--- Block for calculating indicator values 
   for ( int i= 0 ;i< 10 ;i++)
     {
       //--- Write the indicator value into the buffer 
      ColorLineBuffer[i]=close[i];
       //--- For this bar, the line will have the color with the index color_index 
       if (ColorLineBuffer[i]>ColorLineBuffer[i+ 1 ])
         ColorLineColors[i]= 0 ;
       else
         ColorLineColors[i]= 1 ;
     }

//--- Return the prev_calculated value for the next call of the function 
   return (rates_total);
  }
//+------------------------------------------------------------------+


그리고 EA는 버퍼 번호 '0'(' ColorLineBuffer ')과 숫자 '1'(' ColorLineColors ')에서 값을 복사합니다.

 //+------------------------------------------------------------------+
//|                                 DRAW_COLOR_LINE Lite Example.mq5 |
//|                              Copyright © 2019, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2019, Vladimir Karputov"
#property link        "http://wmua.ru/slesar/"
#property version    "1.00"
//---
int     handle_iCustom;                       // variable for storing the handle of the iCustom indicator
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//---
//--- create handle of the indicator iCustom
   handle_iCustom= iCustom ( Symbol (), Period (), "DRAW_COLOR_LINE Lite" );
//--- if the handle is not created
   if (handle_iCustom== INVALID_HANDLE )
     {
       //--- tell about the failure and output the error code
       PrintFormat ( "Failed to create handle of the iCustom indicator for the symbol %s/%s, error code %d" ,
                   Symbol (),
                   EnumToString ( Period ()),
                   GetLastError ());
       //--- the indicator is stopped early
       return ( INIT_FAILED );
     }
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---
   Comment ( "" );
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
   double array_value[],array_color[];
   ArraySetAsSeries (array_value, true );
   ArraySetAsSeries (array_color, true );
   int start_pos= 0 ,count= 1 ;
   if (!iGetArray(handle_iCustom, 0 ,start_pos,count,array_value) ||
      !iGetArray(handle_iCustom, 1 ,start_pos,count,array_color))
     {
       return ;
     }
//---
   string text= "Value: " + DoubleToString (array_value[ 0 ], 8 )+ ", color: " + DoubleToString (array_color[ 0 ], 8 );
   Comment (text);
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
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))
     {
       PrintFormat ( "ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!" , __FILE__ , __FUNCTION__ );
       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)
     {
       //--- if the copying fails, tell the error code
       PrintFormat ( "ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d" ,
                   __FILE__ , __FUNCTION__ ,count,copied, GetLastError ());
       //--- quit with zero result - it means that the indicator is considered as not calculated
       return ( false );
     }
   return (result);
  }
//+------------------------------------------------------------------+
Усреднение ценовых рядов без дополнительных буферов для промежуточных расчетов
Усреднение ценовых рядов без дополнительных буферов для промежуточных расчетов
  • www.mql5.com
В своей статье  я сделал достаточно убедительные тесты, доказывающие тот факт, что далеко не каждый вызов пользовательского или даже технического индикатора в коде - это самый оптимальный вариант для обработки им промежуточных расчетов в разрабатываемом индикаторе. Итоговый результат по скорости своего исполнения может оказаться значительно...