Questions from Beginners MQL5 MT5 MetaTrader 5 - page 412

 
Imminence:

Hello, I have a beginner's problem...

I can't get the system to compare the last bar close value with the highs and lows of a certain period, e.g.

last 20 bars. What am I doing wrong?


I checked it with Alert and for some unknown reason the tester displays the maximum value from the calculation of the last tick, but it gives this value

It is the same number of times as the ticks, so the order does not open.


The second issue is how to make my EA wait for the next bar to open (30m period)? In the checkpoints test everything is fine, but if I use ticks,

then EA opens in the same bar right after it closed at stop loss...


Also, how can I close a trade independent of a tick or not? For example, for a period of 30m I want to close the order 5 seconds before the end of the bar (29.55, 59.55)

Based on all the data at that moment. At this stage the problem is that if a tick does not occur within 5 seconds, therefore no

(In theory this is bullshit, but in reality the next tick might appear in a few candlesticks for some reason.

may be in a few candles for some reason.


Thanks in advance!

1. I did not see anything about the last 20 bars in the code.

2. How to determine the first tick of a new bar

3. How do I close a order without checking whether it was a tick or not?

We have to avoid working with OnTick and work with OnTimer. Set the timer with an interval of 1 second and check the time in it. The timer doesn't depend on ticks.

/// Определяет начало нового бара
bool NewBar()
{
    static datetime lastbar = 0;
    datetime curbar = iTime(Symbol(), PERIOD_M30, 0);
    if(lastbar!=curbar)
    {
        lastbar=curbar;
        return (true);
    }
    return(false);
}
 
Leanid Aladzyeu:

o_oops didn't know the terminal also pokes where the error is, first time I hit a critical error.

It spits on it.

Of course it will spit, you access the 3rd element of an array with dimension 2 - mas[2]++

void Oher(int Mag,string Symb, int &mas[2])
..............
...........

case 1:mas[1]++; mas [2]++;break;// 1 продажа
 

Alexey Volchanskiy:
Так у тебя в комменте стоит управляющий символ "\n " - это символ перевода строки. Если его убрать, многострочия не будет.

It's a joke. Now it adds a comment at the end of the line... and the text runs off to the right. ;-)

 

Good evening. Trying to write a simple EA on tenkan and kinjun crossing. Here is the code:

void OnTick()

void OnTick()

{

TradeSignal_20();

}


int TradeSignal_20()

{

int sig=0;


if(h_ich==INVALID_HANDLE)

{

h_ich=iIchimoku(Symbol(),Period(),IKHtenkansen,IKHkijunsen,IKHsenkouspanb);

return(0);

}

else

{

if (CopyBuffer(h_ich,0,0,3,ich1_buffer)<2) return(0); // TENKANSEN_LINE

if (CopyBuffer(h_ich,1,0,3,ich2_buffer)<2) return(0); // KIJUNSEN_LINE

if (!ArraySetAsSeries(ich1_buffer,true)) return(0);

if (!ArraySetAsSeries(ich2_buffer,true)) return(0);

}

//--- check condition and set value for sig

if(ich1_buffer[1]>ich2_buffer[1]) sig=1;

else if(ich1_buffer[1]<ich2_buffer[1]) sig=-1;

else sig=0;

if (ich1_buffer[1]>ich2_buffer[1])

if (ich1_buffer[2]<ich2_buffer[2])

Alert(Symbol()+": purchase");

if (ich1_buffer[1]<ich2_buffer[1])

if (ich1_buffer[2]>ich2_buffer[2])

Alert(Symbol()+": sale");

//--- return trade signal

return (sig);

}

//+------------------------------------------------------------------+

How can I make the alert be called only once and not constantly?

 
Alexey Volchanskiy:

1. I didn't see anything about the last 20 bars in the code, give details.

2. How to determine the first tick of a new bar

3. How can a trade be closed, regardless of whether it has been ticked or not?

You have to avoid working with OnTick and work with OnTimer, set the timer with 1 second interval and check the time in it. The timer does not depend on the arrival of ticks.

Here, how do I compare the closing price with the maximum of the last 20 bars? And if the last price is equal or greater than the maximum price of the last 20 bars, then there is a signal to open.
  

double HIGHEST              = High[iHighest(Symbol(),0,MODE_HIGH,20,0)];


   
  if(Close[0] > SMMA && Close[0] > BB_UP && Close[0] >= HIGHEST)

  {
   TICKET = OrderSend(Symbol(),OP_BUY,LOT,Ask,0,Ask-StopLoss*Point,Ask+TakeProfit*Point,NULL,MAGIC,0,Blue);
   if(TICKET < 0)
      {
         Alert("Order Send failed, error # ", GetLastError() );
      } 
  }
 
first_may:

Good evening. Trying to write a simple EA on tenkan and kinjun crossing. Here is the code:

void OnTick()

void OnTick()

{

TradeSignal_20();

How can I make the alert be called only once and not all the time?
Can't you press the SRC button?
 
Imminence:
Here, how do I compare the closing price with the maximum of the last 20 bars? And if the last price is equal to or greater than the maximum of the last 20 bars then there is a signal to open.
Let's look at the code
double HIGHEST              = High[iHighest(Symbol(),0,MODE_HIGH,20,0)];

  if(Close[0] > SMMA && Close[0] > BB_UP && Close[0] >= HIGHEST)

  {
***********

I think the problem is with referring to the zero bar, i.e. the current bar. You should define the beginning of a new bar, I gave it in the previous answer and perform all comparisons only on the first tick of a new bar. And change the indexing. We need to ensure that the last closed bar is not in iHighest. And now you have a reference to the current bar being formed on every tick, the results will be the strangest.

double HIGHEST              = High[iHighest(Symbol(),0,MODE_HIGH,20,2)];

  if(Close[1] > SMMA && Close[1] > BB_UP && Close[1] >= HIGHEST)

  {
***********

 
Alexey Volchanskiy:
Let's look at the code of

I think the problem is with the reference to the zero bar, i.e. the current bar. You need to define the start of a new bar, I cited it in the previous reply and only on the first tick of the new bar do all comparisons. And change the indexing. We must ensure that the last closed bar is not in iHighest. And now you have a reference to the current bar being formed on every tick, the results will be the strangest.

Thanks, seems to have helped :) although I could have sworn I did exactly the same thing and it didn't work...

You advised OnTimer() but for some reason it won't cooperate with me. I studied all the help and didn't find any clear explanations or examples, so I was stumped.

That is, this trivial code is not executed, even though it's all specified in the reference... Googling this program I came across that they say OnTimer() does not work in the test

mode. Although this moment seems to have been eliminated with mql5. Help to understand it :) Thanks!

int OnInit()
  {
//---
  bool  Timer = EventSetTimer(1);
  if(Timer != TRUE)
  Print(GetLastError()); 
//---
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
  EventKillTimer();   
  }
  
void OnTimer()
{
Print("It works");
}  
  
 

Imminence:

Googling this program I encountered that they say OnTimer() doesn't work in test mode. It has been solved with mql5. Help me to understand it.) Thanks!

Right, in MT4 in the tester the timer doesn't work and it's not documented! I wrote to servicedesk and they said they would never do it. I got out of it by calling OnTimer in OnTick. I have the timer set to one second.

// Возвращает true, если работает под тестером
bool IsRunOnTester()
{
    if(MQLInfoInteger(MQL_TESTER) || MQLInfoInteger(MQL_VISUAL_MODE) || MQLInfoInteger(MQL_OPTIMIZATION))
        return true;
    return false;    
}

MqlDateTime     TimeCurrStruct;

void OnTick()
{
    if(IsRunOnTester())
    {
        static datetime dt1 = 0, dt2 = 0;
        static bool tfirst = true;
        if(tfirst)
        {
            tfirst = false;
            dt1 = dt2 = TimeCurrent();
            return;
        }
    
        dt2 = TimeCurrent();
        for(datetime TimeTesterCurrent = dt1+1; TimeTesterCurrent <= dt2; TimeTesterCurrent++)
        {
            TimeToStruct(TimeTesterCurrent, TimeCurrStruct);
            OnTimer();
        }    
        dt1 = dt2;
    }
}

So, if in the tester the ticks come more than 1 time/sec, the excess ones are skipped; if less often, the time multiple of 1sec is generated. This time lies in TimeCurrStruct structure, and my main class in any mode takes time only from this structure. In my opinion, this is the only way to deal with this bug. Here's a function, I removed unnecessary things, only meat ))

void OnTimer()
{
    string msg;
    if(!IsRunOnTester())
    {
        TimeToStruct(TimeCurrent(), TimeCurrStruct);
        SmartDsp.ReceiveTick(TimeCurrStruct);    // основной метод робота, в него передается структура со временем
    }
    else
    {
        SmartDsp.ReceiveTick(TimeCurrStruct);    
    }
}




 
Alexey Volchanskiy:
Can't you press the SRC button?
It's not clear what you mean by that?