[ARCHIVO] Cualquier pregunta de novato, para no saturar el foro. Profesionales, no pasen de largo. En ninguna parte sin ti - 3. - página 284

 
ZZZEROXXX:


UP. el principio de convertir un EA en un script en pocas palabras sería apreciado

Es más simple que esto.
 
ZZZEROXXX:


UP. el principio de convertir un EA en un script en pocas palabras sería apreciado


No lo sé exactamente, pero parece que si mueves el EA a scripts, funcionará como un script.
 
ZZZEROXXX:


UP. Me gustaría conocer el principio de convertir un EA en un script en pocas palabras

¿Y qué hará el guión?

Por lo general, se desconecta el terminal, se escribe un archivo CSV de un marco temporal no estándar y luego se carga en lugar de cualquier símbolo y período, en este período y se prueba. Es cierto que a precios de apertura, pero no hay muchas más opciones.

 
splxgf:

¿Y qué hará el guión?

Por lo general, se desconecta el terminal, se escribe un archivo CSV de un marco temporal no estándar y luego se carga en lugar de cualquier símbolo y período, este es el período en el que se realiza la prueba. Es cierto que a precios de apertura, pero no hay muchas más opciones.


Gracias a todos los que han respondido. Me gusta la variante con la sustitución de TF, la probaré. Inicialmente estaba planeando abrir un standalone TF no estándar y descargar las operaciones en un archivo usando un script de Asesor Experto.
 

Lo que es:

    1. Reducción máxima, % - porcentaje de reducción máxima;

?

Se puede especificar dicho parámetro en el optimizador de estrategias, pero no está claro qué significa...

1) ¿Es la máxima disminución del saldo respecto al depósito inicial?

2) ¿Diferencia máxima entre el máximo y el mínimo de la renta variable que se suceden?

3) ¿La diferencia entre el margen mínimo y el máximo?

Se me ocurren muchas otras variantes.

Por favor, explique el significado exacto de ("Disposición máxima, %")

 
snail09:

Comenzó a entender su código. Estoy sorprendido. Lo que has adjuntado no puede funcionar. Se puede ver que está hecho de trozos, pero al menos los soportes son correctos.

El código tiene dos partes. Éste es mi experto. Por favor, échale un vistazo.

//+------------------------------------------------------------------+
//|                                                      rusa_v4.mq4 |
//|                        
//|                      |
//+------------------------------------------------------------------+
#property copyright ""
#property link      "https://www.mql5.com/ru/users/avoitenko"

//--- Внешние переменные 
extern string General = "=== General settings ===";
extern int TakeProfit_Buy  =  260; // Тейк профит для Buy
extern int StopLoss_Buy    =  120; // Стоп лосс для Buy
extern int TakeProfit_Sell =  140; // Тейк профит для Sell
extern int StopLoss_Sell   =  110; // Стоп лосс для Sell
extern int TrailingStop    =   0; // Трейлинг стоп
extern double Lots         = 0.02; // Лот 
extern int Slippage        =   10; // Проскальзывание
extern int BarsShift       =    0; // Смещение в барах для анализа сигнала

extern int Magic           = 555; // Уникальный номер советника


extern string MA1 = "=== #1 Moving Average settings ===";
extern int MA1_period      = 15; // Период скользящей средней 
extern int MA1_shift       = 0;  // Смещение скользящей средней 
extern int MA1_method      = 1;  // MODE_SMA=0,MODE_EMA=1,MODE_SMMA=2,MODE_LWMA =3;
extern int MA1_price       = 2;  // PRICE_CLOSE=0,PRICE_OPEN=1,PRICE_HIGH=2,PRICE_LOW=3,PRICE_MEDIAN=4,PRICE_TYPICAL=5,PRICE_WEIGHTED=6;

extern string MA2 = "=== #2 Moving Average settings ===";
extern int MA2_period      = 20; 
extern int MA2_shift       = 0; 
extern int MA2_method      = 0; 
extern int MA2_price       = 0;

extern string MA3 = "=== #3 Moving Average settings ===";
extern int MA3_period      = 70;
extern int MA3_shift       = 8; 
extern int MA3_method      = 2;
extern int MA3_price       = 3;

extern string RSI = "=== RSI settings ===";
extern int RSI_period      = 14; // Период RSI
extern int RSI_price       =  3; // PRICE_CLOSE=0,PRICE_OPEN=1,PRICE_HIGH=2,PRICE_LOW=3,PRICE_MEDIAN=4,PRICE_TYPICAL=5,PRICE_WEIGHTED=6;

extern int macd_fast             = 12;
extern int macd_slow             = 15;
extern int macd_signal                  = 1;
extern int macd_price                   = 3; // 0-PRICE_CLOSE, 1-PRICE_OPEN, 2-PRICE_HIGH, 3-PRICE_LOW, 4-PRICE_MEDIAN, 5-PRICE_TYPICAL, 6-PRICE_WEIGHTED
extern int macd_open             = 7;
//--- Глобальные переменные
double lot;             // лот

double ma10,ma20,ma30,ma11,ma21,ma31,rsi, macd;

int stop_loss_buy;      // стоп лосс
int take_profit_buy;    // тейк профит

int stop_loss_sell;     // стоп лосс
int take_profit_sell;   // тейк профит

int slippage;           // проскальзывание
int trailing_stop;      // трейлинг стоп

int min_level;          // минимальный отступ от цены для установки SL / TP

int bars_shift;         // смещение в барах для торговых сигналов
int bars_count;         // минимальное число баров для работы
datetime candle_time = 0;   

bool sell_open = false; // флаг открытия позиции sell
bool buy_open  = false; // флаг открытия позиции buy

bool new_bar_buy = false;  // флаг нового бара
bool new_bar_sell = false; // флаг нового бара

//+------------------------------------------------------------------+
int init()
//+------------------------------------------------------------------+
  {
   //--- проверка правильности ввода данных
   bars_shift = BarsShift;
   if(bars_shift < 0)bars_shift = 0;
   
   bars_count = MathMax4(MA1_period, MA2_period, MA3_period, RSI_period) + bars_shift;

   //--- инициализация переменных
   stop_loss_buy     = StopLoss_Buy;
   take_profit_buy   = TakeProfit_Buy;
   stop_loss_sell    = StopLoss_Sell;
   take_profit_sell  = TakeProfit_Sell;
   slippage          = Slippage;
   trailing_stop     = TrailingStop;

   //--- Если цена состоит из 3-x / 5-и цифр
   if((Digits==3) || (Digits==5))
    {
      stop_loss_buy     = stop_loss_buy * 10;
      take_profit_buy   = take_profit_buy * 10;
      stop_loss_sell    = stop_loss_sell * 10;
      take_profit_sell  = take_profit_sell * 10;
      slippage          = slippage * 10;
      trailing_stop     = trailing_stop * 10;
    }

   Print("Советник начал свою работу");
   return(0);
  }
bool macd_up(int timeframe, int fast, int slow, int signal, int price, int num) {
 double y;
 double x = iMACD(NULL,timeframe,fast,slow,signal,price,MODE_MAIN,0)*100000;
 for (int i=1; i<num; i++) {
  y = iMACD(NULL,timeframe,fast,slow,signal,price,MODE_MAIN,i)*100000;
  if (y > x) return(false);
  else x = y;
 }
 return(true);
}
 
//+------------------------------------------------------------------+
bool macd_down(int timeframe, int fast, int slow, int signal, int price, int num) {
 double y;
 double x = iMACD(NULL,timeframe,fast,slow,signal,price,MODE_MAIN,0)*100000;
 for (int i=1; i<num; i++) {
  y = iMACD(NULL,timeframe,fast,slow,signal,price,MODE_MAIN,i)*100000;
  if (y < x) return(false);
  else x = y;
 }
 return(true);
}
//+------------------------------------------------------------------+

int deinit()
//+------------------------------------------------------------------+
  {
   Print("Советник завершил свою работу");
   return(0);
  }

//+------------------------------------------------------------------+
int start()
//+------------------------------------------------------------------+
  {
   
   //--- Разрешение на открытие позиций - каждую свечу
   if(candle_time != Time[0])
   {
      candle_time  = Time[0];  
      new_bar_buy  = true;
      new_bar_sell = true;
   }
   
   if (Bars < bars_count){Print("Мало данных для работы"); return(0);}

   //--- Получение значений индикатора iMA
   ma10 = iMA ( Symbol(), Period(), MA1_period, MA1_shift, MA1_method, MA1_price, bars_shift);
   ma20 = iMA ( Symbol(), Period(), MA2_period, MA2_shift, MA2_method, MA2_price, bars_shift);
   ma30 = iMA ( Symbol(), Period(), MA3_period, MA3_shift, MA3_method, MA3_price, bars_shift);

   ma11 = iMA ( Symbol(), Period(), MA1_period, MA1_shift, MA1_method, MA1_price, bars_shift+1);
   ma21 = iMA ( Symbol(), Period(), MA2_period, MA2_shift, MA2_method, MA2_price, bars_shift+1);
   
   rsi = iRSI ( Symbol(), Period(), RSI_period, RSI_price, bars_shift);
  macd = iMACD(NULL,0,macd_fast,macd_slow,macd_signal,macd_price,MODE_MAIN,0);
   
  
   {
      if (macd <0)
        {
        if (macd_down(0,macd_fast,macd_slow,macd_signal,macd_price,macd_open)) return(true);
       
      {
         //--- Условие для продажи
         if(ma11 < ma21 && ma10 > ma20 && ma30 > ma10 && rsi<50  && new_bar_sell)
         {
            sell_open=true;
            new_bar_sell = false;
         }
          }
           }
            }
      {
        
      
      if (macd >  0)
       {
      if (macd_up(0,macd_fast,macd_slow,macd_signal,macd_price,macd_open)) return(true);
  {
         //--- Условие для продажи
          if(ma11 > ma21 && ma10 < ma20 && ma30 < ma10 && rsi>50 && new_bar_buy)
         {
            buy_open=true;
            new_bar_buy = false;
          }
      }
   }
    }
 {
        if (macd >  0)
       {
      if (macd_up(0,macd_fast,macd_slow,macd_signal,macd_price,macd_open)) return(true);
   {
      //--- Условие для покупки
      if(ma11 < ma21 && ma10 > ma20 && ma30 > ma10 && rsi>50  && new_bar_buy)
      {
         buy_open=true;
         new_bar_buy = false;
      }
   }
     }
     {
      if (macd < 0)
        {
        if (macd_down(0,macd_fast,macd_slow,macd_signal,macd_price,macd_open)) return(true);
     { //--- Условие для продажи
      if(ma11 > ma21 && ma10 < ma20 && ma30 < ma10 && rsi<50  && new_bar_sell)
      {
         sell_open=true;
         new_bar_sell = false;
      }
   }
}
 }  
 }  
    //--- выставление рыночных ордеров
  
   if(IsTradeAllowed())
   {
      Trade_BUY();
      Trade_SELL();      
   }

   return(0);
  }


 
rusa:

segunda parte

//+------------------------------------------------------------------+
void Trade_BUY() 
//+------------------------------------------------------------------+
{ 

   for ( int i = 0; i < OrdersTotal(); i++ ) 
   {
      
      if ( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
      {
         
         if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != Magic)) continue; //не наш ордер
         
         if ( OrderType() == OP_BUY)  // если ордер OP_BUY
         {
          
            min_level = MarketInfo( Symbol(), MODE_STOPLEVEL );
            
            //--- проверка на работу трейлинг стопа
            if (trailing_stop !=0.0 && Ask > NormalizeDouble(OrderStopLoss() + (stop_loss_buy + MathMax(min_level, trailing_stop)) * Point, Digits) && OrderProfit() > 0) 
            {

               if ( OrderModify ( OrderTicket(), OrderOpenPrice(), 
                  NormalizeDouble (OrderStopLoss() + MathMax(min_level, trailing_stop) * Point, Digits),
                  OrderTakeProfit(),  0, CLR_NONE))
               {
                  Print("Сработал трейлинг стоп для Buy");
               }
               else 
               {
                  Print ("Ошибка модификации ордера #", GetLastError());
               }           

               RefreshRates();
               Sleep(3000);
            } //end modify 

         }// end BUY
      
      }//end OrderSelect    
      else
      {
         Print( "OrderSelect ошибка #",  GetLastError() ); 
         Sleep(3000);
         RefreshRates();   
         return;
      } 
   
   }// end for
 
    
   //--- Открываем ордер если есть сигнал
   while (buy_open) 
   { 

      //--- нормализация лота
      lot = Normalize_Lot(Lots);
   
      //--- проверка на наличие свободной маржи
      if( AccountFreeMarginCheck(Symbol(),OP_BUY, lot) <= 0 || GetLastError() == 134 )
      {
         Print("Недостаточно свободной маржи для открытия ордера");
         buy_open = false;
         break;
      }
   
      min_level = MarketInfo( Symbol(), MODE_STOPLEVEL );
      
      if ( OrderSend( Symbol(), OP_BUY, lot, NormalizeDouble(Ask, Digits), slippage, 
            NormalizeDouble(Bid - MathMax(stop_loss_buy, min_level) * Point, Digits),
            NormalizeDouble(Bid + MathMax(take_profit_buy,min_level) * Point, Digits),
            DoubleToStr(Magic, 0), Magic, 0, Blue) > 0 )
      {
            PlaySound("Wait.wav");
            buy_open = false; // ордер открыт
            break;
      }
      
      else
      {
            int Error = GetLastError();                 // Не получилось :(
         
            switch(Error)                             // Преодолимые ошибки
            {
            case 138:Alert("Ошибка: ",Error," Новые цены.");
               RefreshRates();                     
               continue;                          
            case 135:Alert("Ошибка: ",Error," Цена изменилась.");
               RefreshRates();                    
               continue;                          
            case 136:Alert("Нет цен.");
               while(RefreshRates() == false)     
               Sleep(500);                        
               continue;                          
            case 146:Alert("Подсистема торговли занята.");
               Sleep(500);                        
               RefreshRates();                    
               continue; 
            default: Alert("Возникла ошибка ", Error," Выход из подпрограммы."); // Другие варианты ошибок
               
            }// end switch
         
      }// end else
      
      break;
   
   }// end while
   
}// end Trade_BUY
       
//+------------------------------------------------------------------+
void Trade_SELL() 
//+------------------------------------------------------------------+
{

   
   for ( int i = 0; i < OrdersTotal(); i++ ) 
   {
      
      if ( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
      {
         
         if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != Magic)) continue; //не наш ордер
         
         if ( OrderType() == OP_SELL) //если ордер OP_SELL
         {
            min_level = MarketInfo( Symbol(), MODE_STOPLEVEL );

            //--- проверка на работу трейлинг стопа
            if (trailing_stop !=0.0 && Bid < NormalizeDouble(OrderStopLoss() - (stop_loss_sell + MathMax(min_level, trailing_stop)) * Point, Digits)&&OrderProfit() > 0) 
            {   
               if ( OrderModify ( OrderTicket(), OrderOpenPrice(), 
                  NormalizeDouble (OrderStopLoss() - MathMax(min_level, trailing_stop) * Point, Digits),
                  OrderTakeProfit(), 0, CLR_NONE))
               {
                  Print("Сработал трейлинг стоп для Sell");
               }
               else 
               {
                  Print ( "Ошибка модификации ордера #", GetLastError());
               }           

               RefreshRates();
               Sleep(3000);
           
            }          
         }// end BUY
      
      }//end OrderSelect    
      else
      {
         Print( "OrderSelect ошибка #",  GetLastError() ); 
         Sleep(3000);
         RefreshRates();   
         return;
      } 
   
   }// end for
 
    
   //--- Открываем ордер если есть сигнал
   while (sell_open) 
   { 

      //--- нормализация лота
      lot = Normalize_Lot(Lots);
   
      //--- проверка на наличие свободной маржи
      if( AccountFreeMarginCheck(Symbol(),OP_SELL, lot) <= 0 || GetLastError() == 134 )
      {
         Print("Недостаточно свободной маржи для открытия ордера");
         sell_open = false;
         break;
      }
   
      min_level = MarketInfo( Symbol(), MODE_STOPLEVEL );
      
      if ( OrderSend( Symbol(), OP_SELL, lot, NormalizeDouble(Bid, Digits), slippage, 
            NormalizeDouble(Ask + MathMax(stop_loss_sell, min_level) * Point, Digits),
            NormalizeDouble(Ask - MathMax(take_profit_sell, min_level) * Point, Digits),
            DoubleToStr(Magic, 0), Magic, 0, Red) > 0 )
      {
            PlaySound("Wait.wav");
            sell_open = false; // ордер открыт
            break;
      }
      
      else
      {
            int Error = GetLastError();                 // Не получилось :(
         
            switch(Error)                             // Преодолимые ошибки
            {
            case 138:Alert("Ошибка: ",Error," Новые цены.");
               RefreshRates();                     
               continue;                          
            case 135:Alert("Ошибка: ",Error," Цена изменилась.");
               RefreshRates();                    
               continue;                          
            case 136:Alert("Нет цен.");
               while(RefreshRates() == false)     
               Sleep(500);                        
               continue;                          
            case 146:Alert("Подсистема торговли занята.");
               Sleep(500);                        
               RefreshRates();                    
               continue; 
            default: Alert("Возникла ошибка ", Error," Выход из подпрограммы."); // Другие варианты ошибок
               
            }// end switch
         
      }// end else
      
      break;
   
   }// end while
   
}// end Trade_SELL


//+------------------------------------------------------------------+
double Normalize_Lot(double lot)// Проверка на допустимое значение лота
//+------------------------------------------------------------------+
{
   double lot_min  = MarketInfo(Symbol(), MODE_MINLOT);
   double lot_max  = MarketInfo(Symbol(), MODE_MAXLOT);
   double lot_step = MarketInfo(Symbol(), MODE_LOTSTEP);
   
   if ( lot <= lot_min ) lot = lot_min;      // минимальный
   else if ( lot >= lot_max ) lot = lot_max; // максимальный
   else lot = MathFloor( lot / lot_step ) * lot_step ; // округление до ближайшего меньшего
   
   return(lot);
}

//+------------------------------------------------------------------+
int MathMax4(int i1,int i2,int i3,int i4)// Возврат максимального значения
//+------------------------------------------------------------------+
{
   int imax=i1;
   if(i2>imax)imax=i2;
   if(i3>imax)imax=i3;
   if(i4>imax)imax=i4;
   return(imax);
}
 
¿Pueden decirme cómo eliminar una orden pendiente si una de las órdenes pendientes se ha activado? Se establecen un total de dos órdenes pendientes.
 
ArgentumZ:

¡Hola!

Ejecutando el EA en el probador. El servidor tiene cuatro dígitos. Al colocar la orden de compra o venta en el registro dice

2011.10.23 15:27:26 2010.12.16 06:16 test_sovetnik GBPUSD,H1: open #1 buy 0.10 GBPUSD at 1.5551 sl: 1.4551 tp: 1.5586 ok

¡Pero abre a 1.55512 ! A los cinco dígitos. Entonces las órdenes pendientes se colocan a cuatro dígitos y se activan a cuatro dígitos también. Pero OP_SELL y OP_BUY se abren sólo con cinco dígitos.

Hago NormalizeDouble(Ask,Digits);

Nada funciona. Por favor, aconséjeme cómo resolver este problema.

Por supuesto, puedes ignorar el último dígito. El error no se produce, pero en aras de la pureza del experimento, necesito que todas mis operaciones se realicen con cuatro dígitos.


Lo más probable es que tu MT4 y tu servidor tengan una cotización de cinco dígitos, como el mío. Por lo tanto, todo debe multiplicarse por 10, ya que Dígitos = 5.
 
Parn25:
¿Cómo puedo eliminar una orden pendiente si una de ellas se dispara? Hay dos órdenes pendientes en total.

Puedes hacerlo manualmente. Haga clic con el botón derecho y luego... :)

Puede aplicar un script o un Asesor Experto. ¿Qué prefiere? XD

Razón de la queja: