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

 
hoz:

If it's 7.43 and I haven't gone to bed... So I guess it's spelled grail!

Nah, no need to swear like that :)) Yusuf gave me the Grail. I'm sitting in my suitcases, waiting for manna from heaven, I'm going to the Maldives :))

 
artmedia70:
So show me what you've done... No telepaths here - they're on holiday.

extern string time1 = "n";// 
extern string time2="m";
extern double lot=0.2;// объявили лот
extern int slippage=2;// объявили макс отклонение от цены





int start()
{
double max;// максимальная цена 6-ти свечей
double min;// минимальная цена 6-ти свечей
int hour1 = TimeHour(StrToTime(time1)); // время часы
int minute1 = TimeMinute(StrToTime(time1));// время минуты


if (hour1 == TimeHour(TimeCurrent()) && minute1 == TimeMinute(TimeCurrent()))// если время подошло то
{
min=Low[iLowest(Symbol(),0,MODE_LOW,6,1)]; // вычисляем минимальную цену последних 6 свечей
max=High[iHighest(Symbol(),0,MODE_HIGH,6,1)]; // вычисляем максимальную цену последних 6 свечей
double volum=max-min;// общий объем локалки последних 6 свечей М5
 int ticket1=-1;
 int ticket2=-1;
if ((volum<=0.0018)==true)// если объем свечей меньше или равно z пунктов 

if (ticket1<0)
{ 
OrderSend ( Symbol (), OP_BUYSTOP, lot,max+Point,3,min-Point,max+0.0022, NULL,0,time2, Red);
Alert(GetLastError());
}
if(ticket2<0)
{
OrderSend( Symbol (), OP_SELLSTOP, lot,min-Point,3,max+Point,min-0.0022, NULL,0,time2, Yellow);
Alert(GetLastError());
}


return;


if (OrderSelect(1,SELECT_BY_POS,MODE_HISTORY)) ///если первый открытый ордер закрылся с профитом 
if(OrderProfit()>0)
{
OrderDelete(OrderTicket());// удаляем второй отложенный
}

}



bool closeorder;//определим переменную закрытия ордеров
closeorder=true;

if (closeorder==true)// вечернее закрытие всех отложенных ордеров, и рыночных позиций
{
int hour2 = TimeHour(StrToTime(time2));// вычисляем время закрытия ордеров
int minute2 = TimeMinute(StrToTime(time2));

if (hour2 == TimeHour(TimeCurrent()) && minute2 == TimeMinute(TimeCurrent()))// если время ***
{// определяем количество открытых позиций, и отложенных ордеров
for(int i=OrdersTotal()-1; i>=0; i--)
 if (OrderSelect(1,SELECT_BY_POS,MODE_TRADES))break; //определяем место где будем искать ( рабочие позиции)
if (OrderType()==OP_BUY ) OrderClose (OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),slippage);// Закрытие ордера бай если такой есть
if (OrderType()==OP_SELL) OrderClose (OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),slippage);//Закрытие ордера селл если такой есть
if (OrderType()==OP_BUYSTOP)
{ 
OrderDelete(OrderTicket()); //удаляем отложенный байстоп
}                    
if(OrderType()==OP_SELLSTOP)
{ 
OrderDelete(OrderTicket()); //удаляем отложенный sellstop
}                    

I have uploaded the general code of the Expert Advisor, to make it clearer what it should do... I know it's a mess, but I haven't learned otherwise yet =)))
I will tell you once again where it is stupid
open a pending order: opens either one pending order without the opposite one or a whole bunch of pending orders in one direction.
It deletes orders: sometimes ok in the evening at a clearly specified time, and sometimes in a day, or does not close at all ...

Well, the condition is :
If the first open pending order closes with a profit, the second one is deleted immediately - I doubt I have written it correctly, but I cannot check it in action as I do not want to open two opposite positions=(((((
 
artmedia70:
When searching for the last closed order, we should first find the most recently closed one but the check for closing it at take should be taken out of the loop, otherwise it will check for closing at take for each closed order and, if so, it will remember the time of the first order closed at take in the loop and not the latest one.


Well, this is code optimization. The result will not change, as I see it. It just takes longer to calculate. I did fix the code, but it's still the same.

//+-------------------------------------------------------------------------------------+
//| Получаем состояние последней позиции (Открыта или закрыта)                          |
//+-------------------------------------------------------------------------------------+
datetime GetLastOrderState()
{
   datetime lastOrderCloseTime = -1,               // Время закрытия последнего открытого ордера
            lastOOTMarket = -1,          // Время открытия последнего открытого ордера рыночного
            lastOOTHist = -1;            // Время открытия последнего открытого ордера из истории
   
   for (int i=OrdersHistoryTotal()-1; i>=0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
      if (OrderMagicNumber() != i_magic) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderType() > 1) continue;               // Все удалённые отложки нас не интересуют..
  
      if (lastOrderCloseTime < OrderCloseTime())   // Находим время закрытия..
          lastOrderCloseTime = OrderCloseTime();   // ..последней закрытой позиции в истории
      Comment("Время закрытия последнего ордера в истории lastOrderCloseTime = ", lastOrderCloseTime);
   }

   if (MathAbs(OrderTakeProfit() - OrderOpenPrice()) < i_tp * pt) return(0);
      Comment("OrderTakeProfit() - OrderOpenPrice() < i_tp * pt = ", MathAbs(OrderTakeProfit() - OrderOpenPrice()) < i_tp * pt);
   lastOOTHist = OrderOpenTime();   // Тогда время открытия последней закрытой позиции из истории
      Comment("Время закрытия последнего ордера в истории lastOOTHist = ", lastOOTHist);
   
      Comment("Время открытия последнего открытого ордера = ", lastOOTHist);
  
   for (int h=OrdersTotal()-1; i>=0; i--)
   {   
      if (!OrderSelect(h, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() != i_magic) continue;
      if (OrderSymbol() != Symbol()) continue;
      {
         if (lastOOTMarket < OrderOpenTime())
             lastOOTMarket = OrderOpenTime();
  
         if (lastOOTMarket < lastOOTHist)      // Если время открытия последнего открытого ордера (рыночного) ниже последнего открытого ордера из истории..
             lastOrderCloseTime = OrderCloseTime(); // Значит это искомый ордер
      }
   }

   Comment("Время закрытия последнего открытого ордера = ", lastOrderCloseTime);
   return (lastOrderCloseTime);
}

Still, there's something wrong with it.

 
ex1m:

I tried to show you the code of an EA, I know it's a mess, but I've never learned how to do it in another way.)
I will tell you once again where it is stupid
Opening pending orders: it opens either one pending order without the opposite one or a whole bunch of pending orders in one direction.
Deletion of orders: deletes them every time, sometimes ok in the evening at a clearly specified time, and sometimes in a day, or does not close at all...

Well, the condition:
If the first open pending order closes with a profit, the second will be deleted immediately - I also doubt that I wrote it correctly, but I can not check in work, because I do not want to open two opposite positions=(((((



To answer a question with a question. What the hell is that:

if ((volum<=0.0018)==true)// если объем свечей меньше или равно z пунктов 

Decipher it for me, I don't understand :)

Checks to open a position should be after attempting to open a position. I.e.

if (ticket1<0)

You place it after you send an order.

The price has to be higher or lower than the Asc or Bid to open the position. This is how it is for the Buy:

 if (OOP > Ask)
 
hoz:


Well, this is code optimization. The result will not change, as I see it. It just takes longer to calculate. I did fix the code, but it's still the same.

There's still something wrong with it.

No, it's not code optimization. It's just looking for exactly the last one. Once we have completed the search of all closed orders and found the last closed order of them, only then we should check for closing by the take and, if it is closed by the take, only then it makes sense to continue searching for the rest.

If we check for a close one inside the loop, what will we get? We will get an error of logic:
. Suppose we have chosen an order that was closed a year ago. Its time will anyway be more than -1, so we check it to close it at take (it is checked inside the loop). Yes, it closed on the take... What does your function do next? Right - it continues to work with that order closed at the mark a year ago. Let me see what else is wrong. Just got home...

 

It was written: 2. If the last open position closes at the take, then close the whole thing!

So, it goes like this:

//-----------------------------------------------------------------------------------------------+
bool isCloseByTakeLastOpenPos (string sy, int mn, int delta) {
   datetime t=0;
   int   i, k, j=-1;
   
// Сначала определим, что последняя закрытая позиция была закрыта по тейку (в пределах дельты)
   k=OrdersHistoryTotal()-1;
   for(i=k; i>=0; i--) {
      if (OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) {
         if (OrderMagicNumber()!=mn)   continue;
         if (OrderSymbol()!=sy)        continue;
         if (OrderType()>1)            continue;            // Сначала забыл вписать, подправил
         if (t<OrderCloseTime()) {t=OrderCloseTime(); j=i;}
         }
      }  
   // Нашли последнюю. Проверим её закрытие по тейку
   if (OrderSelect(j,SELECT_BY_POS,MODE_HISTORY)) {                      
      if (OrderProfit()+OrderSwap()+OrderCommission()<=0)   return(false);          // Закрыта с убытком или в ноль
      if (MathAbs(OrderTakeProfit()-OrderClosePrice())>delta*Point) return(false);  // закрыта в профите, но не в пределах дельты
      else t=OrderOpenTime();    // Если последняя закрытая была закрыта по тейку (в пределах дельты), запомним время её открытия
      }
   else {Print("FUNC isCloseByTakeLastOpenPos : не удалось выбрать ордер в истории");return(false);}
// Здесь мы имеем последнюю закрытую позицию в профите и закрытую по тейку (в пределах дельты), ищем дальше
   k=OrdersTotal()-1;
   for(i=k; i>=0; i--) {
      if (OrderSelect(i,SELECT_BY_POS)) {
         if (OrderMagicNumber()!=mn)   continue;
         if (OrderSymbol()!=sy)        continue;
         if (OrderType()>1)            continue;
         if (t<OrderOpenTime()) return(false);  // Выбранная рыночная позиция открыта позже закрытой по тейку
         }
      else {Print("FUNC isCloseByTakeLastOpenPos : не удалось выбрать рыночный ордер");return(false);}
      }
   return(true);  // Найденная закрытая по тейку позиция была открыта позже всех, возвращаем её время открытия
}
//-----------------------------------------------------------------------------------------------+

We pass to the function the symbol we want to check, magic number and delta (distance in pips == difference between order's take and close price), like this:

   if (isCloseByTakeLastOpenPos (Symbol(), Magic, 5)) { // Если последняя открытая была закрыта по тейку ...
      // ... тут обрабатываем эту ситуёвину
      }
   else {   // Иначе ...
      // тут обрабатываем, если последняя закрытая была открыта не последней или ...
      // ... последняя закрытая была закрыта с убытком или в профите, но за пределами дельты
      }

I have not checked this function, I wrote it on my own hand. Thus, I will leave it to you to search for errors.

You can make it int and use return codes. For example, if the position you are looking for does not exist or exists, but it is closed with a loss, return -1;
if it exists and is closed with a profit, but not within the delta, return 0;
if it exists and is closed with a profit and at Take (within the delta), return 1...

The scope for imagination is enormous...

 
artmedia70:

If, on the other hand, we check for a close on the take, what do we get? We will get a logic error:

Suppose we have selected an order that was closed a year ago. Its time will anyway be higher than -1, so we check it to close it at the take (this check inside the loop is included to the code). Yes, it closed on the take...


So, if we loop on all orders, the loop will anyway loop through all orders. The time of closing of each order will be compared to the previously selected one. But this is where we face a performance problem. TakeProfit will be constantly checked in the loop, with each closed position, instead of only the last one. Isn't it so!?
 
PapaYozh:

Right.

But there is Open[], with an opening price.


Got it, thanks :)
 
hoz:

So if you cycle through all orders, the cycle will in any case cycle through all orders. The time of closing of each order will be compared to the previous selected one. But this is where we face a performance problem. TakeProfit will be constantly checked in the loop, with each closed position, instead of only the last one. Isn't it so?
I have already written an example of the function.
 
hoz:

So if you cycle through all orders, the cycle will anyway cycle through all orders. The closing time of each order will be compared to the previous selected one. But here we have a performance issue. TakeProfit will be constantly checked in the loop, with each closed position, instead of only the last one. Isn't it so!?

That's a glitch:

   for (int i=OrdersHistoryTotal()-1; i>=0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
      if (OrderMagicNumber() != i_magic) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderType() > 1) continue;               // Все удалённые отложки нас не интересуют.. 
  
      if (lastOrderCloseTime < OrderCloseTime())   // Находим время закрытия..
          lastOrderCloseTime = OrderCloseTime();   // ..последней закрытой позиции в истории
      
      if (MathAbs(OrderTakeProfit() - OrderOpenPrice()) < i_tp * pt) return(0); // ЗДЕСЬ ВЫХОДИМ ПРИ ПЕРВОМ ВСТРЕЧНОМ
      
      lastOOTHist = OrderOpenTime();   // Тогда время открытия последней закрытой позиции из истории
   }
Reason: