[ARCHIVE] Toute question de débutant, afin de ne pas encombrer le forum. Professionnels, ne passez pas à côté. Nulle part sans toi - 3. - page 284

 
ZZZEROXXX:


UP. le principe de la conversion d'un EA en script en quelques mots serait apprécié.

C'est plus simple comme ça.
 
ZZZEROXXX:


UP. le principe de la conversion d'un EA en script en quelques mots serait apprécié.


Je ne sais pas exactement, mais il semble que si vous déplacez l'EA vers les scripts, il fonctionnera comme un script.
 
ZZZEROXXX:


UP. J'aimerais connaître le principe de la conversion d'un EA en script en quelques mots.

Et que va faire le scénario ?

Habituellement, le terminal est débranché, un fichier CSV est écrit à partir d'une période non standard et ensuite chargé à la place de n'importe quel symbole et période, sur cette période et testé. Vrai au prix d'ouverture, mais il n'y a pas beaucoup d'autres options.

 
splxgf:

Et que va faire le scénario ?

Habituellement, le terminal est débranché, un fichier CSV est écrit à partir d'une période non standard et ensuite chargé à la place d'un symbole et d'une période, c'est la période sur laquelle les tests sont effectués. Vrai au prix d'ouverture, mais il n'y a pas beaucoup d'autres options.


Merci à tous ceux qui ont répondu. J'aime la variante avec la substitution TF, je vais l'essayer. J'avais initialement prévu d'ouvrir un standalone TF non standard et de décharger les transactions dans un fichier en utilisant un script Expert Advisor.
 

Ce qui est :

    1. Maximum drawdown, % - pourcentage maximum de drawdown ;

?

Vous pouvez spécifier un tel paramètre dans l'optimiseur de stratégie, mais sa signification n'est pas claire...

1) S'agit-il de la diminution maximale du solde par rapport au dépôt initial ?

2) Différence maximale entre le maximum et le minimum de l'équité qui se suivent ?

3) La différence entre la marge minimale et la marge maximale ?

De nombreuses autres variantes me viennent à l'esprit.

Veuillez expliquer la signification exacte de (Maximum drawdown, %)

 
snail09:

J'ai commencé à comprendre votre code. Je suis surpris. Ce que vous avez joint ne peut pas fonctionner. Vous pouvez voir qu'elle est composée de morceaux, mais au moins les supports sont corrects.

Le code est en deux parties. C'est mon expert. Veuillez y jeter un coup d'œil.

//+------------------------------------------------------------------+
//|                                                      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:

deuxième partie

//+------------------------------------------------------------------+
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);
}
 
Pouvez-vous me dire comment supprimer un ordre en attente si l'un des ordres en attente s'est déclenché ? Un total de deux ordres en attente est fixé.
 
ArgentumZ:

Bonjour !

Exécution de l'EA sur le testeur. Le serveur est composé de quatre chiffres. Lorsque l'on passe un ordre d'achat ou de vente dans le journal, on peut lire ceci

2011.10.23 15:27:26 2010.12.16 06:16 test_sovetnik GBPUSD,H1 : ouvert #1 acheter 0.10 GBPUSD à 1.5551 sl : 1.4551 tp : 1.5586 ok

Mais s'ouvre à 1.55512 ! Aux cinq chiffres. Ensuite, les ordres en attente sont placés à quatre chiffres et déclenchés à quatre chiffres également. Mais OP_SELL et OP_BUY ne s'ouvrent que par cinq chiffres !

Je fais NormalizeDouble(Ask,Digits) ;

Rien ne marche ! Veuillez me conseiller sur la façon de résoudre ce problème.

Vous pouvez, bien sûr, ignorer le dernier chiffre. L'erreur ne se produit pas, mais pour la pureté de l'expérience, j'ai besoin que toutes mes transactions soient effectuées en quatre chiffres.


Il est fort probable que votre MT4 et votre serveur aient une cotation à cinq chiffres, comme le mien. Ainsi, tout doit être multiplié par 10, car chiffres = 5.
 
Parn25:
Comment supprimer un ordre en attente si l'un d'eux s'est déclenché ? Il y a deux ordres en attente au total.

Vous pouvez le faire manuellement. Cliquez avec le bouton droit de la souris et ensuite... :)

Vous pouvez appliquer un script ou un conseiller expert. Lequel préférez-vous ? XD

Raison: