Lot calculation by Vince

 

Ported from

Roman 14.08.2011 06:37


Hey guys, please advise, I am looking for optimal f (for lot volume calculation) by geometric mean method using R.Vince's method.

The task: go through the orders history and with increment f = 0.01 from 0.01 to 1, find its optimal value where TWR is maximal.

the bottom two formulas, and the value of the biggest loss on a trade is known to be D=-458:

which enumeration cycles, in particular to find the optimal f and where in the code, additionally, to organise.

Here is the starting code in int deinit() . It prints in strategy tester about profit properly.

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//--- Расчет оптимального f ---

   double SUMM, MUL, HPR, TWR, G;   
   double D=-458;
   int orderIndex;
   for (orderIndex = (OrdersHistoryTotal() - 1); orderIndex >= 0; orderIndex--)
   {   
      if (!OrderSelect(orderIndex, SELECT_BY_POS, MODE_HISTORY))
      {
         Print("Ошибка при доступе к исторической базе (",GetLastError(),")");
         continue;
      }
   
      if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != magic) || (OrderCloseTime()==0))
      {
         continue;
      }  
     
         int lastType = OrderType();
         double lastLots = OrderLots();
         double lastProfit = OrderProfit() + OrderSwap(); 
         SUMM=SUMM+lastProfit;    
    }           
    
  Print("Профит = ", SUMM);  
  
  return(0);
  }

 
Vinin:

Transferred from

Made the following f, to calculate optimal f according to R. Vince, as he has in his book:

//---------переменные для расчета лота по оптимальному f Ральфа Винса
int Mas_Outcome_of_transactions [10000]; // Массив профитов/убытков закрытых позиций
extern double D = -628;                  // максимальный убыток по сделке

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
  if(Monitor==true)
    {
    for(int a=0;a<=3;a++)
      {
      string N=DoubleToStr(a,0);
      ObjectDelete(N);
      } 
    }
//----
//--- Расчет оптимального f ---
   int Qnt=0;                                          // Счётчик количества ордеров   
   ArrayInitialize(Mas_Outcome_of_transactions,0);     // Обнуление массива
   double f=0.01, SUMM, MUL, HPR, TWR_Rez=0, TWR=1.0, G;
   int orderIndex;
   for (orderIndex = 0; orderIndex<OrdersHistoryTotal(); orderIndex++)
   {   
      if (!OrderSelect(orderIndex, SELECT_BY_POS, MODE_HISTORY))
      {
         Print("Ошибка при доступе к исторической базе (",GetLastError(),")");
         continue;
      }
   
      if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != magic) || (OrderCloseTime()==0))
      {
         continue;
      }  
         Qnt++;                               // увеличиваем счетчик закрытых ордеров
         int lastType = OrderType();
         double lastLots = OrderLots();
         double lastProfit = OrderProfit() + OrderSwap(); 
        
         Mas_Outcome_of_transactions[Qnt] = lastProfit; // Заполняем массив профитом/лоссом по всем закрытым позициям 
         SUMM=SUMM+lastProfit;    
         //TWR = TWR*(1+f*(-lastProfit/(D)));
    }           
 //  Print("Закрытых позиций = ", Qnt, " Профит/лосс = ", SUMM);  
 
   for (f = 0.01; f<=1.0; f=f+0.01)//цикл перебора переменной f для поиска оптимального ее значения,при котором TWR-максимально
     {  
          
          for ( orderIndex = 1;orderIndex<Qnt; orderIndex++) //при заданной f проходим по всем закрытым ордерам
            {                                                // и считаем относительный конечный капитал (TWR)
             TWR = TWR*(1+f*(-Mas_Outcome_of_transactions[orderIndex]/(D))); // TWR - это произведение всех HPR
             //if (TWR>TWR_Rez) {TWR_Rez = TWR; Print(" TWR = ",TWR_Rez, " при f = ", f);}  
             //   else break;       
            }
          if (TWR>TWR_Rez) {
              TWR_Rez = TWR;
              G=MathPow (TWR_Rez, 0.001988); // 1/503 сделки по данной торговой системе, как в книжке: в степени 1/N 
              Print(" TWR = ",TWR_Rez," G = ",G, " при f = ", f);} // если текущий TWR > результирующего, 
              else break;    // то результирующий делаем равным текущему, иначе переходим на след итерацию цикла по f                                  
      }      
             
   Print("Закрытых позиций = ", Qnt, " Нетто Профит/лосс = ", SUMM, " У последней ",Qnt, " закрытой позы профит/лосс = ", 
        Mas_Outcome_of_transactions[Qnt]);     
  
  return(0);
  }

Can you tell me, what does the second line from the top, TWR=1.#INF, mean in the logbook, after testing the EA ?

What is it? - Out of range double ?

If this is the case, then how to calculate the optimal f ?

 
Roman.:

I have made the following function, to calculate optimal f according to R. Vince, as in his book:

Can you tell me, what does the second line from the top, TWR=1.#INF, mean in the logbook, after testing the EA ?

What is it? - Out of range double?

If so, in that case how to calculate the optimal f ?


3289
Rosh 26.10.2005 20:49
And numbers "1.INF", "1.IND" mean either too high in modulo values or undefined value of 0/0 type (I think so).

4464
Slawa 27.10.2005 09:59
And "1.INF", "1.IND" means either too big values in module or undefined value of 0/0 type (I think so).

yes, that's right. it's a float order overflow (1.INF) and a double order overflow (1.IND). you should check the divisor by 0 before dividing
 

Anton Trefolev http://forum.alpari.ru/member.php?u=56027 worked on optimal f, you can ask him. A not unknown person who once raised 11000% in (as far as I remember) 3 months. Then the oxygen was cut off to him by widening the spread on the overnight cross. Nevertheless he managed to get his account to over 100k, after which he had to close the account.

 
Vinin:

3289
Rosh 26.10.2005 20:49
And numbers "1.INF", "1.IND" mean either too big in modulo values, or undefined value like 0/0 (I think so).

4464
Slawa 27.10.2005 09:59
And numbers "1.INF" and "1.IND" mean either too high values modulo or undefined value of 0/0 type (I think so).

yes, exactly. this is a float order overflow (1.INF) and a double order overflow (1.IND). before dividing, you need to check the divisor for 0


That's the thing - there is no division, just multiplication (using Vince's formula, that's all).

So, using mql, we cannot solve this question (correct calculation of TWR), right?

I.e. using ddl, matcad, etc.?

 
Vinin:

3289
Rosh 26.10.2005 20:49
And numbers "1.INF", "1.IND" mean either too big in modulo values, or undefined value like 0/0 (I think so).

4464
Slawa 27.10.2005 09:59
And "1.INF" and "1.IND" numbers mean either too high values modulo or undefined value of 0/0 type (I think so).

yes, exactly. this is a float order overflow (1.INF) and a double order overflow (1.IND). you have to check the divisor by 0 before dividing


What happens when order float (1.INF) overflows?

Are subsequent iterations of f loop interrupted with the current result or does the loop keep on counting? I'm not interested in the numerical value of TWR, I'm interested in the value of f obtained through multiplication with cumulative total TWR.

In this piece of code:

for (f = 0.01; f<=1.0; f=f+0.01)//цикл перебора переменной f для поиска оптимального ее значения,при котором TWR-максимально
     {  
          
          for ( orderIndex = 1;orderIndex<Qnt; orderIndex++) //при заданной f проходим по всем закрытым ордерам
            {                                                // и считаем относительный конечный капитал (TWR)
             TWR = TWR*(1+f*(-Mas_Outcome_of_transactions[orderIndex]/(D))); // TWR - это произведение всех HPR                
            }
          if (TWR>TWR_Rez) {
              TWR_Rez = TWR;
              G=MathPow (TWR_Rez, 0.001988); // 1/503 сделки по данной торговой системе, как в книжке: в степени 1/N 
              Print(" TWR = ",TWR_Rez," G = ",G, " при f = ", f);} // если текущий TWR > результирующего, 
              else break;    // то результирующий делаем равным текущему, иначе переходим на след итерацию цикла по f                                  
      }      
 
Roman.:


The point is that there is no division, just multiplication (using Vince's formula, that's all).

So mql cannot solve this problem (correct calculation of TWR)?

I.e. solve with ddl, matcad, etc.?


Multiplication can also cause an overflow.
 
Vinin:

You can get an overflow during multiplication too.

I know that. But then how to calculate optimal f using its geometric mean method? I have written all formulas, all correctly in the code.
 
Roman.:

I know that. Then how can I calculate the optimum f using its geometric mean method? I've written all the formulas, all correctly in the code.

Probably just need to think about optimality. You can find variants of calculation.
 

How about comparing not TWR with the previous value (TWR_Rez), but comparing their geometric mean G and some G_Rez? After all, if the root of degree K of number_1 is greater than the root of the same degree K of number_2, then number_1 is greater than number_2! :))))))

And already calculating the root (variable G) there will be no overflow, if the product is indeed divided into elements (why bother with parts) and take the root from each element. After all, the root of the product is equal to the product of the roots of its factors! :)))

It will increase calculation time, but there will be no overflow and no fuss with it. In addition, there will be a noticeable increase in calculation accuracy.

If you want to print TWR variable, store its size in an additional variable of int type, and use Print to print TWR size, for example: "89605994539435e+1234121". But do you need it?

 
Roman.:
I know that. Then how can I calculate the optimum f using its geometric mean method? I've got all the formulas right in the code.
I'll have to fiddle with calculating the geometric mean.
Reason: