[ARCHIVIO] Qualsiasi domanda da principiante, per non ingombrare il forum. Professionisti, non passate oltre. Da nessuna parte senza di te - 3. - pagina 284

 
ZZZEROXXX:


UP. il principio della conversione di un EA in uno script in poche parole sarebbe apprezzato

È più semplice così.
 
ZZZEROXXX:


UP. il principio della conversione di un EA in uno script in poche parole sarebbe apprezzato


Non lo so esattamente, ma sembra che se si sposta l'EA in script, funzionerà come uno script.
 
ZZZEROXXX:


UP. apprezzerei il principio della conversione di un EA in uno script in poche parole

E cosa farà la sceneggiatura?

Di solito il terminale è scollegato, un file CSV viene scritto da un timeframe non standard e poi caricato al posto di qualsiasi simbolo e periodo, su questo periodo e testato. Vero a prezzi di apertura, ma non ci sono molte altre opzioni.

 
splxgf:

E cosa farà il copione?

Di solito il terminale è scollegato, un file CSV viene scritto da un timeframe non standard e poi caricato al posto di qualsiasi simbolo e periodo, questo è il periodo su cui vengono fatti i test. Vero a prezzi di apertura, ma non ci sono molte altre opzioni.


Grazie a tutti coloro che hanno risposto. Mi piace la variante con la sostituzione TF, la proverò. Inizialmente avevo intenzione di aprire un TF standalone non standard e scaricare i trade in un file utilizzando uno script Expert Advisor.
 

Che cos'è:

    1. Drawdown massimo, % - percentuale di drawdown massimo;

?

È possibile specificare tale parametro nell'ottimizzatore di strategia, ma non è chiaro cosa significhi...

1) È la diminuzione massima del saldo rispetto al deposito iniziale?

2) La massima differenza tra il massimo e il minimo del patrimonio netto che si susseguono?

3) La differenza tra il margine minimo e massimo?

Mi vengono in mente molte altre varianti.

Si prega di spiegare l'esatto significato di (Maximum drawdown, %)

 
snail09:

Ho iniziato a capire il tuo codice. Sono sorpreso. Quello che avete allegato non può funzionare. Si può vedere che è fatto di pezzi e bocconi, ma almeno le staffe sono corrette.

Il codice è in due parti, questo è il mio esperto. Per favore, dategli un'occhiata.

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

seconda 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);
}
 
Potete dirmi come cancellare un ordine in sospeso se uno degli ordini in sospeso è scattato? Un totale di due ordini pendenti sono impostati.
 
ArgentumZ:

Ciao!

Esecuzione dell'EA sul tester. Il server è a quattro cifre. Quando si inserisce un ordine di acquisto o di vendita nel registro si dice

2011.10.23 15:27:26 2010.12.16 06:16 test_sovetnik GBPUSD,H1: aperto #1 comprare 0,10 GBPUSD a 1,5551 sl: 1,4551 tp: 1,5586 ok

Ma apre a 1,55512! Alle cinque cifre. Poi gli ordini pendenti sono piazzati a quattro cifre e attivati anch'essi a quattro cifre. Ma OP_SELL e OP_BUY si aprono solo di cinque cifre!

Faccio NormalizeDouble(Ask,Digits);

Non funziona niente! Per favore, consigliate come risolvere questo problema?

È possibile, naturalmente, ignorare l'ultima cifra. L'errore non si verifica, ma per la purezza dell'esperimento, ho bisogno che tutti i miei scambi siano fatti in quattro cifre.


Molto probabilmente il tuo MT4 e il tuo server hanno una quotazione a cinque cifre, come il mio. Quindi, tutto deve essere moltiplicato per 10, poiché Cifre = 5.
 
Parn25:
Come posso cancellare un ordine in sospeso se uno di essi è scattato? Ci sono due ordini pendenti impostati in totale.

Puoi farlo manualmente. Fare clic con il tasto destro del mouse e poi... :)

Puoi applicare uno script o un Expert Advisor. Quale preferisci? XD