Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1800

 

What is the DecreaseFactor in the standard MT advisor on mashcats?

lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
 
Nerd Trader #:

It's strange, the buttons are there now. And the code clutter, because it's a draft. Anyway, I've already made a working version, the last thing left is to delete the buttons, here again this shit started: the delete function doesn't find any of the 4 objects.

Clicking on the button creates all the lines:

If the button is pushed - delete:

What a load of crap is written, I'm sorry to say.

 
Artyom Trishkin #:

And you don't need to watch the events. They don't work at all in the tester. You have to watch the status.

UPD. Not modest of course, but if you had listened to my hints for once, you would have done everything long ago. Properly and without the crutches of a multi-storey.

But everyone chooses the abyss they want to plunge into.

Mihail Matkovskij #:

To use the debug in the tester, learn to write in MQL5. Everything works there.

There's no such thing as renaming an object. Think of it as replacing an existing object with a new one.

This cannot be. Your code looks like a mess of things. That's probably why you are experiencing lags with the buttons. Like I told you before, start with something simple. Don't overcomplicate things. And gradually complicate it when the simple starts to work and you're confident in it.

And how do I see the states if they are triggered by event (by click)? Yes, but I'm writing in mql4, it's the same as saying "learn to write in c# where debug works".

"Correct and without multi-storey crutches. "So hiding objects is just crutches.

All in all I've done, everything works https://gist.github.com/satorkain/0cf7a8df8ec1f4b3191defd04c94a418
By clicking on button all lines are created at once, then they are hidden and only one is left depending on button panel location. Further lines are hidden/shown depending on the location of the cursor relative to the price.

P.S.

If it wasn't for crooked mql4 I wouldn't have had to come up with this nonsense about hiding objects, everything should have worked the first time with deleting/renaming objects.

stop order button (public).mq4
stop order button (public).mq4
  • gist.github.com
GitHub Gist: instantly share code, notes, and snippets.
 
Nerd Trader #:

And how do I see states if they are triggered by event (by click)? Yes but I write in mql4, it's the same as saying "learn to write in c# where debug works".

"Correct and without multi-storey crutches. " So hiding objects is just crutches.

All in all I've done, everything works https://gist.github.com/satorkain/0cf7a8df8ec1f4b3191defd04c94a418
By clicking on button all lines are created at once, then they are hidden and only one remains depending on button panel location. Further lines are hidden/shown depending on the location of the cursor relative to the price.

P.S.

If it wasn't for the crooked mql4, I wouldn't have had to come up with this nonsense about hiding objects, everything should have worked the first time with deleting/renaming objects as well.

Hiding an object is just the method recommended by the developer. And there is a special property for it. To see the state, you need to look at the "State" property of the button.

What's crooked here is your logic and substitution of notions - you take developer's recommended means as a crutch, and you take constant voracious object creation/deletion as pure code, but that's exactly what's a crutch, bypassing recommended fast method.

By the way, to quickly make an object on top of all the others, you have to make it invisible, and immediately visible - this will override its position in the object list, and it will be at the top.

ZS. And even there, on the git, you published the code with a C-minus. Totally error-prone. Once one line is not created, your whole thing collapses. That was immediately apparent. You create lines in the event handler - what for? What do you need OnInit() for? You created it, checked its success, set a flag and hide it. In OnDeinit() you have deleted objects created by your program. You also need the name prefix for this.

You only show and hide in the event handler - there should be no building. For your case - exactly.

I would be ashamed to publish such thing in public domain on git. But that's for me.

What about you? Is it okay for people to take advantage of it?

 
Artyom Trishkin #:

Hiding an object is exactly the developer's recommended method. And there is a special property for it. To see the state, you need to look at the "State" property of the button.

What's crooked here is your logic and substitution of notions - you take developer's recommended means as a crutch, and you take constant voracious object creation/deletion as pure code, but that's exactly what's a crutch to bypass the recommended quick method.

By the way, to quickly make an object on top of all the others, you have to make it invisible, and immediately visible - this will redefine its position in the object list, and it will be at the top.

ZS. And even there, on the git, you published the code with a C-minus. Totally error-prone. Once one line is not created, your whole thing collapses. That was immediately apparent. You create lines in the event handler - what for? What do you need OnInit() for? You create it, check its success, set a flag and hide it. In OnDeinit() you have deleted objects created by your program. You also need the name prefix for this.

You only show and hide in the event handler - there should be no building. For your case - exactly.

I would be ashamed to publish such thing in public domain on git. But that's for me.

What about you? Is it okay for people to take advantage of it?

Voracious to create 1 line of 4 as needed? :) What if there are 200 lines? Will it be economical to create them all at once according to your logic? And how it was conceived by the developers is known only to them, and conceived in a very non-intuitive way. As if nothing incredible or illogical was required. How could I have known that I should work with objects only in this way and not any other way? Maybe from a textbook on mql4? I doubt that this point is explained there.

At least, it works as it was intended :) It's in brackets in the title (public), so it's not complete yet, but yes, there is no check to create objects, let's fix it. And I posted it on git only because I couldn't remember paste bin. Ashamed? The Git was created for people to learn, exchange experiences, share code, working or not, makes no difference, anyone can make a fork and make changes if they are not happy with something.

Here you are, 250 objects have been created and stored in memory for the duration of the Expert Advisor. All right, well, thank you, I'll know. This is what I mean by "non-intuitive logic". For example, in the tutorial about OnInit(), you can read only that the function is processed during initialization of the Expert Advisor/indicator.

 
Nerd Trader #:


Let me tell you a secret. You can create as many as 1,000 objects or more, as long as you don't have a 'calculator'. But it can do it too. A calculator is a computer with 4GB RAM. Anything below that is "grandma's calculator"... :) So you can create objects all at once or one at a time. It makes no difference. But without fanaticism.

That way, everything works for everyone if you do it wisely!...

 
Nerd Trader #:

Voraciousness to create 1 line of 4 as needed? :) What if there are 200 lines? Would it be economical to create them all at once according to your logic? And how it was conceived by the developers is known only to them, and conceived in a very non-intuitive way. As if nothing incredible or illogical was required. How could I have known that I should work with objects only in this way and not any other way? Maybe from a textbook on mql4? I doubt that this point is explained there.

At least, it works as it was intended :) It's in brackets in the title (public), so it's not complete yet, but yes, there is no check to create objects, let's fix it. And I posted it on git only because I couldn't remember paste bin. Ashamed? The Git was created for people to learn, exchange experiences, share code, working or not, makes no difference, anyone can make a fork and make changes if they are not happy with something.

Here you are, 250 objects have been created and stored in memory for the duration of the Expert Advisor. All right, well, thank you, I'll know. This is what I mean by "non-intuitive logic". You can read in the tutorial, for example, about OnInit(), that the function is processed during initialization of an EA/indicator.

You can create as many objects as you need at the same time. At the time MT was not very developed in terms of drawing of indicator buffers, we had to draw 400 visible candlesticks with trend lines, for one candlestick we need 5 lines, 400*5=2000, plus one object for each one and so on. Altogether we got about 2500 objects. It worked without any dullness.

You do not quite understand the logic of working with objects, but you know how to argue. It's better to do the opposite.

 
Nerd Trader #:

Voraciousness to create 1 line of 4 as needed? :) What if there are 200 lines? Would it be economical to create them all at once according to your logic? And how it was conceived by the developers is known only to them, and conceived in a very non-intuitive way. As if nothing incredible or illogical was required. How could I have known that I should work with objects only in this way and not any other way? Maybe from a textbook on mql4? I doubt that this point is explained there.

At least, it works as it was intended :) It's in brackets in the title (public), so it's not complete yet, but yes, there is no check to create objects, let's fix it. And I posted it on git only because I couldn't remember paste bin. Ashamed? The Git was created for people to learn, exchange experiences, share code, working or not, makes no difference, anyone can make a fork and make changes if they are not happy with something.

Here you are, 250 objects have been created and stored in memory for the duration of the Expert Advisor. All right, well, thank you, I'll know. This is what I mean by "non-intuitive logic". For example, in the tutorial about OnInit(), you can read only that function is processed during initialization of the Expert Advisor/indicator.

Welcome. I will try to explain it in simple Russian.

You are going on a fishing trip.

  1. At home you open the pantry, scratch your head and close it.
  2. You go fishing and you need a fishing rod.
  3. You go home to the storeroom to get a fishing rod.
  4. Went fishing, cast your rod and caught a fish, and then you needed a net
  5. Went home to the storeroom for the net
  6. Went fishing, picked up the fish you had caught and floated on the hook with the net, and you needed a container for storing the fish you had caught
  7. Go home for ..... Shall I continue?

Or you can take everything you need from the pantry (OnInit) straight away, fish without running around and, when you get home, put everything in the pantry and the fridge (OnDeinit).

You may have known about it here on the forum. You just need to listen and hear what you are told sometimes.

Otherwise you get a question, get an answer, say "bullshit" and do as you think.

You must first think over the question, ask questions, and then start editing.

Are you aware that the simplest thing in programming is printing code? And the lion's share of development is thinking about the logic.

 

I'm sorry to bring this up a second time.

But there is a problem that I cannot solve yet, namely

opening a series of orders (one after the other) on the same candlestick.

I need to prevent the EA from opening a new order on the same candlestick.

I thought about solving it using Sleep(), but Makar said it would be better not to stop the process.

problem.

The code now looks like this:

// Параметры советника
input string  sParametersEA = "";     // Параметры советника
input double  Lot           = 0.01;   // Количество лотов
input int     StopLoss      = 30;     // Уровень убытка
input int     TakeProfit    = 30;     // Уровень прибыли
input int     Slippage      = 3;      // Проскальзование (в пунктах)
input int     Magic         = 1;      // Индентификатор советника
input double  K_Martin1     = 2.0;    // Множитель мартин 1
input double  K_Martin2     = 2.0;    // Множитель мартин 2
input double  K_Martin3     = 2.0;    // Множитель мартин 3
input int     OrdersClose   = 5;      // Ограничение лотности мартин1
input int     OrdersClose2  = 5;      // Ограничение лотности мартин2
input int     DigitsLot     = 2;      // Точность лотности
// Параметры индикатора
input string  sParametersMA = "";     // Параметры индикатора
input int     PeriodMA      = 14;     // Период мувинга
input int     MovingShift   = 1;      // Сдвиг мувинга
// Глобальные переменные
string AC;
datetime Start;
double dMA;
double MaxMartinLot;
double MaxMartinLot2;
//+-----------------------------------------------------------------------------------------------+
int OnInit()
  {
Start          = TimeCurrent();
MaxMartinLot   = Lot*MathPow(1.4,OrdersClose);
MaxMartinLot2  = Lot*MathPow(K_Martin2,OrdersClose2);
AC             = StringConcatenate(" ", AccountCurrency());
return(INIT_SUCCEEDED);
  }
//+-----------------------------------------------------------------------------------------------+
void OnDeinit(const int reason)
  {

  }
//+-----------------------------------------------------------------------------------------------+
void OnTick()
  {
// Получим значение индикатора
   dMA = iMA(Symbol(), 0,PeriodMA, MovingShift, MODE_SMA, PRICE_CLOSE, 0); // MODE_SMA - простое усреднение , значение 0. PRICE_CLOSE- цена закрытия, значение 0.

// Если нет открытых ордеров, то входим в условие
      if(CountOrders()==0)
     {
// Если появился сигнал на покупку, то откроем ордер на покупку
      if(bSignalBuy() == true)
         vOrderOpenBuy();

// Если появился сигнал на продажу, то откроем ордер на продажу
      if(bSignalSell() == true)
         vOrderOpenSell();
     }
   }
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция проверки открытых оредров |
//+-----------------------------------------------------------------------------------------------+
int CountOrders() 
  {
   int cnt=0;
   int i=OrdersTotal()-1;
   for(int pos=i;pos>=0;pos--)
     {
      if(OrderSelect(pos, SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol()==_Symbol)
           {
            if(OrderMagicNumber()==Magic) cnt++;
           }
        }
     }
   return(cnt);
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция поиска сигнала на покупку |
//+-----------------------------------------------------------------------------------------------+
bool bSignalBuy()
  {
   if(dMA > Open[1] && dMA < Close[1])  //Open[1] и Close[1]- цены открытия и закрытия каждого бара текущего графика.
      return(true);

   return(false);
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция поиска сигнала на продажу |
//+-----------------------------------------------------------------------------------------------+
bool bSignalSell()
  {
   if(dMA < Open[1] && dMA > Close[1])
      return(true);

   return(false);
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                            Функция открытия ордера на покупку |
//+-----------------------------------------------------------------------------------------------+
void vOrderOpenBuy()
  {
// Тикет ордера
   int iOTi = 0;   

   iOTi = OrderSend(Symbol(), OP_BUY, LOT(), Ask, Slippage, 0, 0, "", Magic, 0, clrNONE);
   
// Проверим открылся ли ордер
   if(iOTi > 0)
// Есди да, то выставим уровни убытка и прибыли
      vOrderModify(iOTi);
   else
// Если нет, то получим ошибку
      vError(GetLastError());
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                            Функция открытия ордера на продажу |
//+-----------------------------------------------------------------------------------------------+
void vOrderOpenSell()
  {
// Тикет ордера  
   int iOTi = 0;   
//Print(bCheckOrders());
   iOTi = OrderSend(Symbol(), OP_SELL, LOT(), Bid, Slippage, 0, 0, "", Magic, 0, clrNONE);

// Проверим открылся ли ордер
   if(iOTi > 0)
// Есди да, то выставим уровни убытка и прибыли
      vOrderModify(iOTi);
   else
// Если нет, то получим ошибку
      vError(GetLastError());
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                                    Функция модификации ордера |
//+-----------------------------------------------------------------------------------------------+
void vOrderModify(int iOTi)
  {
   int    iOTy = -1;    // Тип ордера
   double dOOP = 0;     // Цена открытия ордера
   double dOSL = 0;     // Стоп Лосс
   int    iMag = 0;     // Идентификатор советника
   double dSL  = 0;     // Уровень убытка
   double dTP  = 0;     // Уровень прибыли

// Выберем по тикету открытый ордер, получим некоторые значения
   if(OrderSelect(iOTi, SELECT_BY_TICKET, MODE_TRADES))
     {
      iOTy = OrderType();
      dOOP = OrderOpenPrice();
      dOSL = OrderStopLoss();
      iMag = OrderMagicNumber();
     }

// Если ордер открыл данный советник, то входим в условие
   if(OrderSymbol() == Symbol() && OrderMagicNumber() == iMag)
     {
// Если Стоп Лосс текущего ордера равен нулю, то модифицируем ордер
      if(dOSL == 0)
        {
         if(iOTy == OP_BUY)
           {
            dSL = NormalizeDouble(dOOP - StopLoss * Point, Digits);
            dTP = NormalizeDouble(dOOP + TakeProfit * Point, Digits);

            bool bOM = OrderModify(iOTi, dOOP, dSL, dTP, 0, clrNONE);
           }

         if(iOTy == OP_SELL)
           {
            dSL = NormalizeDouble(dOOP + StopLoss * Point, Digits);
            dTP = NormalizeDouble(dOOP - TakeProfit * Point, Digits);

            bool bOM = OrderModify(iOTi, dOOP, dSL, dTP, 0, clrNONE);
           }
        }
     }
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                                      Функция обработки ошибок |
//+-----------------------------------------------------------------------------------------------+
void vError(int iErr)
  {
   switch(iErr)
     {
      case 129:   // Неправильная цена
      case 135:   // Цена изменилась
      case 136:   // Нет цен
      case 138:   // Новые цены
         Sleep(1000);
         RefreshRates();
         break;

      case 137:   // Брокер занят
      case 146:   // Подсистема торговли занята
         Sleep(3000);
         RefreshRates();
         break;
     }
  }
//+-----------------------------------------------------------------------------------------------+
double LOT()
{
   int n=0;
   int m=0;
   int v=0;
   double OL=Lot;
   for (int j = OrdersHistoryTotal()-1; j >= 0; j--)
   {
      if (OrderSelect(j, SELECT_BY_POS,MODE_HISTORY))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
         {
            if (OrderProfit()>0) 
            {

               if (n==0) OL=NormalizeDouble(OrderLots()+K_Martin1,DigitsLot);
               n++;
               
               if ((OL>=MaxMartinLot)&& (m==0)) OL=NormalizeDouble(OrderLots()*K_Martin2,DigitsLot);
               m++;
               
               if ((OL>=MaxMartinLot2) && (v==0)) OL=NormalizeDouble(OrderLots()*K_Martin3,DigitsLot);
               v++;
            }
            else
            {
               if (n==0) {return(Lot);}
               else {return(OL);}
            }
         }
      }
   }
   
   return(OL);
}
 
законопослушный гражданин #:

I need the EA not to be able to open a new order on the same candle.

void OnTick()
  {
  datetime cTime;
  static datetime time = 0;

  cTime = iTime(NULL, PERIOD_CURRENT, 0);

  if (time != cTime)
    time = cTime;
  else
    return;

// Получим значение индикатора
   dMA = iMA(Symbol(), 0,PeriodMA, MovingShift, MODE_SMA, PRICE_CLOSE, 0); // MODE_SMA - простое усреднение , значение 0. PRICE_CLOSE- цена закрытия, значение 0.

// Если нет открытых ордеров, то входим в условие
      if(CountOrders()==0)
     {
// Если появился сигнал на покупку, то откроем ордер на покупку
      if(bSignalBuy() == true)
         vOrderOpenBuy();

// Если появился сигнал на продажу, то откроем ордер на продажу
      if(bSignalSell() == true)
         vOrderOpenSell();
     }
   }
Reason: