[ARCHIVE] Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 3. - page 284

 
ZZZEROXXX:


UP. the principle of converting an EA into a script in a nutshell would be appreciated

It's simpler like this.
 
ZZZEROXXX:


UP. the principle of converting an EA into a script in a nutshell would be appreciated


I don't know exactly, but it seems that if you move the EA to scripts, it will work like a script.
 
ZZZEROXXX:


UP. I would be grateful for the principle of converting an EA into a script in a nutshell

And what will the script do?

Usually the terminal is unplugged, a CSV file is written from a non-standard timeframe and then loaded instead of any symbol and period, on this period and tested. True at opening prices, but there are not much other options.

 
splxgf:

And what will the script do?

Usually the terminal is unplugged, a CSV file is written from a non-standard timeframe and then loaded instead of any symbol and period, this is the period on which testing is done. True at opening prices, but there are not really any other options.


Thanks to all who responded. I like the variant with TF substitution, I will try it. I was initially planning to open a non-standard TF standalone and unload trades into a file using an Expert Advisor script.
 

What is:

    1. Maximum drawdown, % - maximum drawdown percentage;

?

You can specify such parameter in the strategy optimizer, but it's not clear what it means...

1) Is it the maximal decrease of the balance compared to the initial deposit?

2) Maximum difference between the equity maximum and minimum following each other?

3) The difference between the minimum and maximum margin?

Many other variants come to mind.

Please explain the exact meaning of (Maximum drawdown, %)

 
snail09:

Started to understand your code. I'm surprised. What you have attached cannot work. You can see it's made up of bits and pieces, but at least the brackets are correct.

The code is two parts. This is my expert. Please take a look at it.

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

second part

//+------------------------------------------------------------------+
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);
}
 
Can you tell me how to delete a pending order if one of the pending orders has triggered? A total of two pending orders are set.
 
ArgentumZ:

Hello!

Running the EA on the tester. The server is four digits. When placing buy or sell order in the log says

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

But opens at 1.55512 ! At the five digits. Then the pending orders are placed at four digits and triggered at four digits as well. But OP_SELL and OP_BUY open only by five digits!

I do NormalizeDouble(Ask,Digits);

Nothing works! Please advise how to solve this issue?

You can, of course, ignore the last digit. The error doesn't occur, but for the sake of purity of the experiment, I need all my trades to be made in four digits.


Most likely your MT4 and server has a five digit quote, like mine. So, everything has to be multiplied by 10, as Digits = 5.
 
Parn25:
How do I delete a pending order if one of them triggered? There are two pending orders set in total.

You can do it manually. Right-click and then... :)

You can apply a script or an Expert Advisor. Which do you prefer? XD

Reason: