Yeni başlayanlardan sorular MQL5 MT5 MetaTrader 5 - sayfa 1239

 
Alexey Viktorov :

Hiçbir şey tavsiye edemem. Optimizasyon kullanmıyorum. Ben bunu şarlatanlık olarak görüyorum.

Aynı fikirde olmamak. Bence optimizasyon, belirli bir çift ve strateji için en uygun parametrelerin seçimidir.

PS Şimdi spreadler normal görünüyor.

 
Youri Lazurenko :

Aynı fikirde olmamak.

Senin için kampanya yapmadım. Sadece kişisel fikrimi belirttim.

 
Alexey Viktorov :

Senin için kampanya yapmadım. Sadece kişisel fikrimi belirttim.

Belki de fikrim yanlıştır. Ben de kampanya yapmıyorum.

 

Merhaba. Yardıma ihtiyacım var. Bekleyen bir emrin ömrünü, tercihen çubuk sayısıyla sınırlamak gerekir. mql4'te şu işlevi kullandım:

 datetime DateExp()                                 
{
   datetime expDate = 0 ;
   
   if ( Period () == PERIOD_M1 )
      expDate = TimeCurrent () + ExpDate* 60 ;
      
   if ( Period () == PERIOD_M5 )
      expDate = TimeCurrent () + ExpDate* 5 * 60 ;
    
   if ( Period () == PERIOD_M15 )
      expDate = TimeCurrent () + ExpDate* 15 * 60 ;
    
   if ( Period () == PERIOD_M30 )
      expDate = TimeCurrent () + ExpDate* 30 * 60 ;
    
   if ( Period () == PERIOD_H1 )
      expDate = TimeCurrent () + ExpDate* 60 * 60 ;
    
   if ( Period () == PERIOD_H4 )
      expDate = TimeCurrent () + ExpDate* 4 * 60 * 60 ;
   
   if ( Period () == PERIOD_D1 )
      expDate = TimeCurrent () + ExpDate* 24 * 60 * 60 ;      
    
   if ( Period () == PERIOD_W1 ) 
      expDate = TimeCurrent () + ExpDate* 7 * 24 * 60 * 60 ; 
   
   if ( Period () == PERIOD_MN1 )
      expDate = TimeCurrent () + ExpDate* 30 * 24 * 60 * 60 ;
          
   return (expDate);  
}

nerede

harici int ExpDate = 6; // sipariş ömrü çubuklarının sayısı

Her şey çalıştı.

mql5'te benzer bir şey denedim:

 datetime DateExp()                                 
{
   datetime expDate = 0 ;
   
   if ( Period () == PERIOD_M1 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M1 )*ExpDate;
      
   if ( Period () == PERIOD_M2 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M2 )*ExpDate;
   
   if ( Period () == PERIOD_M3 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M3 )*ExpDate;
   
   if ( Period () == PERIOD_M4 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M4 )*ExpDate;
      
   if ( Period () == PERIOD_M5 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M5 )*ExpDate;
   
   if ( Period () == PERIOD_M6 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M6 )*ExpDate;
   
   if ( Period () == PERIOD_M10 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M10 )*ExpDate;
   
   if ( Period () == PERIOD_M12 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M12 )*ExpDate;
    
   if ( Period () == PERIOD_M15 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M15 )*ExpDate;
   
   if ( Period () == PERIOD_M20 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M20 )*ExpDate;
    
   if ( Period () == PERIOD_M30 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_M30 )*ExpDate;
    
   if ( Period () == PERIOD_H1 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_H1 )*ExpDate;
   
   if ( Period () == PERIOD_H2 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_H2 )*ExpDate;
   
   if ( Period () == PERIOD_H3 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_H3 )*ExpDate;
    
   if ( Period () == PERIOD_H4 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_H4 )*ExpDate;
   
   if ( Period () == PERIOD_H6 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_H6 )*ExpDate;
   
   if ( Period () == PERIOD_H8 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_H8 )*ExpDate;
   
   if ( Period () == PERIOD_H12 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_H12 )*ExpDate;
   
   if ( Period () == PERIOD_D1 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_D1 )*ExpDate;      
    
   if ( Period () == PERIOD_W1 ) 
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_W1 )*ExpDate; 
   
   if ( Period () == PERIOD_MN1 )
      expDate = TimeCurrent () + PeriodSeconds ( PERIOD_MN1 )*ExpDate;
          
   return (expDate);  
}

nerede

intExpDate = 6 girin; // sipariş ömrü çubuklarının sayısı

Sonra, örneğin satın almak için bekleyen bir sipariş verirken onu (yukarıdaki işlevi) kullanmaya çalıştım.

               request.action       = TRADE_ACTION_PENDING ;                                         
               request.magic        = Magic;                                                       
               request.symbol       = _Symbol ;                                                      
               request.volume       = GetLots();                                                    
               request.price        = openBuy;                                                      
               request.sl           = slBuy;                                                        
               request.tp           = tpBuy;                                                        
               request.type         = ORDER_TYPE_BUY_STOP ;                                          
               request.type_filling = ORDER_FILLING_FOK ;                                           
               request.expiration   = DateExp();                                                    
               request.deviation    = SG; 

Bekleyen bir sipariş verilir, ancak etkinleştirilene kadar (test cihazında) geçerlidir. request.expiration'a sadece bir sayı koymaya çalıştım, hiçbir şey yardımcı olmadı. Google'da herhangi bir bilgi bulamadım. Benimle ilgili sorun ne? Belirli bir süre sonra sipariş neden silinmiyor?

PS Açıklamada çıkarıldığında, DateExp() işlevi tarih ve saati gösterir.

Документация по MQL5: Константы, перечисления и структуры / Торговые константы / Свойства ордеров
Документация по MQL5: Константы, перечисления и структуры / Торговые константы / Свойства ордеров
  • www.mql5.com
Приказы на проведение торговых операций оформляются ордерами. Каждый ордер имеет множество свойств для чтения, информацию по ним можно получать с помощью функций Идентификатор позиции, который ставится на ордере при его исполнении. Каждый исполненный ордер порождает сделку, которая открывает новую или изменяет уже существующую позицию...
 
Youri Lazurenko :


Eklemeyi unuttum:

 struct MqlTradeRequest
  {
   ENUM_TRADE_REQUEST_ACTIONS     action;           // Тип выполняемого действия
   ulong                          magic;             // Штамп эксперта (идентификатор magic number)
   ulong                          order;             // Тикет ордера
   string                         symbol;           // Имя торгового инструмента
   double                         volume;           // Запрашиваемый объем сделки в лотах
   double                         price;             // Цена 
   double                         stoplimit;         // Уровень StopLimit ордера
   double                         sl;               // Уровень Stop Loss ордера
   double                         tp;               // Уровень Take Profit ордера
   ulong                          deviation;         // Максимально приемлемое отклонение от запрашиваемой цены
   ENUM_ORDER_TYPE                type;             // Тип ордера
   ENUM_ORDER_TYPE_FILLING        type_filling;     // Тип ордера по исполнению
   ENUM_ORDER_TYPE_TIME           type_time;         // Тип ордера по времени действия
   datetime                       expiration;       // Срок истечения ордера (для ордеров типа ORDER_TIME_SPECIFIED)
   string                         comment;           // Комментарий к ордеру
   ulong                          position;         // Тикет позиции
   ulong                          position_by;       // Тикет встречной позиции
  };
 
Vladimir Karputov :

Eklemeyi unuttum:

Teşekkür ederim zaten kendim buldum, sorunun kaldırıldığını yazmak istedim. Bunlar ayarlanmadan önce, ancak ayarlandığında, doğru parametre olmadığı ortaya çıkıyor request.type_time = ORDER_TIME_GTC; request.type_time = ORDER_TIME_SPECIFIED için düzeltildi; ve her şey çalışıyor. Ama geri bildiriminiz ve tavsiyeniz için çok teşekkür ederim.

 
Artyom Trishkin :

Alexey, ilk başta göstergenizi en azından mum çizdirmeniz gerektiğini söyledi. Nasıllarsa öyle. En azından mevcut çubukta. Bu nasıl yapılır - anlamaya yönelik ilk adımın geçtiğini düşünün. Ancak, farklı parametreleri yazarak ve sıralayarak değil, kendi zihninizle ortaya çıkması arzu edilir.

Ve burada "önceden gerekli / gerekli değil"? Gerçekten buna ihtiyacınız var - çünkü sadece dört değerden bir mum çizemezsiniz.

Burada USDJPY,H8 grafiğinden 5 mum (gerçek) çekmesi gereken çok basit bir test göstergesi yazdım.

 //+------------------------------------------------------------------+
//|                                                        cTest.mq5 |
//|                                     Copyright 2020, Tabolin S.N. |
//|                           https://www.mql5.com/ru/users/vip.avos |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, Tabolin S.N."
#property link        "https://www.mql5.com/ru/users/vip.avos"
#property version    "1.00"
//#property indicator_separate_window
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots    1
//--- plot bars
#property indicator_label1    "bars"
#property indicator_type1    DRAW_CANDLES
#property indicator_color1    clrGold
#property indicator_style1    STYLE_SOLID
#property indicator_width1    1
//--- indicator buffers
double    barsBuffer1[];
double    barsBuffer2[];
double    barsBuffer3[];
double    barsBuffer4[];
//+------------------------------------------------------------------+
double    newCandles_Open[ 5 ]   = { 106.785 , 106.724 , 106.760 , 106.767 , 106.769 };
double    newCandles_High[ 5 ]   = { 106.792 , 106.765 , 106.780 , 106.781 , 106.769 };
double    newCandles_Low[ 5 ]    = { 106.716 , 106.719 , 106.746 , 106.758 , 106.715 };
double    newCandles_Close[ 5 ]  = { 106.724 , 106.760 , 106.766 , 106.769 , 106.725 };

int       tick_count           = 0 ;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit ()
{
//--- indicator buffers mapping
   SetIndexBuffer ( 0 , barsBuffer1, INDICATOR_DATA );
   SetIndexBuffer ( 1 , barsBuffer2, INDICATOR_DATA );
   SetIndexBuffer ( 2 , barsBuffer3, INDICATOR_DATA );
   SetIndexBuffer ( 3 , barsBuffer4, INDICATOR_DATA );
   
   ArraySetAsSeries (barsBuffer1  , true );
   ArraySetAsSeries (barsBuffer2  , true );
   ArraySetAsSeries (barsBuffer3  , true );
   ArraySetAsSeries (barsBuffer4  , true );
   
   ArrayInitialize (barsBuffer1   , 0.0 );
   ArrayInitialize (barsBuffer2   , 0.0 );
   ArrayInitialize (barsBuffer3   , 0.0 );
   ArrayInitialize (barsBuffer4   , 0.0 );
//---
   return ( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int    OnCalculate (
   const int         rates_total,       // размер входных таймсерий
   const int         prev_calculated,   // количество обработанных баров на предыдущем вызове
   const datetime &  time[],             // массив Time
   const double &    open[],             // массив Open
   const double &    high[],             // массив High
   const double &    low[],             // массив Low
   const double &    close[],           // массив Close
   const long &      tick_volume[],     // массив Tick Volume
   const long &      volume[],           // массив Real Volume
   const int &       spread[]           // массив Spread
   )
{
   if (rates_total - prev_calculated > 1 )
   {
       if (prev_calculated == 0 )
      {
         Print ( "~~~~ Предварительный расчёт индикатора." );
         for ( int i = 0 ; i < 5 ; i++)
         {
            barsBuffer1[ 0 ] = newCandles_Open[i];
            barsBuffer2[ 0 ] = newCandles_High[i];
            barsBuffer3[ 0 ] = newCandles_Low[i];
            barsBuffer4[ 0 ] = newCandles_Close[i];
         }
         Print ( "~~~~ Предварительный расчёт индикатора закончен." );
      }
       else return ( 0 );
   }
   else Print ( "tick_count = " ,++tick_count);
//--- return value of prev_calculated for next call
   return (rates_total);
}
//+------------------------------------------------------------------+

Sadece bu mumları çiziyor, başka bir şey değil.

Ama çalıştırırsam, çizgiyi çiziyor...

Açıkla bana aptal, neyi yanlış yapıyorum?


Bu arada, belgelerde bir yazım hatası var:

 const datetime &  time {} ,             // массив Time
Документация по MQL5: Обработка событий / OnCalculate
Документация по MQL5: Обработка событий / OnCalculate
  • www.mql5.com
события Calculate для обработки изменений ценовых данных. Существуют два варианта функции, в пределах одного индикатора нельзя использовать оба варианта. [in]  Размер массива price[] или входных таймсерий, доступных индикатору для расчета. Во втором варианте функции значение параметра соответствует количеству баров на графике, на котором он...
Dosyalar:
cTest.mq5  8 kb
 
Сергей Таболин :

Burada USDJPY,H8 grafiğinden 5 mum (gerçek) çekmesi gereken çok basit bir test göstergesi yazdım.

Sadece bu mumları çiziyor, başka bir şey değil.

Ama çalıştırırsam, çizgiyi çiziyor...

Açıkla bana aptal, neyi yanlış yapıyorum?


Bu arada, belgelerde bir yazım hatası var:

Hata ayıklayıcıda, zamanı[0] kontrol edin ve şu soruyu yanıtlayın: "Neden grafiğin SOL SOL KENARINDAN mum çizmeye çalışıyorsunuz???


Size söyledim - DRAW_CANDLES üzerindeki yardımı kullanın. DRAW_CANDLES yardımından örneği kopyalayın. Anlayın. Ve tiki'de senin için hala çok erken.

Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_CANDLES
Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_CANDLES
  • www.mql5.com
//|                                                 DRAW_CANDLES.mq5 | //|                        Copyright 2011, MetaQuotes Software Corp. | //|                                             https://www.mql5.com | "Рисует в отдельном окне разным цветом свечи по случайно выбранному из MarketWatch символу...
 
Vladimir Karputov :

Hata ayıklayıcıda, zamanı[0] kontrol edin ve şu soruyu yanıtlayın: "Neden grafiğin SOL SOL KENARINDAN mum çizmeye çalışıyorsunuz???


Size söyledim - DRAW_CANDLES üzerindeki yardımı kullanın. DRAW_CANDLES yardımından örneği kopyalayın. Anlayın. Ve tiki'de senin için hala çok erken.

Vladimir, en sol kenardan çizmeye çalıştığım şeyi zaten anladım. Testte şimdi sağ kenardan bir çizim var

   ArraySetAsSeries (barsBuffer1  , true );
   ArraySetAsSeries (barsBuffer2  , true );
   ArraySetAsSeries (barsBuffer3  , true );
   ArraySetAsSeries (barsBuffer4  , true );

Ve mum fiyatları gerçek alındı... Ve kene yok...

 
Сергей Таболин :

Vladimir, en sol kenardan çizmeye çalıştığım şeyi zaten anladım. Testte şimdi sağ kenardan bir çizim var

Ve mum fiyatları gerçek alındı... Ve kene yok...

Son olarak, yardımdan bir örnek alın! Peki, ne kadar yapabilirsin? Anlamlarını gerçekten anlamadıysanız, icat ettiğiniz yapıları kullanmanıza gerek yoktur. Standart yapıları kullanın - nasıl çalıştıklarını anlayın. Bundan sonra, tasarımlarınızı çöp kutusuna atın.


Ve şablonu oluşturmak için 'MQL Sihirbazı'nı kullanın.

kod

 //+------------------------------------------------------------------+
//|                                                 Draw Candles.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link        "https://www.mql5.com"
#property version    "1.00"
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots    1
//--- plot USDJPY
#property indicator_label1    "USDJPY"
#property indicator_type1    DRAW_CANDLES
#property indicator_color1    clrRed
#property indicator_style1    STYLE_SOLID
#property indicator_width1    1
//--- input parameters
input int       Input1= 9 ;
//--- indicator buffers
double    Buffer1[];
double    Buffer2[];
double    Buffer3[];
double    Buffer4[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit ()
  {
//--- indicator buffers mapping
   SetIndexBuffer ( 0 ,Buffer1, INDICATOR_DATA );
   SetIndexBuffer ( 1 ,Buffer2, INDICATOR_DATA );
   SetIndexBuffer ( 2 ,Buffer3, INDICATOR_DATA );
   SetIndexBuffer ( 3 ,Buffer4, INDICATOR_DATA );
//---
   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[])
  {
//---
   int limit=prev_calculated- 1 ;
   if (prev_calculated== 0 )
      limit= 0 ;
   for ( int i=limit; i<rates_total; i++)
     {
      Buffer1[i]=open[i];
      Buffer2[i]=high[i];
      Buffer3[i]=low[i];
      Buffer4[i]=close[i];
     }
//--- return value of prev_calculated for next call
   return (rates_total);
  }
//+------------------------------------------------------------------+

ve sonuç


Dosyalar: