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

 
eugggy:
I understand in general terms, but what does it mean if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))break; if no such order is selected, then abort or what?


OrderSelect (see https://docs.mql4.com/ru/trading/OrderSe lect) returns FALSE when the function fails. See https://docs.mql4.com/ru/basis/operators/bre ak for break operator.

This can be simplified to

OrderSelect(i,SELECT_BY_POS,MODE_TRADES);

the main thing is to select the order.

 
eugggy:


And to me it looks like absolutely different things. Could you insert this into your code if(Tip==OP_BUYSTOP||Tip==OP_SELLSTOP&&Minute()<59&&Minute()>57) OrderDelete(Ticket);

and if so, which part?


Without seeing your code, I can assume that instead (it all depends on your algorithm):

if(OrderType()==OP_BUYSTOP) OrderDelete(OrderTicket());
if(OrderType()==OP_SELLSTOP) OrderDelete(OrderTicket());
if(OrderType()==OP_BUYLIMIT) OrderDelete(OrderTicket());
if(OrderType()==OP_SELLLIMIT) OrderDelete(OrderTicket());

Only you need to put order in variables and correct brackets in condition with || and &&.

The Minute()<59&&Minute()>57 condition can be reduced to Minute()==58 or use >= or <=.

To force the closing of a pending order at the end of a period or at a certain time when setting it, you can specify the expiration date parameter - see https://docs.mql4.com/ru/trading/OrderSend. In this case you don't need to bother with programming its closing. And the order will be closed unconditionally without any correction for the lack of connection.

 
eugggy:

Yeah, lots of useful stuff. I could have done without the freebies, but it's a very intricately written textbook.
You see... I'm on the subject of how "they're talking now" :)

Freebie, dudes! Yo! Comon evry body!!!

I guess if the SC textbook was written like that it would be a 6+.

Sorry about the off-topic...

 
eugggy:

No, we don't need it instead, we need it in addition. I looked at the chart: sometimes the price does not go out of the High-Low channel and the pending orders remain. If they do not go out of the High-Low channel, they remain. The only thing you need is to close the pending ones before the new ones appear. As for the 1986 book, are you serious? I am ancient myself, but I think it is too much.


In addition, you have to write additional similar code. Somehow it seems to me that your code is a bit of a jumble.

I wasn't joking about the 1986 book. Again, if you want to learn the basics of programming, you need to learn them without clogging your head with modern language constructs. You need the basics. Computer science textbooks for high school, especially the first one, are methodically well-composed for "dumb" people. How, by whom, for whom and why modern textbooks are written is a separate topic

 

date time lots price

26 2010.01.05 12:24 sell 12 0.10 1.44026 1.44907 1.43526 0.00 3200.09
28 2010.01.05 13:21 buy 13 0.26 1.44326 1.43445 1.44826 0.00 3200.09
30 2010.01.05 15:34 sell 14 0.43 1.44026 1.44907 1.43526 0.00 3200.09
32 2010.01.05 16:27 buy 15 0.72 1.44326 1.43445 1.44826 0.00 3200.09
34 2010.01.05 17:18 sell 16 1.19 1.44026 1.44907 1.43526 0.00 3200.09

Here we have 5 open orders in the corresponding directions.

How to calculate the total margin for all open orders?

Pair: EURUSD, contract 100,000, leverage 100.

 
ikatsko:

date time lots price

26 2010.01.05 12:24 sell 12 0.10 1.44026 1.44907 1.43526 0.00 3200.09
28 2010.01.05 13:21 buy 13 0.26 1.44326 1.43445 1.44826 0.00 3200.09
30 2010.01.05 15:34 sell 14 0.43 1.44026 1.44907 1.43526 0.00 3200.09
32 2010.01.05 16:27 buy 15 0.72 1.44326 1.43445 1.44826 0.00 3200.09
34 2010.01.05 17:18 sell 16 1.19 1.44026 1.44907 1.43526 0.00 3200.09

Here are 5 open orders in the respective directions.

How do I calculate the total margin for all open orders?

Pair: EUROLLAR, contract 100000, leverage 100.

MarketInfo(Symbol(),MODE_MARGINREQUIRED);

Returns the amount of free funds needed to open 1 lot in a buy order, well look at the other ones, depending on your needs.

You may also find this useful:

double AccountFreeMarginCheck ( string symbol, int cmd, double volume)

Returns the amount of free funds remaining after opening the specified position at the current price on the current account. If there are not enough available funds, error 134 (ERR_NOT_ENOUGH_MONEY) will be generated.
 
Thanks for the quick reply, but I want to calculate the margin BEFORE these positions open! The strategy is an avalanche, I need to know if there will be a Stop Out after the respective positions open? The lot sizes of all upcoming lots are known in advance. I would like to know: how many orders (with known incremental lots in advance) will be possible to open?
 
ikatsko:
Thanks for the quick response, but I want to calculate the margin BEFORE these positions open! The strategy is an avalanche, I need to know if there will be a Stop Out after the corresponding positions are opened? The lot sizes of all upcoming lots are known in advance. I would like to know: how many orders (with known incremental lots in advance) can be opened?
// ==========================================================================
// ------------ Функция рассчёта величины лота для открытия позиции ---------
// Если лот превышает возможный для открытия позы, то он корректируется 
// ==========================================================================

double CorrectLots(double lt)
{
   double ltcorr;
   double pnt =      MarketInfo(Symbol(),MODE_POINT);
   double mspr =     MarketInfo(Symbol(),MODE_SPREAD);
   double dig =      MarketInfo(Symbol(),MODE_DIGITS);
   double MaxLot =   MarketInfo(Symbol(),MODE_MAXLOT);
   double MinLot =   MarketInfo(Symbol(),MODE_MINLOT);
   double StpLot =   MarketInfo(Symbol(),MODE_LOTSTEP);
   double OneLot =   MarketInfo(Symbol(),MODE_MARGINREQUIRED);
   double TradeMrg = NormalizeDouble(AccountFreeMargin()/4.0,dig);    // Свободные средства, разрешенные к торговле
   
   lt=MathAbs(lt);
   ltcorr=lt;                       // Зададим начальное значением ltcorr равным значению lt
   
   if (lt>MaxLot) ltcorr=MaxLot;   // Проверим превышение допустимых ...
   if (lt<MinLot) ltcorr=MinLot;   // ... значений лота
   
   double Money=ltcorr*OneLot+mspr*pnt;    // Вычисляем стоимость открываемой позы

   if (Money<TradeMrg)              // Если свободных средств больше, чем цена позиции - 
      {
         return(ltcorr);                                                            // ... возвращаем неизменённый лот
      }
   else if (Money>=TradeMrg)        // Если цена позиции равна или больше, чем есть свободных средств, то ...
      {
         ltcorr=MathAbs(MathFloor(TradeMrg/OneLot/StpLot)*StpLot);               // ... рассчитаем допустимый лот
         double MoneyCorr=ltcorr*OneLot+mspr*pnt;                      
         Print("Func CorrectLots: лот ",lt," скорректирован до ",ltcorr,
               " Стоимость позы до корректировки = ",Money,
               " Стоимость позы после корректировки = ",MoneyCorr
               ); 
         return(ltcorr);                                                         // ... и вернём его значение
      }
   Print("Func CorrectLots: лот вернули без изменений");
   if (lt>MaxLot) ltcorr=MaxLot;   // Проверим превышение допустимых ...
   if (lt<MinLot) ltcorr=MinLot;   // ... значений лота
   return(ltcorr);                            // Возврат изначального лота в непредусмотренных случаях с сообщением
}

Try and see what you can find out for yourself... :)

And, again.

double AccountFreeMarginCheck ( string symbol, int cmd, double volume)

I used this function in a custom EA which also uses a naked martingale.
I had to write a line before opening any position to make it more stable:

double lt;                           // Лот
// --------------------------------- +

lt=CorrectLots(lt*2);                // Умножаем лот на 2 с проверкой и коррекцией под допустимый размер лота

// ------- Открытие позы ----------- +
 
Artem, I need to calculate the margin myself, that is, I need to know the calculation formula. I don't need the terminal's answer about the current possibilities. I do know the formula, but there is something about calculating margin on overlapping positions! And I don't even know what overlapping positions are! I specifically gave an example where you can see that each successive position is opened in the opposite direction to the previous one. If you calculate the margin on open positions by summing up all the lots (and paste that amount into the formula), it does not match the actual reaction of the DC when it applies a Stop Out. I would like to calculate it the way the DC calculates it
 
ikatsko:
Artem, I need to calculate the margin myself, i.e. I need to know the calculation formula. I don't need the terminal's answer about the current possibilities. I do know the calculation formula, but there is some kind of peculiarity of margin calculation for overlapping positions!!! And I don't even know what overlapping positions are! I specifically gave an example where you can see that each successive position is opened in the opposite direction to the previous one. If you calculate the margin on open positions by summing up all the lots (and paste that amount into the formula), it does not match the actual reaction of the DC when it applies a Stop Out. I would like to calculate it the way the DC calculates it

Are overlapping positions not equal to locked positions? This is the margin required to maintain two open positions of equal volume but opposite direction. It is usually half the margin required to maintain one open position of the same size as one of the two locked positions.

I noticed it right away, but I didn't think it would confuse you...

For the same EA I calculated the margin this way, I don't know now, maybe it's wrong??? :

// ======================================================================
// -------------------------- Рассчёт свободной маржи -------------------
// ======================================================================
bool LastFreeMargin(string sy, int op, double lot)
{
   if (sy=="0" || sy=="") sy=Symbol();
   double FreeEqu  = AccountFreeMargin();                         // Вся маржа
   double FreeEqu4 = NormalizeDouble(Equ_Start/4.0, 2);           // Делим маржу на 4 (Средства для торговли)
   double CheckEqu = AccountFreeMarginCheck(sy, op, lot);         // Остаток всех средств после открытия позы 
   double EquTrade = FreeEqu-CheckEqu;                            // Средства, требуемые для открытия следующей
   
   if (FreeEqu4-EquTrade>0) return(true);
   else return(false);
}   

This is all that the DC returns to you:

MODE_MARGININIT 29 Initial margin requirement for 1 lot
MODE_MARGINMAINTENANCE 30 Amount of margin requirement to support open positions per 1 lot
MODE_MARGINHEDGED 31 Margin charged on overlapped positions per 1 lot
MODE_MARGINREQUIRED 32 Amount of free funds needed to open 1 lot to buy