[WARNING CLOSED!] Any newbie question, so as not to clutter up the forum. Professionals, don't go by. Can't go anywhere without you. - page 842

 
You have the order modification in the same block as the opening, and its condition is no orders. It turns out that you have just opened an order and immediately try to modify it - but where will the profit of 5 pips come from?
 

Hi all! Recently got interested in moving averages. I found some combination of moving averages and trading conditions and decided to check my TS, whether it is profitable or not, and optimize it, if anything. But my Expert Advisor did not open deals during testing. I spent the whole evening trying to figure out the solution and decided to ask you, dear programmers. To understand how the EA works, I will briefly explain my TS: on the chart with EMA(13) and EMA(55), if a bar crossed EMA(13) and all following bars were above/below EMA(13), then on touching the price with MA(13) we open a position in the direction of the previous bars (after crossing + at least 9 and no more than 23). Take Profit 60 points, Stop Loss = EMA(55) plus minus five points. That's actually the whole strategy. For better illustration, I have posted an example:

And here is the code of the Expert Advisor:

//+------------------------------------------------------------------+
//|                                                          DWM.mq4 |
//|                                 Copyright © 2010, Bobkov Vasiliy |
//|                                          http://www.forex4you.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, Bobkov Vasiliy"
#property link      "http://mql4.com"
extern double Lot=0.1;
extern int FastMA=13;         //Быстрая МА
extern int SlowMA=54;         //МедленнаяМА
extern int TP=60;             //Тейк профит
extern int MinBars=8;         //Минимальное кол-во баров вне МА
extern int MaxBars=25;        //Максимальное кол-во баров вне МА
extern int slippage=3;        //Слипадж
extern int Magic=347586;      //Магическое число
extern int Space=10;          //Отступ от МА при тралле ордеров

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
if (OrderCheck()==true)                                        //Проверяем, есть ли ордер...
   {                                                           //...если ордер есть...
   Trall();                                                    //Траллим
   return (0);
   }
else                                                           //...если нет открытых позиций то...
   {
   double FMA=MA(0);
   double SMA=iMA(NULL,0,SlowMA,0,MODE_EMA,PRICE_CLOSE,0);
   for (int x=1;;x++)                                          //Вычесляем сколько баров вне МА...
      {
      if (MA(x)<High[x]&& MA(x)>Low[x]) break;
      }
   if (Bid==FMA && x>MinBars && x<MaxBars)                     //Если условия выполняются, то...
      {
      if (FMA>SMA ) OrdOpen(0,SMA);                            //...открывем сделку на покупку
      if (FMA<SMA) OrdOpen(1,SMA);                             //...или на продажу
      }
   }   
//----
   return(0);
  }
//+------------------------------------------------------------------+

bool OrderCheck()                                              //Функция проверки позиций
   {
   for(int i=1;i<=OrdersTotal();i++)
      {
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         {
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) return(true);
         }
      else
         Print("OrderSelect() вернул ошибку - ",GetLastError());
          
      }
    return(false);
   }

void OrdOpen(int type,double SO)                               //Функция открытия позиций
   {
   if (type==0) 
      {
      if (OrderSend(Symbol(),0,Lot,Ask,slippage,SO-Space*Point,Ask+TP*Point,NULL,Magic,0,Blue)==true) return;
      else Print("OrderSend() вернул ошибку - ",GetLastError());
      }
   else 
      {
      if (OrderSend(Symbol(),0,Lot,Bid,slippage,SO+Space*Point,Bid-TP*Point,NULL,Magic,0,Blue)==true) return;
      else Print("OrderSend() вернул ошибку - ",GetLastError());
      }
   return;
   }
   
void Trall()                                                    //Трейллинг стоп
   {
   if (OrderSelect(Magic,SELECT_BY_TICKET)==true)
      {
      double SL=iMA(NULL,0,SlowMA,0,MODE_EMA,PRICE_CLOSE,0);
      if (Bid<iMA(NULL,0,SlowMA,0,MODE_EMA,PRICE_CLOSE,0)) SL=SL+Space*Point;
      else SL=SL-Space*Point;
      if (OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(SL,Digits),OrderTakeProfit(),0,Blue)==true) return;
      else Print("OrderModify() вернул ошибку - ",GetLastError());
      }
   return;
   }
double MA(int m)                                                  //Функция возвращающая значение МА
   {
   return(iMA(NULL,0,FastMA,m,MODE_EMA,PRICE_CLOSE,0));
   }

If anyone can help please. I will also give you the EA itself

Files:
dwm.mq4  5 kb
 

Many functions can be collected in one for-cycle to open, change, close positions, etc.

Here is a simple Example:

            bool Ans=OrderModify(Ticket,Price,SL,TP,0);
            if (Ans==true) {
               Alert ("Ордер ",Text,Ticket," модифицирован:)");
               break;                           // Из цикла модифи.
            }

- Question: is it correct to use "break" rather than "return" here? Is there a difference?

 
chief2000:

Many functions can be collected in one for-cycle to open, change, close positions, etc.

Here is a simple Example:

- Question: is it correct to use "break" rather than "return" here? Is there a difference?

From https://docs.mql4.com/ru/basis/operators/break:
"The break statement stops execution of the nearest nested external switch, while, or for statement. Control is given to the operator that follows the one that ends."

From https://docs.mql4.com/ru/basis/operators/return:
"The return statement terminates the current function and returns control to the calling program."

Answer: It is correct to use "break" here.

 
abolk:

From https://docs.mql4.com/ru/basis/operators/break:
"The break statement terminates the execution of the nearest nested external switch, while or for statement. Control is given to the operator that follows the one that ends."

From https://docs.mql4.com/ru/basis/operators/return:
"The return operator terminates the current function and returns control to the calling program."

Answer: it is correct to use "break" here.

I actually use break myself, but thought return meant a tick change (and break didn't).

In reality, until the order changes, there will be a change of tick, so in order for the tester to correctly simulate the situation

you need to use return. Right?

Maybe I am mistaken but I would like to understand it.

 
chief2000:

I actually use break myself, but I thought return meant a tick change (while break does not).

In reality, until the order changes, the tick change will occur and therefore the tester has to use return to correctly simulate the situation

you need to use return. Right?

Maybe I am mistaken, but I want to understand it.

Let's read in the documentation: "The return operator stops executing the current function and returns control to the calling program."

If the current start() function, again read the documentation:

https://docs.mql4.com/ru/runtime/start
"When a new quote comes, the function start() of attached Expert Advisors and custom indicators is executed. If at the arrival of a new quote the function start(), running on the previous quote, is executed, then the incoming quote will be ignored by the Expert Advisor. All new quotes, coming during the program execution, are ignored until the next execution of the start() function is finished. After that the function start() will be launched only after the next new quote arrival.

 
abolk:

Read in the documentation: "The return statement terminates the current function and returns control to the calling program."

If the current function is start(), again read in the documentation:

https://docs.mql4.com/ru/runtime/start
"When new quotes come, the function start() is executed for attached Expert Advisors and custom indicators. If at the arrival of a new quote the function start(), running on the previous quote, is executed, then the incoming quote will be ignored by the Expert Advisor. All new quotes, coming during the program execution, are ignored until the next execution of the start() function is finished. After that the function start() will be launched only after the next new quote arrival.

I wish you'd put it in your own words. I don't understand what you mean.

In the tester, if for is terminated with break and some other function follows it, it will be executed on the same tick. But in reality, several ticks may change during this time (while the order is being modified). That's why I think return is more realistic. Isn't it?

 
chief2000:

I wish you had put it in your own words. I don't understand what you mean.

If for is terminated with break and followed by some other function, it will be executed on the same tick. But in reality, several ticks may change during this time (while the order is being modified). That's why I think return is more realistic. Doesn't it?


start() starts at the beginning of a tick and may not be finished by the beginning of the next tick.

break terminates for, and return terminates the function. If there are no operators after for, there is no difference in using for and return for this algorithm.

But each operator has its purpose. And unintended use of an operator is like an unloaded shotgun.

Again, in the for loop algorithm, for some reason there is no need to continue executing the function, we can use return.

In other words, if the algorithm requires a break in the loop, then break is used, even if the function is still terminated after the loop.

 
abolk:


start() starts working at the beginning of a tick and its work may not end by the beginning of the next tick.

break completes for, return completes the function. If there are no operators after for, there is no difference between using for and return for this algorithm.

But each operator has its purpose. And unintended use of an operator is like an unloaded shotgun.

Again, in the for loop algorithm, for some reason there is no need to continue executing the function, we can use return.

In other words, if the algorithm requires us to break the loop, we put break, even if the function terminates after the loop anyway.

A thought occurred to me, since all this was intended only for the tester, we can (where necessary) do the following:

if(IsTesting()==true   ||   IsOptimization()==true) {
   return;
}

break;

Thank you!

 
chief2000:

An idea has come up - since this was only started for a tester, you could (where appropriate) do the following:

Thank you!


you can
Reason: