[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 665

 
Roger:
Do not count highs and lows from the zero bar but from the first bar, on the zero bar the Bid cannot be less than the Min.
I.e. i=1; ? And leave Bid and Ask untouched?
 
eugggy:
double
Min=Bid, variable declaration

Max=Bid,

____________________________________________________________________________________________

for (i=0;i<=20-1;i++) opening criteria

{
if (Low[i]<Min) Min=Low[i]:
if (High[i]>Max) Max=High[i];

}

if (................. &&Ask>Max)

{

Opn_B=true; //open Buy

}

if (................ &&Bid<Min)

{

Opn_S=true; //open Sell

}

___________________________________________________________________________________________

I'm sorry it's so ugly - I had to write it from memory as the code didn't work and I deleted it. But you, as a professional, should be understandable (I hope).

____________________________________________________________________________________________

You flatter me :)) I'm a beginner just like you...

extremumprice.mq4 
// Предназначен для использования в качестве примера в учебнике MQL4.
//--------------------------------------------------------------------
extern int  Quant_Bars  =30;                    // Количество баров
bool        OpnBuy      =false,
            OpnSell     =false;
//--------------------------------------------------------------------
int start()                                     // Спец. функция start
  {
   int i;                                       // Номер бара 
   double Minimum=Bid,                          // Минимальная цена
          Maximum=Bid;                          // Максимальная цена
 
   for(i=0;i<=Quant_Bars-1;i++)                 // От нуля (!) до..
     {                                          // ..Quant_Bars-1 (!)
      if (Low[i]< Minimum)                      // Если < известного
         Minimum=Low[i];                        // то оно и будет мин
      if (High[i]> Maximum)                     // Если > известного
         Maximum=High[i];                       // то оно и будет макс
     }
//--------------------------------------------------------------------

   if (iOpen(NULL,0,1)>Maximum)
      {
         OpnBuy =true:
         OpnSell=false;
      }
   if (iOpen(NULL,0,1)<Minimum)
      {
         OpnSell=true;
         OpnBuy =false:
      }   
//-------------------------------------------------------------------
//  А тут код открытия позиций.  if (OpnBuy)  {открываем Бай};
//                               if (OpnSell) {открываем Селл};
// Но обязательно нужно сделать проверку на существование уже открытой позиции,
// иначе они будут открываться на каждом тике пока присутствует сигнал...
   return;                                      // Выход из start()
  }
//--------------------------------------------------------------------
It goes something like this. Didn't check it, just wrote it on the spot...
 
artmedia70:

So here is the logic:

1. set the pending order with a magic number, say 101, and reset the flag to convert the order into a position, say ConvOrd=false;

2. check if the position with magic 101 has appeared; if so, set the conversion flag ConvOrd=true;

3. Check ConvOrd for truth and if ConvOrd==true,
we check if the position with magic number 101 exists - and if it is missing
it means it is already closed.

{deselect ConvOrd=false; set a new pending one;}.

I think we can do without flags...


I understand the logic, but I don't know how to implement it in code. I've tried a lot of variants but I haven't got any result. I think I'm a dummy. That's why I wrote here. On p.663 I showed you my code. If you are interested, please tell me how to improve it or at least tell me how to improve it. Thank you.
 
artmedia70, Roger thanks for your help. I think I figured it out, indeed the price at bar 0 cannot be lower or higher than minimum and maximum, I didn't think about that and added Ask as a value of Min variable, now it seems to work. artmedia70, compared to me, most are professionals))). Thanks again.
 
dimon74:
I understand the logic, but I don't know how to implement it in code. I've tried a lot of variants but I haven't got any result. I think I'm a dummy. That's why I wrote here. On p.663 I showed you my code. If you are interested, please tell me how to improve it or at least tell me how to improve it. Thank you.

Try a simpler way, when you put a SellStop order, remember the TakeProfit value and if the Bid falls below that price, put it on Buy.
 
Roger:

Try a simpler way, when you place a SellStop order, remember the TakeProfit value and if the Bid falls below that price, put it on Buy.
Thanks for the tip! I already tried this variant but it is not suitable for my strategy.
 
dimon74:
Thanks for the advice! I have already tried this option but it is not suitable for my strategy.
May the pros forgive me, but I'll still give you a list of useful functions from Igor Kim, maybe you'll build it yourself... :)
Files:
 

I don't understand why there are two locking positions at once. The logic is as follows:

When equity reaches a certain percentage of the previous profit, we close all positions... This works properly... Next...

If the equity falls by a certain percentage from its previous value, look for the position with the largest loss, identify who it is... Buy or Sell...

and open a locking position in the opposite direction with double lot. Then we look at their total profit (of the losing and locking position) and as soon as it gets bigger,

Let's say 10 pips, close them...

Logically, the equity should be checked on the next tick and if everything is OK, we continue working... If everything is OK again, we will have to look for the next sucker...

But for some reason it opens two locking positions at once... and Buy and Sell, and if the lot was 0.1, then the first locking opens double the lot = 0.2,

and the second one doubles it again and opens with 0.4 lot ... Respectively, what the hell lot is there, if they're fighting with each other for a place under the Sun ... :(

I'm attaching the code, maybe someone could poke me with their... finger.

//----------------- Закрытие позиций если эквити выросло на N процентов ---------------------------
            
   if (Equ_NEW>=Equ_OLD+EquPerc)                       // Новое эквити больше старого на процент прибыли..
   {                                         
//      ClosePosBySizeLossInCurrency(NULL, -1, -1, 0); // Закрытие всех убыточных позиций
      ClosePosFirstProfit(NULL, -1, -1);           // Закрываем все позиции, сначала прибыльные
      DeleteOrders(NULL, -1, -1);                  // Удаляем ордера
      Equ_NEW=AccountEquity();                     // Запоминаем новое значение эквити
      Equ_OLD=Equ_NEW;                             // и вписываем его в "старое"
      CountClsEQU++;                               // Увеличиваем счётчик кол-ва закрытий для ф-ции вывода информации
      LockBuy51 =true;                             // Разрешаем открытие локирующих
      LockSell51=true;                             // позиций Buy и Sell
      OpnBuy51  =true;                             // и вообще разрешаем открываться
      OpnSell51 =true;                             // в любую сторону... 
   }

//------------- Включение вывода убыточных позиций в ноль, если эквити упало на N процентов -----------------------
               
   if (Equ_NEW<=Equ_OLD-EquPerc/2)                 // Новое эквити меньше старого на столько-то процентов...
      {                                         
         Trade=false;                              // Запрещаем торговлю
//-------------- Закрытие двух позиций, если ранее был установлен лок на убыточную ------------- 
        
         if (OrderSelect(TicketLoss, SELECT_BY_POS, MODE_TRADES))    // Выбираем убыточную позицию (если её тикет
            {                                                        // ранее был сохранён в TicketLoss)
               double prloss=OrderProfit()+OrderSwap();              // Размер профита убыточной позиции
               int typeloss =OrderType();                            // Тип убыточной позиции
               int mnloss   =OrderMagicNumber();                     // Magic убыточной позиции
            }
         if (OrderSelect(TicketLock, SELECT_BY_POS, MODE_TRADES))    // Выбираем локирующую позицию (если её тикет
            {                                                        // ранее был сохранён в TicketLock)
               double prlock=OrderProfit()+OrderSwap();              // Размер профита локирующей позиции
               int typelock =OrderType();                            // Тип локирующей позиции
            }
         if (prloss+prlock>=10*Point)                                // Если их суммарный профит больше 10 пунктов
            {
                ClosePositions(NULL, typelock, 5100);           // Закрываем локирующую позицию
               ClosePositions(NULL, typeloss, mnloss);         // Закрываем убыточную позицию
            }
//--------------- Поиск убыточной позиции и установка локирующей -------------------------  
       
         double Loss=0;                                        // Последнее значение убытка
         int    i, k=OrdersTotal(), OrdTicket=-1;

         for (i=k-1; i>=0; i--) {                              // Цикл по всем ордерам терминала
            if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
               if ((OrderProfit()+OrderSwap()<0)) {            // Если профит позиции меньше 0
                  if (Loss>OrderProfit()+OrderSwap()) {        // Если последнее значение убытка больше убытка позиции  
                     Loss=OrderProfit()+OrderSwap();           // Значит тут убыток больше, запоминаем как последнее
                     OrdTicket=i;                              // Запоминаем номер убыточной позиции
                  }
               }
            }
         }
            if (OrdTicket>=0) {
               if (OrderSelect(OrdTicket, SELECT_BY_POS, MODE_TRADES)) {   // Выбираем позицию по тикету
                  TicketLoss=OrdTicket;                                    // Запоминаем как тикет убыточной позы
                  if (OrderType()==OP_BUY)                                 // Если её тип Бай
                     {
                        Magic=5100;                                              // Задаём магик... 
                        New_Comm="Sell_M5_Стратегия_1_Локирующая позиция";       // Задаём комментарий для позиции
                        Lots_New=NormalizeLot(OrderLots()*2, False, NULL);       // Увеличим лот в два раза
                        if (!ExistPositions(NULL, OP_SELL, 5100, 0)){            // Если нет локирующего Sell
                        OpenPosition(NULL,OP_SELL,Lots_New,0,pb-tp*100*po,Magic,New_Comm);} // Открываем локирующий...
                        if (ExistPositions(NULL, OP_SELL, 5100, 0))              // Проверяем, заодно и выбираем её
                              {TicketLock=OrderTicket();}                        // Сохраняем тикет локирующего Sell
                     }
                  if (OrderType()==OP_SELL)
                     {
                        Magic=5100;                                              // Задаём магик... 
                        New_Comm="Buy_M5_Стратегия_1_Локирующая позиция";        // Задаём комментарий для позиции
                        Lots_New=NormalizeLot(OrderLots()*2, False, NULL);       // Увеличим лот в два раза
                        if (!ExistPositions(NULL, OP_BUY, 5100, 0)){             // Если нет локирующего Buy
                        OpenPosition(NULL,OP_BUY,Lots_New,0,pa+tp*100*po,Magic,New_Comm);} // Открываем локирующий...
                        if (ExistPositions(NULL, OP_BUY, 5100, 0))               // Проверяем, заодно и выбираем её
                              {TicketLock=OrderTicket();}                        // Сохраняем тикет локирующего Buy
                     }
               }
            }
         }

Starting from

//------------- Включение вывода убыточных позиций в ноль, если эквити упало на N процентов -----------------------

...there's a joint somewhere...

 

PAGE NUMBER "666" :-)

 
Scary... Whoo!!!
Reason: