Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 210

 
artmedia70:


The mistake with the magician causes your EA not to see that its position is closed on a stop when closing on a stop. Why? The answer is that you open a position with magic 123 and send the variable Magic to the function that checks for closing the position at the stop. What do you think it equals when initialized implicitly? Zero. The function is naturally searching for positions with magic number 0 and it is equal to 123 in your positions. And we're not arguing, just... ...reasoning... Check the response to close on the stop:


I didn't look at the rest of your "dead" EA logic - I was helping you figure out the stop close check function...


Artem ! Good day! Thanks again for the help.

I have removed all unnecessary "dead" logic and "revived" the remaining ones.... as far as I understand it.

Left only one function, which you have helped me to fix.

But miracles began to happen beyond my comprehension

1. My Expert Advisor opens trades at the beginning of each candle (I have a 5 minute candle)

and ignoring all of the conditions.

I.e. the control enters the first line

double Price=iOpen(Symbol (),0,0);

And then it jumps through 11 lines and gets to the following lines

Lot=0.1;

OrderSend(Symbol(),OP_SELL,1,Bid,Lot,Ask+1500*Point,Ask-300*Point, "jfh",123 );

2. If we remove the line that calculates the minimum lot Lot=MarketInfo(Symbol(), MODE_MINLOT);

The Expert Advisor works fine, but the isCloseLastPosByStop function doesn't work.

I was straining my brain for a long time..... but in vain. I would be grateful if you could tell me where the error is hidden.

double   Lot = 0.1;                                          //я проинициализировал переменную
int      Magic=123;

int start() 
{

   double Price=iOpen(Symbol (),0,0);                      //запоминаем время открытия очередной свечи
   int ot=OrdersTotal();                                   //запоминаем количество всех открытых ордеров
      if ((ot==0)                                         //если ордеров в рынке никаких нет
      &&(Bid==Price)                                     //И ПРИ ЭТОМ  если  цена = цене открытия очередной свечи
         &&(Open[1]-Close[1]>100*Point&&Open[1]-Close[1]<120*Point)      //И ПРИ ЭТОМ  если свеча N1 соответствуе этим параметрам
            &&(High[1]-Open[1]>40*Point&&High[1]-Open[1]<60*Point)       //И ПРИ ЭТОМ  если свеча N1 соответствуе этим параметрам
                &&(Close[1]-Low[1]>40*Point&&Close[1]-Low[1]<60*Point))  //И ПРИ ЭТОМ  если свеча N1 соответствуе этим параметрам
                
                  Lot=MarketInfo(Symbol(), MODE_MINLOT);                  //вычислить минимальный лот инструмента
                               
                  if (isCloseLastPosByStop(Symbol(), OP_BUY, Magic, Lot))//вызываем функцию,если она вернула(не понимаю-ведь функция
                     {                                                   //должна вернуть и положить сюда true или False,а здесь совсем другие передаваемые парам.)
                     t=Lot*2; // удваиваем начальный лот
                     OrderSend(Symbol(),OP_SELL,Lot,Bid,1,Ask+1500*Point,Ask-300*Point,"jfh",123 );
                     }
                  else                                                    //в противном случае(если функция на вернула ??????
                     {
                     Lot=0.1;                                             // лот отстается 0.1       
                     OrderSend(Symbol(),OP_SELL,1,Bid,Lot,Ask+1500*Point,Ask-300*Point,"jfh",123 );
                     }
                      
   return(0);
}
//+----------------------------------------------------------------------------+
bool isCloseLastPosByStop(string sy, int op, int mn, double &ll) {
   double   pt;
   int      dg, i, j=-1, k=OrdersHistoryTotal()-1;
   datetime t=0;                                   // во избежание возможных ошибок после возможных будущих улучшений
   for (i=k; i>=0; i--) {
     if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
         if (OrderMagicNumber()!=mn)   continue;   // если магик не тот, переходим к следующему
         if (OrderSymbol()!=sy)        continue;   // если символ не тот, переходим к следующему
         if (OrderType()!=op)          continue;   // если тип не тот, переходим к следующему
         if (t<OrderCloseTime()) {
            t=OrderCloseTime();
            j=i;
            }
         }
      }
   if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
      dg=MarketInfo(OrderSymbol(), MODE_DIGITS);      // количество знаков в цене символа ордера
      pt=MarketInfo(OrderSymbol(), MODE_POINT);       // размер пункта инструмента в валюте котировки ордера
      if (MathAbs(OrderClosePrice()-OrderStopLoss())<0.5*pt) { // Если закрыт по стопу
         ll=OrderLots();                              // записываем количество лотов в ордере, закрытом по стопу
         return(true);                                // возвращаем истину
         }
      }
   return(False);                                     // возвращаем ложь (позиции нету, либо не по стопу)
}


 

solnce600:

Артем ! Добрый день! Еще раз спасибо за помощь.

All my " dead logic" removed unnecessary and "revived" the rest.... as far as I understand it.

I practically left only the function, which you helped me to correct.

But the miracles, which are beyond my understanding, have started to happen.

After

 if ((ot==0)                                         //если ордеров в рынке никаких нет
      &&(Bid==Price)                                     //И ПРИ ЭТОМ  если  цена = цене открытия очередной свечи
         &&(Open[1]-Close[1]>100*Point&&Open[1]-Close[1]<120*Point)//И ПРИ ЭТОМ  если свеча N1 соответствуе этим параметрам
            &&(High[1]-Open[1]>40*Point&&High[1]-Open[1]<60*Point)
               &&(Close[1]-Low[1]>40*Point&&Close[1]-Low[1]<60*Point))

add everything to the body { }

Sorry I'm not Artem.

 
ALXIMIKS:

solnce600:

After

add everything to the body { }

I'm sorry I'm not Artem.

Thanks .Forgive me for the first time.......(don't know how to add the joking emoticon)
 
 t=Lot*2; // удваиваем начальный лот
                     OrderSend(Symbol(),OP_SELL,Lot,Bid,1,Ask+1500*Point,Ask-300*Point,"jfh",123 );

t or Lot ???

 
ALXIMIKS:

solnce600:

After

add everything to the body { }

Sorry I'm not Artem.

Did as you said..... alas advisor works .... the isCloseLastPosByStop function does not work

double   Lot=0.1;
int      Magic=123;

int start() 
{

   double Price=iOpen(Symbol (),0,0);  //запоминаем время открытия очередной свечи
   int ot=OrdersTotal();               //запоминаем количество всех открытых ордеров
      if ((ot==0)                      //если ордеров в рынке никаких нет
      &&(Bid==Price)                   //И ПРИ ЭТОМ  если ПРИ ЭТОМ  цена = цене открытия очередной свечи
         &&(Open[1]-Close[1]>100*Point&&Open[1]-Close[1]<120*Point)//И ПРИ ЭТОМ  если свеча N1 соответствуе этим параметрам
            &&(High[1]-Open[1]>40*Point&&High[1]-Open[1]<60*Point)
               &&(Close[1]-Low[1]>40*Point&&Close[1]-Low[1]<60*Point))
               
                {
                  Lot=MarketInfo(Symbol(), MODE_MINLOT);            //вычислить минимальный лот инструмента
                               
                  if (isCloseLastPosByStop(Symbol(), OP_BUY, Magic, Lot))//вызываем функцию,если она вернула(не понимаю-ведь функция
                     {                            //должна вернуть и положить сюда true или False,а здесь совсем другие передаваемые парам.)
                     Lot=Lot*2; // удваиваем начальный лот
                     OrderSend(Symbol(),OP_SELL,Lot,Bid,1,Ask+1500*Point,Ask-300*Point,"jfh",123 );
                     }
                  else  //в противном случае(если функция на вернула??????
                     {
                     Lot=0.1; // лот отстается 0.1       
                     OrderSend(Symbol(),OP_SELL,1,Bid,Lot,Ask+1500*Point,Ask-300*Point,"jfh",123 );
                     }
                     } 
   return(0);
}
//+----------------------------------------------------------------------------+
bool isCloseLastPosByStop(string sy, int op, int mn, double &ll) {
   double   pt;
   int      dg, i, j=-1, k=OrdersHistoryTotal()-1;
   datetime t=0;                                   // во избежание возможных ошибок после возможных будущих улучшений
   for (i=k; i>=0; i--) {
     if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
         if (OrderMagicNumber()!=mn)   continue;   // если магик не тот, переходим к следующему
         if (OrderSymbol()!=sy)        continue;   // если символ не тот, переходим к следующему
         if (OrderType()!=op)          continue;   // если тип не тот, переходим к следующему
         if (t<OrderCloseTime()) {
            t=OrderCloseTime();
            j=i;
            }
         }
      }
   if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
      dg=MarketInfo(OrderSymbol(), MODE_DIGITS);      // количество знаков в цене символа ордера
      pt=MarketInfo(OrderSymbol(), MODE_POINT);       // размер пункта инструмента в валюте котировки ордера
      if (MathAbs(OrderClosePrice()-OrderStopLoss())<0.5*pt) { // Если закрыт по стопу
         ll=OrderLots();                              // записываем количество лотов в ордере, закрытом по стопу
         return(true);                                // возвращаем истину
         }
      }
   return(False);                                     // возвращаем ложь (позиции нету, либо не по стопу)
}
 

This is a piece of code from the function bool isCloseLastPosByStop(string sy, int op, int mn, double &ll)

But what if there is a slip in 3 pips? It is not very well thought out ))

 if (MathAbs(OrderClosePrice()-OrderStopLoss())<0.5*pt) { // Если закрыт по стопу
         ll=OrderLots();                              // записываем количество лотов в ордере, закрытом по стопу
         return(true);                                // возвращаем истину
 
solnce600:

You understand - I'm not really bothered about it yet....

I've been trying for a week to figure out why this function doesn't work for me.

I.e. I need the next order to open with a double volume of the order closed at the stop, and the next order to open with a regular volume after the non-stop.


Correct the logic of work, otherwise it will take a long time to think
 
ALXIMIKS:

This is a piece of code from the function bool isCloseLastPosByStop(string sy, int op, int mn, double &ll)

But what if there is a slip in 3 pips? It's not very well thought out ))


You understand - I'm not bothering with it yet....

I haven't understood for a week why this function doesn't work the way I want it to.

I.e. I need to open the next order after the stop with a double volume of the order which closed at the stop, and after the non-stop, the next order is opened with a regular volume.
 

And why touch the order history? Look at the balance - where it went in that direction and change the lot.

If it is only a robot that will trade on your account.

 
Vinin:

Correct the logic of operation, or it will take a long time to think

I would be very grateful if you could explain "on your fingers" in relation to my example.

What is my faulty logic. I do not understand what I am talking about.

Thank you.

Reason: