Cualquier pregunta de novato, para no saturar el foro. Profesionales, no pasen de largo. En ninguna parte sin ti - 6. - página 287

 
artmedia70:

En esta situación hay que añadir al código. Cree una variable externa, por ejemplo, Appled_Price.

Y cambias todos los PRICE_CLOSE en el código por Appled_Price.


Ah, sí, lo siento, me refería a las nuevas construcciones, y hay un código un poco inusual.

Esa es la cuestión, el código no tiene precio de forma libre, todo está en arrays, simplemente no se puede cambiar, lo he probado (((

Y si funcionara, ¿cómo hacer una selección de una lista desplegable (como en la imagen de mi pregunta)?


//+------------------------------------------------------------------+
//|                                       Custom Moving Averages.mq4 |
//|                   Copyright 2005-2013, MetaQuotes Software Corp. |
//|                                              https://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright   "2005-2013, MetaQuotes Software Corp."
#property link        "https://www.mql4.com"
#property description "Moving Average"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Red
//--- indicator parameters
input int            InpMAPeriod=13;        // Period
input int            InpMAShift=0;          // Shift
input ENUM_MA_METHOD InpMAMethod=MODE_SMA;  // Method
//--- indicator buffer
double ExtLineBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit(void)
  {
   string short_name;
   int    draw_begin=InpMAPeriod-1;
//--- indicator short name
   switch(InpMAMethod)
     {
      case MODE_SMA  : short_name="SMA(";                break;
      case MODE_EMA  : short_name="EMA(";  draw_begin=0; break;
      case MODE_SMMA : short_name="SMMA(";               break;
      case MODE_LWMA : short_name="LWMA(";               break;
      default :        return(INIT_FAILED);
     }
   IndicatorShortName(short_name+string(InpMAPeriod)+")");
   IndicatorDigits(Digits);
//--- check for input
   if(InpMAPeriod<2)
      return(INIT_FAILED);
//--- drawing settings
   SetIndexStyle(0,DRAW_LINE);
   SetIndexShift(0,InpMAShift);
   SetIndexDrawBegin(0,draw_begin);
//--- indicator buffers mapping
   SetIndexBuffer(0,ExtLineBuffer);
//--- initialization done
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//|  Moving Average                                                  |
//+------------------------------------------------------------------+
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[])
  {
//--- check for bars count
   if(rates_total<InpMAPeriod-1 || InpMAPeriod<2)
      return(0);
//--- counting from 0 to rates_total
   ArraySetAsSeries(ExtLineBuffer,false);
   ArraySetAsSeries(close,false);
//--- first calculation or number of bars was changed
   if(prev_calculated==0)
      ArrayInitialize(ExtLineBuffer,0);
//--- calculation
   switch(InpMAMethod)
     {
      case MODE_EMA:  CalculateEMA(rates_total,prev_calculated,close);        break;
      case MODE_LWMA: CalculateLWMA(rates_total,prev_calculated,close);       break;
      case MODE_SMMA: CalculateSmoothedMA(rates_total,prev_calculated,close); break;
      case MODE_SMA:  CalculateSimpleMA(rates_total,prev_calculated,close);   break;
     }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
//|   simple moving average                                          |
//+------------------------------------------------------------------+
void CalculateSimpleMA(int rates_total,int prev_calculated,const double &price[])
  {
   int i,limit;
//--- first calculation or number of bars was changed
   if(prev_calculated==0)
   
     {
      limit=InpMAPeriod;
      //--- calculate first visible value
      double firstValue=0;
      for(i=0; i<limit; i++)
         firstValue+=price[i];
      firstValue/=InpMAPeriod;
      ExtLineBuffer[limit-1]=firstValue;
     }
   else
      limit=prev_calculated-1;
//--- main loop
   for(i=limit; i<rates_total && !IsStopped(); i++)
      ExtLineBuffer[i]=ExtLineBuffer[i-1]+(price[i]-price[i-InpMAPeriod])/InpMAPeriod;
//---
  }
//+------------------------------------------------------------------+
//|  exponential moving average                                      |
//+------------------------------------------------------------------+
void CalculateEMA(int rates_total,int prev_calculated,const double &price[])
  {
   int    i,limit;
   double SmoothFactor=2.0/(1.0+InpMAPeriod);
//--- first calculation or number of bars was changed
   if(prev_calculated==0)
     {
      limit=InpMAPeriod;
      ExtLineBuffer[0]=price[0];
      for(i=1; i<limit; i++)
         ExtLineBuffer[i]=price[i]*SmoothFactor+ExtLineBuffer[i-1]*(1.0-SmoothFactor);
     }
   else
      limit=prev_calculated-1;
//--- main loop
   for(i=limit; i<rates_total && !IsStopped(); i++)
      ExtLineBuffer[i]=price[i]*SmoothFactor+ExtLineBuffer[i-1]*(1.0-SmoothFactor);
//---
  }
//+------------------------------------------------------------------+
//|  linear weighted moving average                                  |
//+------------------------------------------------------------------+
void CalculateLWMA(int rates_total,int prev_calculated,const double &price[])
  {
   int        i,limit;
   static int weightsum;
   double     sum;
//--- first calculation or number of bars was changed
   if(prev_calculated==0)
     {
      weightsum=0;
      limit=InpMAPeriod;
      //--- calculate first visible value
      double firstValue=0;
      for(i=0;i<limit;i++)
        {
         int k=i-1;
         weightsum+=k;
         firstValue+=k*price[i];
        }
      firstValue/=(double)weightsum;
      ExtLineBuffer[limit-1]=firstValue;
     }
   else
      limit=prev_calculated-1;
//--- main loop
   for(i=limit; i<rates_total && !IsStopped(); i++)
     {
      sum=0;
      for(int j=0;j<InpMAPeriod;j++)
         sum+=(InpMAPeriod-j)*price[i-j];
      ExtLineBuffer[i]=sum/weightsum;
     }
//---
  }
//+------------------------------------------------------------------+
//|  smoothed moving average                                         |
//+------------------------------------------------------------------+
void CalculateSmoothedMA(int rates_total,int prev_calculated,const double &price[])
  {
   int i,limit;
//--- first calculation or number of bars was changed
   if(prev_calculated==0)
     {
      limit=InpMAPeriod;
      double firstValue=0;
      for(i=0; i<limit; i++)
         firstValue+=price[i];
      firstValue/=InpMAPeriod;
      ExtLineBuffer[limit-1]=firstValue;
     }
   else
      limit=prev_calculated-1;
//--- main loop
   for(i=limit; i<rates_total && !IsStopped(); i++)
      ExtLineBuffer[i]=(ExtLineBuffer[i-1]*(InpMAPeriod-1)+price[i])/InpMAPeriod;
//---
  }
//+------------------------------------------------------------------+
 
evillive:

Esa es la cuestión, no hay precio libre en el código, no puedes sustituirlo(((

Pruebe aquí

switch(InpMAMethod)
     {
      case MODE_EMA:  CalculateEMA(rates_total,prev_calculated,close);        break;
      case MODE_LWMA: CalculateLWMA(rates_total,prev_calculated,close);       break;
      case MODE_SMMA: CalculateSmoothedMA(rates_total,prev_calculated,close); break;
      case MODE_SMA:  CalculateSimpleMA(rates_total,prev_calculated,close);   break;
     }

cambie cerrar por abrir. Si empieza a contar por abierto, entonces indaga en esta dirección cómo cambiar este valor. Ahora no puedo ejecutar el terminal beta para mirar a través de su editor.

Cambia el valor aquí de antemano:

//--- counting from 0 to rates_total
   ArraySetAsSeries(ExtLineBuffer,false);
   ArraySetAsSeries(close,false);
//--- first calculation or number of bars was changed
 
No tiene sentido cambiar Cerrar por Abrir, habrá poco cambio. Es más fácil no molestarse con esas tonterías, sino tomar los datos de la barra formada.
 

Saludos a todos))

Escribí un EA, pero no funciona en todo)))) o no funciona correctamente. he estado hurgando, arreglando muchas cosas, pero sin embargo, el EA no funciona.

aquí se muestra un fragmento del cálculo de las decisiones de trading basadas en el indicador RSI :

//--------------------Данные------------------------------------

   int Ticket1_RSI=-1, Ticket2_RSI=-1;                    // Номера открытых ордеров
   extern double Lot=0.01;                                 // Объем лота
int RSI()                                                  // Функция RSI
   {                                                                                                             
   double T, P;
   double RSI_0, RSI_1, RSI_2;                      // Значения индикатора RSI
//------------------Значения индикатора---------------------------------------   
   RSI_0=iRSI(Symbol(), 0, 14, PRICE_CLOSE, 0);              // Получаем данные от RSI 
   RSI_1=iRSI(Symbol(), 0, 14, PRICE_CLOSE, 1);              // Получаем данные от RSI 
   RSI_2=iRSI(Symbol(), 0, 14, PRICE_CLOSE, 2);              // Получаем данные от RSI 
//------------------Условие на продажу---------------------------------   
   if (RSI_1 > RSI_0 > 70 && RSI_1 > RSI_2)         // Если индикатор превышает значение 70 и виден поворот вниз
      {                                                                                                           
      if (Ticket2_RSI > 0)                                                     // Если имеется ордер на покупку
         OrderClose(Ticket2_RSI, OrderLots(), Bid, 0, 0);                            // Закрытие ордера на покупку
      if (Ticket1_RSI <= 0)                                                    // Если ордера на продажу нет
         {
         Ticket1_RSI=OrderSend(Symbol(), OP_SELL, Lot, Bid, 2, 0, 0);        // Открытие ордера на продажу
         if (OrderSelect(Ticket1_RSI, SELECT_BY_TICKET)==true)
            {
            T=OrderOpenTime();
            P=OrderOpenPrice();
            ObjectCreate("Arrow", 22, 0, T, P);               // Создание индикатора ордера
            ObjectSet("Arrow", OBJPROP_COLOR, IndianRed);                             // Изменение цвета в мутно-красноватый
            ObjectSet("Arrow", OBJPROP_ARROWCODE, 242);                               // Направление стрелки вниз
            ObjectCreate("Text", 21, 0, T, P);                // Создание текстового объекта
            ObjectSetText("Text", "Open sell-order by RSI", 6, "Times New Roman", Navy);     // Текст, шрифт, стиль, цвет     
            }
         }
      }
//-------------------Условие на покупку--------------------------------   
   if (RSI_1 < RSI_0 < 30 &&  RSI_1 < RSI_2)         // Если индикатор ниже значения 30 и виден поворот вверх
      {
      if (Ticket1_RSI > 0)                                                     // Если имеется ордер на продажу
         OrderClose(Ticket1_RSI, OrderLots(), Ask, 0, 0);                            // Закрытие ордера на продажу
      if (Ticket2_RSI <= 0)                                                    // Если ордера на продажу нет
         {
         Ticket2_RSI=OrderSend(Symbol(), OP_BUY, Lot, Ask, 2, 0, 0);         // Открытие ордера на покупку
         if (OrderSelect(Ticket2_RSI, SELECT_BY_TICKET)==true)
            {
            T=OrderOpenTime();
            P=OrderOpenPrice();
            ObjectCreate("Arrow", 22, 0, T, P);   // Создание индикатора ордера          
            ObjectSet("Arrow", OBJPROP_COLOR, LawnGreen);                             // Изменение цвета в ярко-зеленый
            ObjectSet("Arrow", OBJPROP_ARROWCODE, 241);                               // Направление стрелки вверх
            ObjectCreate("Text", 21, 0, T, P);     // Создание текстового объекта
            ObjectSetText("Text", "Open buy-order by RSI", 6, "Times New Roman", Navy);      // Текст, шрифт, стиль, цвет
            }
         }   
      }
//--------------------------------------------------------------------   
   return;    
   } 

El caso es que el EA abre inmediatamente una orden de compra, a pesar del valor del indicador, y no quiere cerrarla. Los objetos como el texto y las flechas no aparecen.

Ayúdame a resolver esto)) solo soy nuevo en esto

 
waroder:

Saludos a todos))

Escribí un EA, pero no funciona en todo)))) o no funciona correctamente. he estado hurgando, arreglando muchas cosas, pero sin embargo, el EA no funciona.

aquí se muestra un fragmento del cálculo de las decisiones de trading basadas en el indicador RSI :

//--------------------Данные------------------------------------

El caso es que el EA abre inmediatamente una orden de compra, a pesar del valor del indicador, y no quiere cerrarla. Los objetos como el texto y las flechas no aparecen.

Ayúdame a resolver esto)) solo soy nuevo en esto


if (RSI_1 > RSI_0 && RSI_0 > 70 && RSI_1 > RSI_2)         // Если индикатор превышает значение 70 и виден поворот вниз
 
Vinin:



Entonces, ¿hay que escribir cada desigualdad por separado en las condiciones? Si se generaliza de alguna manera, se verá como un error? Entonces, ¿por qué el programa dice que no hay errores al compilar?
 
waroder:

Entonces, ¿hay que escribir cada desigualdad por separado en las condiciones? Si se generaliza de alguna manera, se percibirá como un error? Entonces, ¿por qué el programa dice que no hay error al compilar?

No hay ningún error, simplemente no se obtiene el resultado esperado.
 
hoz:

...¿Cómo se busca la causa en una situación como ésta?


Lo encontré por casualidad. Hay que simplificar las cosas. Comentar todo, descomentar la primera importación, compilar, llamar a las funciones, etc.


 
Integer:
No tiene sentido cambiar Cerrar por Abrir, habrá poco cambio. Es más fácil no molestarse con esas tonterías, sino tomar los datos de la barra formada.
Estoy de acuerdo, pero como había una pregunta...
 
Vinin:

No hay ningún error, simplemente no se obtiene el resultado que se esperaba.


Me di cuenta)) una orden se abrió inmediatamente sin más cambios, porque tuve que escribir NULL en lugar de Symbol() en la línea:

   RSI_1=iRSI(Symbol(), 0, 14, PRICE_CLOSE, 1);              // Получаем данные от RSI 

Tienes que escribir NULL en lugar de Symbol(), porque hay una discrepancia en los tipos de variables. Debido a esto, vi RSI como un valor nulo, así que inmediatamente lo abrí, porque la condición funcionó.

Ahora lo he arreglado y todo está bien.

El único problema es que los objetos sólo se crean una vez en la primera operación.