Questions from Beginners MQL4 MT4 MetaTrader 4 - page 129

 
Can you tell me how to select the symbol to be tested in the tester?
int OnInit(){return(INIT_SUCCEEDED);}
 
Nikolay Gaylis:
Please advise how to select a symbol in the tester for testing in

You can't. Only manually select in the settings.

In the tester, of course, you can request data on other symbols, but for this you will have to work hard enough to ensure the synchronization of data (the tester itself will not do it for you, because by default it works with one symbol). Trade on the symbol, different from the selected, in general, can not.

P. S. All this is for MT4. In MT5 situation is different.

 
EA works withOnTimer()EventSetTimer(1).I miss many ticks. The eventOnTick() is not suitable for me, because I analyze multiple currency pairs at once ... Even Sleep(200) in loop will load system...What to do?
 

NO DECOMPILING ALLOWED!

 
Nikolay Gaylis:
The Expert Advisor works inOnTimer() EventSetTimer(1). I miss many ticks. TheOnTick() event does not fit me because I analyze several currency pairs at once ... Even Sleep(200) in loop will load system...What to do?

There is also EventSetMillisecondTimer() - it can reduce periodicity of OnTimer() execution.

 
Vladislav Boyko:

There is also EventSetMillisecondTimer() - so you can reduce the periodicity of OnTimer().

Thanks, I'll try it...

 

Good afternoon.

The message "Array out of range" appears in the allocated space during the test. It does not indicate an error during compilation. What is the essence of the error and how can we fix it?

double TD_Close=Close[1];

for (int i=2; i<=Period_bars; i++)

{

if (ABS_High<High[i]) ABS_High=High[i];

}

if (TD_Close>ABS_High)

{

if(OrdersTotal () <= 1 && newCandle != Time[0]) int tiket=OrderSend(Symbol(),OP_BUY,volume,Ask,3,sl,tp,",magic,0);

else newCandle = Time[0];

}

 
Andrey.Sabitov:

Good afternoon.

The message "Array out of range" appears in the highlighted place during the test. It does not indicate an error during compilation. What is the essence of the error and how can we fix it?

double TD_Close=Close[1];

for (int i=2; i<=Period_bars; i++)

{

if (ABS_High<High[i]) ABS_High=High[i];

}

if (TD_Close>ABS_High)

{

if (OrdersTotal () <= 1 && newCandle != Time[0]) int tiket=OrderSend(Symbol(),OP_BUY,volume,Ask,3,sl,tp,",magic,0);

else newCandle = Time[0];

}

Period_bars should be <= Bars - 1

 

Hello, friends, help me solve the following problem: I am trying to write a simple Expert Advisor and I have faced the following: if the SL is set to a value different from 0, then trades are not opened at all, as well as the TP, TStop and TrailingStep functions do not work at all.

What should I fix in the code?

//+------------------------------------------------------------------+
//|                                                           MA.mq4 |
//|                                                           Sergey |
//|                                              http://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright   "Sergey Karev"
#property link        "http://www.mql4.com"
#property description "Moving Average sample expert advisor"
//#property strict

#define  MAGICMA  23101987
//--- Inputs
input double Lots              = 0.01; // Объем лота
input int    SL                = 0;    // Stop Loss
input int    TP                = 0;    // Take profit
input int    TStop             = 0;    // Пункты
input int    TrailingStep      = 0;    // Шаг TS в пунктах
input int    MA_per1           = 5;    // MA быстрая
input int    MA_per2           = 55;   // MA медленная
input int    Timeframe         = 60;   // Таймфрейм 
input double MaximumRisk       = 0.02;
input double DecreaseFactor    = 3;
input int    MovingShift       = 0;    // Cдвиг средней
input int    Shift             = 0;    // Сдвиг баров
input int    Magic_number      = 1987; // Если Magic = 0, то работает + ручные ордеры


bool         TSProfitOnly      = true;
int          NumberOfTry       = 5;
bool         UseSound          = True;
string       NameFileSound     = "expert.wav";
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//--- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//--- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double ma1;
   double ma2;
   int    res;
   
//+------------------------------------------------------------------+
//| Приводим SL и TP к единым целым                                  |
//+------------------------------------------------------------------+   
   
   double sl=0, tp=0;
   sl=NormalizeDouble(SL*Point(),_Digits);
   tp=NormalizeDouble(TP*Point(),_Digits);
   
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
   
//--- get Moving Average 
   ma1=iMA(NULL,         Timeframe,   MA_per1, MovingShift,    MODE_SMMA,        PRICE_CLOSE,Shift);
   ma2=iMA(NULL,         Timeframe,   MA_per2, MovingShift,    MODE_SMMA,        PRICE_CLOSE,Shift);
//         имя символа,  таймфрейм,   период,  сдвиг средней,  метод усреднения, тип цены,   сдвиг

//--- sell conditions
   if(ma1 < ma2) //[1] - номер свечи
     {
      res=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,sl,tp,"",MAGICMA,0,Red);
      return;
     }
//--- buy conditions
   if(ma1 > ma2)
     {
      res=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,sl,tp,"",MAGICMA,0,Blue);
      return;
     }
//---
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double ma1;
   double ma2;
   
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//--- get Moving Average 
   ma1=iMA(NULL,Timeframe,MA_per1,MovingShift,MODE_SMMA,PRICE_CLOSE,Shift);
   ma2=iMA(NULL,Timeframe,MA_per2,MovingShift,MODE_SMMA,PRICE_CLOSE,Shift);
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //--- check order type 
      if(OrderType()==OP_BUY)
        {
         if(ma1 < ma2)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(ma1 > ma2)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
     }
//---
  }
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//+------------------------------------------------------------------+
//| Trailing Stop / Step                                             |
//+------------------------------------------------------------------+

   double tr=0, ts=0, op=0, sl=0,
   ask=NormalizeDouble(Ask,_Digits),
   bid=NormalizeDouble(Bid,_Digits);
   
   tr=NormalizeDouble(TStop*Point(),_Digits);
   ts=NormalizeDouble(TrailingStep*Point(),_Digits); // Приводим к единым величинам (включая центовые счета)
   
double ma2 = iMA(NULL,Timeframe,MA_per2,MovingShift,MODE_SMMA,PRICE_CLOSE,Shift);
   
   for(int i=OrdersTotal()-1; i>=0; i--)
   {
      if(OrderSelect(i,SELECT_BY_POS)==true)
      {
         if(OrderSymbol()==Symbol())
         {
            if(OrderMagicNumber()==Magic_number) // Если Magic = 0, то работает + ручные ордеры
            {
               op=NormalizeDouble(OrderOpenPrice(),_Digits);
               sl=NormalizeDouble(OrderStopLoss(),_Digits);
               
               if(OrderType()==OP_BUY)
               {
                  if((bid-op)>tr)
                  if((bid-sl)>tr)
                  if((bid-tr)>ma2)
                  if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(ma2,_Digits),OrderTakeProfit(),0, clrGreen)==false)
                  Print("Error BUY OrderModify");
               }
               if(OrderType()==OP_SELL)
               {
                  if((op-ask)>tr)
                  if((sl-ask)>tr || sl==0)
                  if((ask+tr)<ma2)
                  if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(ma2,_Digits),OrderTakeProfit(),0, clrGreen)==false)
                  Print("Error SELL OrderModify");                  
               }
            }
         }
      }
   }
  }
//+----------------------------------------------------------------------+

MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
  • www.mql4.com
MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
 
Sergey_M_K:

Hello, friends, help me solve the following problem: I am trying to write a simple Expert Advisor and was faced with the following: if the SL is set to a value different from 0, then trades are not opened at all, as well as the TP, TStop and TrailingStep do not work at all.

What should I fix in the code?

Do you use a debugger to search for errors?
Reason: