c++cmql4metatrader4mql5

How to divide a number into several, unequal, yet increasing numbers [ for sending a PlaceOrder( OP_BUY, lots ) contract XTO ]


I try to create an MQL4-script (an almost C++ related language, MQL4) where I want to divide a double value into 9 parts, where the fractions would be unequal, yet increasing

My current code attempts to do it this way (pseudo-code) :

   Lots1 = 0.1;
   Lots2 = (Lots1 / 100) * 120;//120% of Lot1
   Lots3 = (Lots2 / 100) * 130;//130% of Lot2
   Lots4 = (Lots3 / 100) * 140;//140% of Lot3
   Lots5 = (Lots4 / 100) * 140;//140% of Lot4
   Lots6 = (Lots5 / 100) * 160;//160% of Lot5
   Lots7 = (Lots6 / 100) * 170;//170% of Lot6
   Lots8 = (Lots7 / 100) * 180;//180% of Lot7
   Lots9 = (Lots8 / 100) * 190;//190% of Lot8
   ...

or better :

double Lots = 0.1;   // a Lot Size
double lot  = Lots;
...
                   /* Here is the array with percentages of lots' increments
                                                         in order */
int AllZoneLots[8] = { 120, 130, 140, 140, 160, 170, 180, 190 }; // 120%, 130%,...

                  /* Here, the lot sizes are used by looping the array
                                         and increasing the lot size by the count */
for( int i = 0; i < ArraySize( AllZoneLots ); i++ ) {
                        lots = AllZoneLots[i] * ( lots / 100 ) *;
 // PlaceOrder( OP_BUY, lots );
}

But, what I want is to just have a fixed value of 6.7 split into 9 parts, like these codes do, yet to have the value increasing, rather than being same... e.g, 6.7 split into :

double lots = { 0.10, 0.12, 0.16, 0.22, 0.31, 0.50, 0.85, 1.53, 2.91 };
            /* This is just an example
                            of how to divide a value of 6.7 into 9, growing parts

Solution

  • This can be done so as to make equal steps in the values. If there are 9 steps, divide the value by 45 to get the first value, and the equal step x. Why? Because the sum of 1..9 is 45.

    x = 6.7 / 45
    

    which is 0.148889

    The first term is x, the second term is 2 * x, the third term is 3 * x etc. They add up to 45 * x which is 6.7, but it's better to divide last. So the second term, say, would be 6.7 * 2 / 45;

    Here is code which shows how it can be done in C, since MQL4 works with C Syntax:

    #include <stdio.h>
    
    int main(void) {
        double val = 6.7;
        double term;
        double sum = 0;
        for(int i = 1; i <= 9; i++) {
            term = val * i / 45;
            printf("%.3f ", term);
            sum += term;
        }
        printf("\nsum = %.3f\n", sum);
    }
    

    Program output:

    0.149 0.298 0.447 0.596 0.744 0.893 1.042 1.191 1.340 
    sum = 6.700