Welcome Forex EA downloads & MT4/MT5 auto-trading resources — EAs, Gold EAs, quant tools and real-world automation.
Sign In Sign Up

CDouble and CDoubleVector - MetaTrader 5 Library - MT4/MT5 Resources

author EAcpu | 2 reads | 0 comments |

A library for common rounding methods used in MQL development, primitive wrapper classes for types (double) and vectors of CDouble objects. MQL5 and MQL4 are compatible!

Version 1.02: (2018.02.18)

The CDouble class wraps values ​​of the basic type double in objects. Additionally, this class also provides several methods and static methods for rounding doubles as well as arrays/collections of double type.

 Class Double: Public Object


 #include <double.mqh>


inheritance hierarchy

Virtual methods implemented/overridden from CObject class: type , load , save , compare .

Objects of type CDouble contain five data fields:

 String
 m_symbol
The symbol assigned to the class instance used to retrieve the rounding lot step size and tick size.
 double
 m_value
The raw double value assigned to the instance.
 Uchar
 m_step
Rounding steps are represented as char to reduce memory footprint. For example, 0.0025 becomes 25.
 Uchar
 m_bits
The number of digits after the decimal point.
 ENUM_PRECISION
 model
Mode of operation that locks the rounding method to a specific "step size".

Before we look further into the documentation, here's a practical example of a wrapper class:

 MQTick tick;
SymbolInformationTick ( _symbol ,tick);
  CDouble price = tick.ask - 0.0087263487676283476 ,
            sl = price - 500 * _views ,
            tp = price + 500 * _views ,
            Lot size = 5.25 / 3.78789 ;
Mql transaction request r={ 0 };
  r.symbol = _symbol ;
  r.price = price.AsRoundedTick();
  r.sl = sl.AsRoundedTick();
  r.tp = tp.AsRoundedTick();
  r.volume=lots.AsRoundedLots();

...

Another example using static library methods:

MQTick tick;
SymbolInformationTick ( _symbol ,tick);
Mql transaction request r={ 0 };
  r.symbol = _symbol ;
  r.price=tick.ask - 0.0087263487676283476 ,
  r.sl = price - 500 * _views ,
  r.tp = price + 500 * _views ,
  r.Volume = 5.25 / 3.78789 ;
  ...
  CDouble::RoundTradeRequest(r);
//Automatically round price fields to tick size //and volume to lot steps


Summary of static methods

Note: You don't need to know OOP or use wrapper class instances to use this library. All we have to do is use CDouble scope resolution to call the static function. The syntax is as follows:

Type variable name = CDouble::Method(args);
Modifiers and types method describe
static boolean
Are they equal (even number 1,
 even number 2,
 double step);
Compares two doubles and returns a Boolean value by subtracting the second number from the first, rounding the sum to "step", and comparing it to 0.
static boolean
Are they equal (even number 1,
 even number 2,
 integer number);
Compares two doubles and returns an by subtracting the second number from the first, rounding the sum to "number", and comparing it to 0.
static integer
compare (even1,
 even number 2,
 double step)
Compares two doubles and returns an integer:
  • 0 if equal.
  • 1 if number 1 > number 2.
  • If number 1 < number 2, then -1.
static double
turn to step (const even, 
 double step)
Returns the rounded value to the nearest step precision (e.g. 0.0025).
 static double
 round to number (const even, 
 integer number)
Returns the value rounded to the nearest number (with normalized double precision ).
 static double
 round to boost (const even, 
 double step)
Returns a value rounded up to step precision.
 static double
 rounddown (const even, 
 double step)
Returns a value rounded down to step precision.
 static double
 circular scale (constant even number, 
 string symbol=NULL)
Returns the nearest rounded value of the tick size of the current symbol (symbol=NULL) or the specified symbol symbol range.
 static double
 Turn-based hand size (constant even number,
 String symbol=NULL,
 boolean always_return_valid = true)

Returns the batch step of the current symbol rounded down to the nearest value (symbol=NULL) or the specified symbol symbol range.

always_return_valid == true: Valid lots will always be returned (min_lots <= return_value <= max_lots)

 Static invalid (MQL5)
 Round Trade Request (MqlTradeRequest and Request)

Modify the Price, Stop Loss, Take Profit and Volume fields via the ticker identified in the request.

Round Price, SL and TP to the nearest price change.

Round volume down to the nearest lot step.

 static invalid
 circle array reaches step

(double&arr[], double step = NULL)

static invalid
 circle array reaches step

(CArrayDouble &arr, double step = NULL)

static integer
 Get number (double float)
Returns the number of digits in a double up to trailing zeros. (eg 0.0002500... will return 5 digits).
 static double
 Get points (integer)
Returns the double value of the specified number. (eg 3 will return 0.001).
 static string
 Convert to string

(even numbers, integer number)

MQTick tick;
SymbolInformationTick ( _symbol ,tick);
Double rnd_by_step = CDouble::RoundToStep(tick.bid* 1.052565465 , _view );
Double rnd_by_digits = CDouble::RoundToDigit(tick.bid* 1.052565465 , _digits );
double by_lot_step = CDouble::RoundToLots( 0.123423 , _symbol );
double by_tick_size = CDouble::RoundToTick(tick.ask- 100 * _view , _symbol );
Double summary = CDouble::RoundToStepUp( 3.999999999 , _view );
double rounddn = CDouble::RoundToStepDown( 3.999999999 , _view );
integer number = CDouble::GetDigits( 0.0000025 );
Double point = CDouble::GetPoint( 10 );
Boolean equal = CDouble::IsEqual(tick.bid,tick.bid+ 0.00000009 , _view );
String tostr = CDouble::ToString( 3.1399999999999999 );
Integer comparison = CDouble::Compare(tick.ask,tick.bid);
#ifdef __MQL5__ Mql transaction request r={ 0 };
  r.symbol = _symbol ;
  r.price=tick.ask+ 0.000089849847658759198199999 ;
  r.sl = r.price- 503 * _view ;
  r.tp = r.price + 503 * _view ;
  r.Volume = 1.127984984 ;
  
   CDouble::RoundTradeRequest(r); #endif


Constructor summary

 double (const ENUM_PRECISION mode = PRECISION_DEFAULT,
 const string symbol = NULL)

Note: There is no need to call the constructor explicitly as the parameters are already initialized in the caller. There is also no need to specify the precision method as there are methods that return rounded values ​​based on the method call.

Enumeration precision:

 Double (const Cdouble &other)
Copy constructor: Copies all private fields of other objects to this object.

Example:

 C even number;
C double bid(PRECISION_TICK_SIZE, _symbol );
C double important price (buying price)
CDouble Ask2 = bid;
C double lot(PRECISION_LOT_STEP, _symbol );


Job Summary - Overloaded Job Operators

 blank
 put (const double value)
Assign a raw double value to m_value.
 blank
 Put (const Cdouble &other)
Assigns the original double value of the CDouble object to m_value.
 blank
Overloaded operators = , += , -= , *= , /= ( double or C double & ) Assign or modify a raw double value to an m_value.

Notes: The = assignment operator can be called on the same line as its declaration.

 C double standard;
bid.Set(tick.bid);
CDouble Ask = tick.ask;

C double pi = 3.14 ;
Cdouble factor = 2 ;
pi*=factor; print (pi.ToString()); //6.28


Summary of overloaded arithmetic operators

 double
Overloaded operators + , - , * , / ( double or C double & ) Can accept double or CDouble type objects as parameters. Returns a double value after applying the arithmetic associated with the overloaded operator.

Note: Arithmetic operators are the only ones that can be used in every statement.

Syntax for overloaded operator arithmetic:

type_double_result <-- CDouble_object <-- operator <-- double
//The CDouble object is always on the left side of the operator type_double_result <-- CDouble_object1 <-- operator <-- CDouble_object2 //The order is not important when using two CDouble objects.

Example:

 C double foo = 3.14 ;
C parallel bars = 10 ;
CDouble foobar = bar + foo; //13.14 CDouble err = bar + foo + foobar; //Error - illegal operation use

double variable = bar/foo;


Summary of overloaded comparison operators

 Boolean value
Overloaded operators == , != , > , < , >= , <= ( double or C double & )

Can accept double or CDouble type objects as parameters. Returns a Boolean value for comparison.

NOTE: This is using Compare method to compare.

 C double foo = 3.14 , bar = 3.1399999999999999999999 ;
  
print (foo == bar); //true print (foo <= bar); //true print (foo > bar); //wrong


Summary of instance methods

Precision control (default): digits = 8; steps = 1e-08

 blank
 Precision mode (const ENUM_PRECISION mode)

Sets the default mode for rounding calculations and ToString. Overwrite existing step size and number settings. Note: It can also be set in the constructor.

Enumeration precision:

 ENUM_PRECISION
 exactmode ()
Returns the current working precision mode.
 blank
 step (const double step or point)
Sets the step size to the specified precision. Cover precision mode.
 double
 step ()
Returns the current value of Step.
 blank
 Number (constant integer number)
Sets the precision to the specified number of digits. Override precision mode and set the step size to 1e- (number).
 integer
 number ()
Returns the current working numeric precision.
 double
 AsRawDouble ()
Returns the original value of the stored double.
 double
 circle ()

Returns the nearest rounded value of the specified step size. Default = 1e-08.

When PRECISION_TICK_SIZE, the step size is locked to the tick size.

When PRECISION_LOT_STEP, steps are locked to batch steps.

 double
 round up ()
Returns the value rounded up by the specified step size.
 double
 Round down ()
Returns the value rounded down by the specified step size.
 double
 fillet scale ()
Returns the rounded value to the nearest tick - specified by the tick size of the symbol.
 double
 circular plot (boolean always_return_valid = true)
Returns the rounded value to the nearest lot - specified by the symbol's lot step size.
 integer
 to integer ()
Returns an int value.
 long
 earth dragon ()
Returns a long value.
 String
 stringprecision ()
Returns a string with trailing zeros.
 String
 Convert to string ()
Returns a string with truncated trailing zeros.
 String
 symbol ()
Returns the current working symbol.
 String
 symbol (const string symbol)
After calling the constructor, set the working symbol to a symbol other than the chart symbol. Used when using multiple symbols.

Example:

 C double pi2 = 3.14159265359 ;
  
//Get the value... double raw_double = pi2.AsRawDouble();
Double round_double_to_step = pi2.AsRounded();
Double tick_size_double = pi2.AsRoundedTick();
Double lot_step_double = pi2.AsRoundedLots();
Double rounded_up = pi2.AsRoundedUp();
Double rounded_down = pi2.AsRoundedDown();
Integer double_to_int = pi2.ToInt();
Long double_to_long = pi2.ToLong();
String precision_str = pi2.ToStringPrecision();
  π2 = 3.140000000009 ;
  pi2. number ( 8 );
String truncated_str = pi2.ToString();


Virtual method summary

Methods overridden from CObject:

 virtual integer
 compare (const CObject *node,
 constant integer mode=0)
The Compare method is used for sorting and searching, comparing the AsRounded value of this object with the AsRounded value of the incoming node.
 virtual integer
 type ()
Returns an int of TYPE_DOUBLE.
 virtual boolean
 save (const int filehandle)
Serialize and save member variables to the file passed in the handle.
 virtual boolean
 load (const int filehandle)
Sets the member variable to the value saved in the file passed in the handle.

See CDoubleVector below for an example.

The CDoubleVector class is a collection of object pointers specifically used for dynamic instances of CDouble.

 Class CD bivector: public CArray object


 #include <double.mqh>


inheritance hierarchy

Virtual method implementation/override from CArrayObj class: Create Element .

Summary of instance methods

**See CArray object for inherited public methods .

 C double*
 operator []
(constant integer index)
Overloaded index operators. Returns a pointer to the object at index n in the vector.
 Boolean value
 add (const double value)
Takes a raw double as argument and converts it to a CDouble object and adds it to the end of the vector.
 Boolean value
 allocate double array (const doublearray[])
Get arrays of doubles and convert them to CDouble objects and assign them to vectors.
 Boolean value
 copy output (double&arr[])
Copies the CDouble values ​​in the vector to the original double array.
 Boolean value
 Copy output (CArrayDouble &arr)
Copies the CDouble values ​​in the vector to the CDoubleArray collection.
 virtual boolean
 save (const int filehandle)
Saves the vector to the file specified by the passed file handle.
virtual boolean
 load (const int filehandle)
Loads the saved vector state from the file specified by the passed file handle.

Example:


Attachment download

📎 doubletests.mq5 (5.47 KB)

📎 double.mqh (28.61 KB)

Source: MQL5 #19727

Verification code Refresh