Tutte le domande dei nuovi arrivati su MQL4 e MQL5, aiuto e discussione su algoritmi e codici - pagina 145

 
fxsaber:

ArraySort è facile da scrivere per strutture semplici.

Scritto da
#include <TypeToBytes.mqh>

template <typename T>
void Swap( T &Value1, T &Value2 )
{
  const T Tmp = Value1;
  
  Value1 = Value2;
  Value2 = Tmp;
}

// Сортировка массива любого простого типа
template <typename T>
bool MyArraySort( T &Array[] )
{
  if (!ArraySort(Array))
  {
    const int Size = ArraySize(Array);
    
    for (int i = 0; i < Size - 1; i++)
    {
      const T Tmp = Array[i];
      
      for (int j = i + 1; j < Size; j++)
        if (_R(Tmp) == Array[j]) // TypeToBytes.mqh
        {
          Swap(Array[i + 1], Array[j]);
          
          i++;
        }
    }      
  }
  
  return(true);
}

// Возвращает количество различных элементов массива, которых не меньше Repeat
template <typename T>
int Strange( const T &InArray[], const int Repeat = 2 )
{
  int Res = 0;  
  
  T Array[];
  
  const int Size = ArraySize(InArray);
  
  if ((ArrayCopy(Array, InArray) == Size) && MyArraySort(Array))
  {    
    int Tmp = 1;
    
    for (int i = 1; i < Size; i++, Tmp++)
      if (_R(Array[i - 1]) != Array[i]) // TypeToBytes.mqh
      {
        if (Tmp >= Repeat)
          Res++;
        
        Tmp = 0;
      }
      
    if (Tmp >= Repeat)    
      Res++;
  }

  return(Res);
}

void OnStart()
{
  int Array[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};  
  const int Size = ArraySize(Array);

  MqlTick Ticks[], NullTick = {0};
  ArrayResize(Ticks, Size);        
  
  for (int i = 0; i < Size; i++)
  {
    Ticks[i] = NullTick;
    
    Ticks[i].time = Array[i];
  }
  
  for (int i = 1; i <= 4; i++)
  {
    Print(Strange(Array, i));
    
    Print(Strange(Ticks, i));
  }
}
 

Buona sera, per favore aiutatemi con l'EA che ho scritto, se si può chiamare così.

In generale, l'EA fa quello che mi aspettavo che facesse. Ma c'è uno strano inconveniente.

1) In alcuni casi, invece di ordini pendenti apre prima una posizione Sell con 0,02 lotti. Anche se secondo lo script non dovrebbe. (errore da qualche parte). Non riesco a capire a cosa sia legato, a volte tutto va bene e a volte il primo apre un Sell.

Per favore aiutatemi con questo errore. Voglio dare alla mia EA alcuni commenti generali sui miei scritti e sugli errori. Ho fatto il mio primo Expert Advisor, giudicare di sicuro.

//+------------------------------------------------------------------+
//|                                               ALEXANDROS_001.mq4 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
input double perv_Lot=0.01;
input double  shag1=40;
input double  profit=20;
input double  koredor=10;
input int    magic=907;
input int    slipage=10;
int ret,ORD=0,ic;
//
void OnTick()
  {

//-----ищет цену последнего открытого ордера---------------------------------------------------------------
  double OpenPrice = 0.0;
  
     int    orders=OrdersTotal();    
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol())continue;
        if(  OrderType()==OP_SELL||OrderType()==OP_BUY)
        
           OpenPrice = OrderOpenPrice();
                    break;
        }

//------если нет открытых позиций открывает два отложника------------------------------------------------------
  int kolpos=0;
   for (int pos=0; pos<OrdersTotal(); pos++)
  {
   OrderSelect(pos,SELECT_BY_POS,MODE_TRADES);
   if(OrderSymbol()==Symbol()&&OrderMagicNumber()==magic)
   kolpos++;  
    }
    if (kolpos==0)
    {
    OrderSend(Symbol(),OP_BUYSTOP,perv_Lot,Ask+shag1*Point,slipage,0,0,NULL,magic,0,clrGreen);
    OrderSend(Symbol(),OP_SELLSTOP,perv_Lot,Bid-shag1*Point,slipage,0,0,NULL,magic,0,clrRed);
    }
//--------------определяет если есть открытые позиции---------------------------------------------------------------------  
    int order=0;
   for (int pos=0; pos<OrdersTotal(); pos++)
  {
   OrderSelect(pos,SELECT_BY_POS,MODE_TRADES);
   if(OrderSymbol()==Symbol()&&OrderMagicNumber()==magic)
  
   if(OrderType()==OP_SELL||OrderType()==OP_BUY) //если это продажи или покупки считаем что сделки открыты
  
   order++;
    }
    if(order>0)
//--------------- находит и удаляет отложки.---------------------------------------------------------------
    {
    
    for(ic=OrdersTotal()-1;ic>=0;ic--)
                   {
                  if(OrderSelect(ic,SELECT_BY_POS,MODE_TRADES)==false) continue;
                  if (OrderSymbol()==Symbol())
                  {                  
                  if (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP)//если это отложки то удаляем
                  {
                  ret=OrderDelete(OrderTicket());//удалил отложки
                  }
                  }}
//--------------ищем последний открытый ордер-------------------------------------    
                  for(ic=OrdersTotal()-1;ic>=0;ic--)
                   {
                  if(OrderSelect(ic,SELECT_BY_POS,MODE_TRADES)==false) continue;
                  if (OrderSymbol()==Symbol()&&OrderMagicNumber()==magic&&OrderOpenPrice()==OpenPrice)
                  
                  
                  {
                
                  double minus=NormalizeDouble( Ask-OpenPrice,Digits);
                  double plus= NormalizeDouble(Ask-OpenPrice,Digits);
                  if(Digits==3)
                   {
                    minus=minus*100;
                    plus=plus*100;
                   }
                   if(Digits==5)
                   {
                   minus=minus*10000;
                   plus=plus*10000;
                   }
  //-------------если последний открытый ордер SELL--------------------------------------------------------------                
                  if (OrderType()==OP_SELL)
                  {
                  if(plus<=-profit)
                  {
                  for(int i=OrdersTotal()-1;i>=0;i--)
                  {
                  OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
                  if(OrderType()==OP_BUY)OrderClose(OrderTicket(),OrderLots(),Bid,slipage,0);
                  if(OrderType()==OP_SELL)OrderClose(OrderTicket(),OrderLots(),Ask,slipage,0);
                  }
                  }
//---------------а если цена пошла в минус---------------------------------------------------------------------------                
                 if( minus>=koredor)
                  {
                  double Lot=OrderLots();
                  OrderSend(Symbol(),OP_BUY,Lot*2,Ask,slipage,0,0,NULL,magic,0,clrRed);// открываем BUY с удвоеным лотом
                  }
                  }
                  double minusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                  double plusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                   if(Digits==3)
                   {
                    minusbuy=minusbuy*100;
                    plusbuy=plusbuy*100;
                   }
                   if(Digits==5)
                   {
                   minusbuy=minusbuy*10000;
                   plusbuy=plusbuy*10000;
                   }
//-----------------если последний ордер Buy--------------------------------------------------------------------------------
                  if (OrderType()==OP_BUY)
                  {
                   if(plusbuy>=profit)//-------если цена пошла в плюс-------------------------------------------------------
                  {
                  for(int i=OrdersTotal()-1;i>=0;i--)
                  {
                  OrderSelect(i,SELECT_BY_POS,MODE_TRADES);//---находим и закрываем все открытые ордера--------------------
                  if(OrderType()==OP_BUY)OrderClose(OrderTicket(),OrderLots(),Bid,slipage,0);
                  if(OrderType()==OP_SELL)OrderClose(OrderTicket(),OrderLots(),Ask,slipage,0);
                  }
                  }
//-----------------------------а если цена пошла в минус------------------------------------------------------------------                
                  if(minusbuy<=-koredor)
                  {
                  Comment("Ордеров -",order);
                  double Lot=OrderLots();
                  OrderSend(Symbol(),OP_SELL,Lot*2,Bid,slipage,0,0,NULL,magic,0,clrRed);//открываем ордер SELL с удвоенным лотом----
                  }
                  }
   }}}}

 
Alexandr Nevadovschi:

Buona sera, per favore aiutatemi con l'EA che ho scritto, se si può chiamare così.

In generale, l'EA fa quello che mi aspettavo che facesse. Ma c'è uno strano inconveniente.

1) In alcuni casi, invece di ordini pendenti apre prima una posizione Sell con 0,02 lotti. Anche se secondo lo script non dovrebbe. (errore da qualche parte). Non riesco a capire a cosa sia legato, a volte tutto va bene e a volte il primo apre un Sell.

Per favore aiutatemi con questo errore. Voglio dare alla mia EA alcuni commenti generali sui miei scritti e sugli errori. Ho realizzato il mio primo Expert Advisor, quindi vi prego di giudicare severamente.


In primo luogo utilizzare lo styler (Ctrl +,) e correggere tutti i commenti che il compilatore, ci sono molti.

Poi, questo:

                  double minusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                  double plusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                   if(Digits==3)
                   {
                    minusbuy=minusbuy*100;
                    plusbuy=plusbuy*100;
                   }
                   if(Digits==5)
                   {
                   minusbuy=minusbuy*10000;
                   plusbuy=plusbuy*10000;
                   }

è facilmente e senza sforzo cambiato in questo:

                  double minusbuy=NormalizeDouble((Ask-OpenPrice)/_Point,Digits);
                  double plusbuy=minusbuy;

Allo stesso modo e sopra il codice.

Anche se non è chiaro perché l'Ask conta sia per gli acquisti che per le vendite, e i calcoli sono fatti PRIMA che il tipo di ordine sia definito. E OpenPrice è in qualche modo troppo lontano per essere rilevato diversi cicli prima.

 
Vitalie Postolache:


Per prima cosa, usate lo styler (Ctrl+,) e correggete tutte le osservazioni fatte dal compilatore, ce ne sono molte.

Poi, questo:

                  double minusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                  double plusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                   if(Digits==3)
                   {
                    minusbuy=minusbuy*100;
                    plusbuy=plusbuy*100;
                   }
                   if(Digits==5)
                   {
                   minusbuy=minusbuy*10000;
                   plusbuy=plusbuy*10000;
                   }

cambia facilmente e senza sforzo in questo:

                  double minusbuy=NormalizeDouble((Ask-OpenPrice)/_Point,Digits);
                  double plusbuy=minusbuy;

Allo stesso modo e sopra per codice.

Anche se non è chiaro perché l'Ask conta sia per gli acquisti che per le vendite, e i calcoli sono fatti PRIMA che il tipo di ordine sia definito. OpenPrice è anche in qualche modo troppo determinato e anche qualche ciclo prima.


Grazie, cercherò di risolvere il problema.
 

Saluti. Puoi dirmi perché nei test dice "impossibile aprire il file 'E:-MT4-1\Alpari Limited MT4\MQL4\indicators/ Indicator parameters WmiFor.ex4' [2]"?

C'è un indicatore, funziona. https://www.mql5.com/ru/code/10394

#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern string WmiFor             = "Параметры индикатора WmiFor";
extern bool IsTopCorner = true; // Информационный блок в верхнем углу?
extern int Offset = 1; // Смещение исходного образца в барах (для проверки надежности прогноза) [1..]
extern bool IsOffsetStartFixed = true; // Фиксировано ли начало образца
extern bool IsOffsetEndFixed = false; // Фиксирован ли конец образца
extern int PastBars = 24; // Размер образца в барах, который ищется на истории [3..]
extern int ForecastBars = 24; // На сколько баров вперед делать прогноз [1..]
extern int MaxAlts = 5; // Искать указанное кол-во лучших образцов [1..100]
extern bool ShowCloud = true; // Показывать ли облако
extern bool ShowBestPattern = true; // Показывать ли максимально близкий образец
extern bool IsExactTime = true; // Должно ли совпадать время образцов (для учета эффекта сессий)
extern datetime MinDate = D'01.01.2001'; // Минимальная дата образца
extern int PeriodMA = 2; // Периуд сглаженной средней
extern double ScalePercents = 90.0; // Рассматривать только образцы с этим минимальным процентом совпадения
extern color IndicatorCloudColor = Sienna; // Цвет облака похожих вариантов
extern color IndicatorBestPatternColor = DodgerBlue; // Цвет самого похожего образца
extern color IndicatorVLinesColor = Sienna; // Цвет вертикальных линий-границ образца
extern color IndicatorTextColor = MediumBlue; // Цвет текста инф.блока
extern color IndicatorTextWarningColor = Tomato; // Цвет предупреждений в тестовом инф.блоке
extern int XCorner = 5; // Отступ инф.блока индикатора от правой границы графика
extern int YCorner = 5; // Отступ инф.блока индикатора от верхней границы графика
extern string FontName = "Arial"; // Шрифт тестового инф.блока
extern int FontSize = 7; // Размер шрифта тестового инф.блока

double Index0, Index1, Index2, Index3, Index4, Index5;

void OnTick()
  {

Index0 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 0, 3);

Index1 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 1, 3);

Index2 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 2, 3);

Index3 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 3, 3);

Index4 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 4, 3);

Index5 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 5, 3);

Comment ( "0==", DoubleToString(Index0,Digits), "     1==", DoubleToString(Index1,Digits),  "      2==", DoubleToString(Index2,Digits),
"     3==", DoubleToString(Index3,Digits),"     4==", DoubleToString (Index4, Digits), "     5==", DoubleToString (Index5, Digits));
  
  }
//+------------------------------------------------------------------+


 
Andrey Sokolov:

Saluti. Puoi dirmi perché nei test dice "impossibile aprire il file 'E:-MT4-1\Alpari Limited MT4\MQL4\indicators/ Indicator parameters WmiFor.ex4' [2]"?

C'è un indicatore, funziona. https://www.mql5.com/ru/code/10394

#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern string WmiFor             = "Параметры индикатора WmiFor";

void OnTick()
  {

Index5 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 5, 3);

Comment ( "0==", DoubleToString(Index0,Digits), "     1==", DoubleToString(Index1,Digits),  "      2==", DoubleToString(Index2,Digits),
"     3==", DoubleToString(Index3,Digits),"     4==", DoubleToString (Index4, Digits), "     5==", DoubleToString (Index5, Digits));
  
  }
//+------------------------------------------------------------------+
Leggete nella documentazione su"iCustom", e come accedere correttamente all 'indicatore
 
Vitaly Muzichenko:
Leggete la documentazione su"iCustom", e come accedere correttamente all'indicatore


Grazie.

Ho dimenticato le virgolette, idiota.

 

Buon pomeriggio!

Aiutami a scoprire cosa c'è che non va. Ho bisogno di emettere il prezzo quando la linea è attraversata da una barra. Ho scritto il codice.

int start() {

double pr=ObjectGetValueByShift("line",0);

Allarme (pr);

return(0);}

line è il nome della linea.

Questo codice mostra sempre "0". Cosa c'è che non va?

 
Kot:

Buon pomeriggio!

Aiutami a scoprire cosa c'è che non va. Ho bisogno di emettere il prezzo quando la linea è attraversata da una barra. Ho scritto il codice.

int start() {

double pr=ObjectGetValueByShift("line",0);

Allarme (pr);

return(0);}

line è il nome della linea.

Questo codice mostra sempre "0". Cosa c'è che non va?


Aveteuna linea di tendenza?

E visivamente va sopra (sotto) la barra 0, no, controlla la casella nelle proprietà, raggio.

 

Buon pomeriggio a tutti!

Domanda, su insta quando si cerca di inviare un ordine, dice che gli stop sono sbagliati.

Ecco la linea stessa:

OrderSend(Symbol(),OP_BUYSTOP,Lots,HiP,3,0,0,NULL,111,0,clrBlue);

Stop Loss e Take Points hanno 0. Se imposto un numero in Stop Loss, tutto è normale.

Non ho bisogno di Stop Loss. Cosa devo fare?