[ARCHIVE] Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 3. - page 509

 

edyuson:
Как зделать, чтоб не сразу умножал, а скажем через два-три раза? Пример: лот=0,01, еще - 0,01, еще - 0,01 и только после умножать. Подскажите, если не много возни. Спасибо.

sergeev:

make an int counter and add +1 at each opening.

Once the correct counter value is set, allow to do lot*koef as well.


Yes, it's not as easy as I thought, now it's starting to occur. And the cycle: lot-0.01, lot-0.01, lot-0.01 and only after multiplying lot-0.02, lot-0.02, lot-0.02 further: lot-0.04, lot-0.04, lot-0.04 .... should be interrupted by profit and continue with lots. There were some variants from the guys on the other forum about this: You could declare double koef[]={ 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1 . 0, 1.0, 2.0 .......} - as an array, filling it with the required coefficients, and a static or global variable int k=0;
Then lot=lot*koef[k++]; Starting series: k=0;

and such:
int k = 1;
int koef = 3;
if (k/koef == k) { lot*=2; k++; } but everything is wrong.

I tried a counter like: int j;
for(j=0; j<15; j++)
, but again it is not the same. Here it is all:
int X=0;
double S = 0.0000;
extern double lot=0.01;
extern double koef=2.0;
extern int SL=30;
extern int TP=120;
double dl;
double a;
int init()
{
a=lot;
return(0);
}
int deinit()
{
return(0);
}

int start()

{
if(OrdersTotal() == 0 && X==1)
{
if (Close[0]>dl){lot=a;}
X=0;
}

if(OrdersTotal() == 0 && X==2)
{
if (Close[0]<dl){lot=a;}
X=0;
}


if (OrdersTotal() == 0 && Close[1]>Open[1])
{
dl=Close[0];
OrderSend(Symbol(),OP_BUY,lot,Ask,3,Ask-SL*0.0001,Ask+TP*0.0001,",14774,0,Blue);
//--------------------------------------------------------------------

lot=lot*koef;
X=1;
}

if(OrdersTotal() == 0 && Close[1]<Open[1])
{
dl=Close[0];
OrderSend(Symbol(),OP_SELL,lot,Bid,3,Bid+SL*0.0001,Bid-TP*0.0001,",14774,0,Red);
//sudy some haler may help
lot=lot*koef;

X=2;
}
}
return(0);
//It's just a martin

 

Thanks, but look, there are two prices, one is the opening price of the order, and the other is the stop loss price, the number of points to the stop loss and the price of the point are known. How do I calculate the lot size so that the loss would be 10% of the deposit if the price reaches stop loss? I am just not good with figures.

I also do not understand

For cross rates, the point value, expressed in dollars, is calculated by the formula
PIP = LOT_SIZE * TICK_SIZE * BASE_QUOTE / CURRENT_QUOTE,
where LOT_SIZE is the lot size, TICK_SIZE is tick size, BASE_QUOTE is the current quote of base (first) currency to US dollar, CURRENT_QUOTE is the current rate of the pair.

How do you understand this first currency to US dollar?

 

Yes... tight... :-)

the base (first) currency to the US dollar, is, in the example GBP to JPY - GBP/JPY, would beGBP/USD

I redid this script, which is what you need with the calculation of the traded position volume depending on the amount of capital and stop-loss size.

You also need it - "I faced a problem and I have been struggling for three days already and cannot solve it. In the finished Expert Advisor I decided instead of a lot to enter the % risk, so I need to calculate the lot to stop, for example at 10 000 depo the risk of 1% at a stop of 100 points it will be about 0.1 lot and here at 200 lot stop the lot should be 0.05, so the 1% risk has remained at the same level. I hope everything is clear. And here you are writing:

"How do I calculate the lot size so that the loss would be equal to 10% of the deposit, for example, if the price reaches a stop loss? I'm just not good with numbers. "

So I modified the lot calculation function from the tutorial - its description and approach is the same, only instead of lot calculation by percentage of deposit size, the traded lot is calculated exactly by your (given by me in this example - see script, link above) conditions:

extern string A0 = "Параметры ММ и мониторинга";
extern double Lots = 0;           // Стартовый лот = 0 для использования максимального риска на капитал в процентах, в зависимости от величины стоп-лосса
extern int StopLoss = 1000;
extern int TakeProfit =4000;      // TakeProfit для новых ордеров (пунктов)
extern  double MaxRisk = 10;      // риск на капитал в %
                                  // рассчитываем объем позиции взависимости от размера стопа, при заданном риске
                                  // например при депо 10 000 риск 1% при стопе 100 пп это будет примерно лот 0.1,
                                  // при стопе 200 пп уже лот должен быть 0.05, для того чтобы риск 1% остался на том же уровне

int start()
{    
   //----------------------------------СТАРТ------------------------------------------------------------------------------------- 
 
// ...  

//----------------------------------Расчет объема лота------------------------------------------------------------------------ 
  if (Lot(StopLoss)==false)  
                        {
                          Comment(" Пополните счет. Не хватает средств на минимальный лот. Советник остановлен.");// Если средств не хватает на мин, то выход
                          Print  ("Не хватает средств на минимальный лот. Lots_New = ",Lots_New, " AccountFreeMargin() = ", AccountFreeMargin()); 
                                                                                                   // Если средств не хватает на мин, то выход
                          return (0);
                        }  
// ---------НОРМАЛИЗУЕМ НОВЫЕ РАСЧЕТНЫЕ ЛОТЫ И ОТКРЫВАЕМ ОЧЕРЕДНУЮ ПОЗИЦИЮ...                          
   Lots_New = NormalizeLots(Lots_New);      

//... здесь условия на открытие поз и установка ордеров

}//------------------------------------------Конец Старт-----------------------------------------------------

//+------------------------------------------------------------------+
//| Нормализация лота                                                |
//+------------------------------------------------------------------+

double NormalizeLots(double lot)
{
   double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
   double lots = NormalizeDouble(lot / lotStep, 0) * lotStep;   
   lots = MathMax(lots, MarketInfo(Symbol(), MODE_MINLOT));
   lots = MathMin(lots, MarketInfo(Symbol(), MODE_MAXLOT));   
   return (lots);
}

//--------------------------------------------------------------------
// Lot.mqh
// 
//--------------------------------------------------------------- 1 --
// Функция вычисления количества лотов.
// Глобальные переменные:
// double Lots_New - количество лотов для новых ордеров (вычисляется)
// double Lots     - желаемое количество лотов, заданное пользовател.
// double  MaksRisk  - процент риска
// Возвращаемые значения:
// true  - если средств хватает на минимальный лот
// false - если средств не хватает на минимальный лот
//--------------------------------------------------------------- 2 --
bool Lot(int sl)                               // Позовательская ф-ия
  {
   string Symb   =Symbol();                    // Финансовый инструм.
   double One_Lot=MarketInfo(Symb,MODE_MARGINREQUIRED);//Стоим. 1 лота
   double Min_Lot=MarketInfo(Symb,MODE_MINLOT);// Мин. размер. лотов
   double Max_Lot =MarketInfo(Symbol(),MODE_MAXLOT);
   double Step   =MarketInfo(Symb,MODE_LOTSTEP);//Шаг изменен размера
   double Free   =AccountFreeMargin();         // Свободные средства
   double LotVal =MarketInfo(Symbol(),MODE_TICKVALUE);//стоимость 1 пункта для 1 лота
   

//--------------------------------------------------------------- 3 --
   if (Lots > 0)                                 // Лоты заданы явно..
     {                                         // ..проверим это
      double Money=Lots*One_Lot;               // Стоимость ордера
      if(Money<=AccountFreeMargin())           // Средств хватает..
         Lots_New=Lots;                        // ..принимаем заданное
      else                                     // Если не хватает..
         Lots_New=MathFloor(Free/One_Lot/Step)*Step;// Расчёт лотов
     }
//--------------------------------------------------------------- 4 --
  else                                        // Если лоты не заданы
     {                                         // то берём процент 
                                               // Желаем. колич.лотов:
                                               
      Lots_New =MathFloor((Free*MaxRisk/100)/(sl*LotVal)/Step)*Step;
      if(Lots_New<Min_Lot) Lots_New=Min_Lot;
      if(Lots_New>Max_Lot) Lots_New=Max_Lot;
      Print ("Lot_New в ф-ии Lots = ",Lots_New, "ширина канала = ",sl, "Point  = ",Point);
     }
//--------------------------------------------------------------- 5 --
   if (Lots_New < Min_Lot)                     // Если меньше допуст..
      Lots_New=Min_Lot;                        // .. то миниамальный
   if (Lots_New*One_Lot > AccountFreeMargin()) // Не хватает даже..
     {                                         // ..на минимальн. лот:(
      Print ("Не хватает средств на минимальный лот.  Lots_New = ",Lots_New, " AccountFreeMargin() = ", AccountFreeMargin());  // Сообщение..
      return(false);                           // ..и выход 
     }
   return(true);                               // Выход из польз. ф-ии
  }
//--------------------------------------------------------------- 6 --
 
Reshetov:
static int Kvadrat = 0;



I tried this method. Now during the whole testing period one pending STOPLOSS order has opened and that's it...maybe my terminal is glitchy?

The program is supposed to find maximum and minimum prices every day, from 7 to 9 am and put a stop order at these levels.

Files:
 
mamba5:


I tried this method. Now during the whole testing period one pending STOPLOSS order has opened and that's it...maybe my terminal is glitchy?

Do you have trouble looking in the log to see what exactly is glitching?
 

Hello.

Has anyone had any problems with the function

IsDemo()

?

I always get 1 result - that the account is real (no matter if it is real or demo).

 
nemo811:

Hello.

Has anyone had any problems with the function

?

I always get 1 result - my account is real (no matter if it is real or demo).

I put an EA on a chart with a code on a demo account:

int start()
  {
//----
   if (IsDemo()) {
      Print("Это демо");
      return(0);
   }
   Print("Это не демо");
   
//----
   return(0);
}
Writes in the magazine: "This is a demo.
 
Reshetov:

I have a demo account with an EA with code on the chart:

It writes in the log: "This is a demo.

I have a demo on a phibogroup - for some mysterious reason it says I'm on a real account. In your version it shows - This is not a demo.

It turns out that somehow the DC itself is perverted

 
nemo811:

I have a demo on phibogroup - for some mysterious reason it says I'm on real. In your version of the picture - It's not a demo.

It turns out that somehow the DC itself has become perverted

Some brokers provide one server for both demo and for real. Check with the broker's support.
 
Reshetov:
Some brokers have one server for both demo and real. Check with your broker's support department.

Thank you.

Reason: