Description
The ring buffer is one of the form of organization to store data. Usually it represents itself finite-length array to the entry where the oldest elements are replaced by the newest data. Thus, there is always access to a certain number of the last data. Mostly used for the asynchronous reading/writing of stream data. For further details look here.
When writing the Expert Advisors and indicators often doesn’t need to store the calculated values for all bars. It will be enough to keep handy the last data, for example, for 100 bars. The ring buffer is suitable for this. Obvious advantages:
- calculations increase
- memory economy
- easy to use, no need to worry about the exit beyond the array.
сlass CArrayRing
Title
#include <IncOnRingBuffer\CArrayRing.mqh>
File of the CArrayRing.mqh class need to be placed in the IncOnRingBuffer folder which is necessary to create in MQL5\Include\. There are examples to the links below which this class uses.
Class methods
//--- the buffer initialization method: bool Init( // if error it returns false, if successful - true int size, // ring buffer size double volue=EMPTY_VALUE // meaning for empty location buffers );
//--- the addition method of new element into the buffer: void Add( const double element // added element value );
//--- the method overwrites the element value with the given index: bool Update( // if error it returns false, if successful - true const double element, // new value of the element const int index=0 // element index );
//--- the method returns the element value with the given index: double At( // returns element value const int index // element index ) const;
//--- the method returns the value of the last written in the buffer element: double Last() const;
//--- the method overwrites the last element value in the buffer : void Last( const double element // new value of the element );
//--- the method returns the ring buffer size: int Size();
//--- the method changes the ring buffer size: bool Resize( const int size // new size );
Note:
- when the buffer size decrease then, as usual, not the last, but the oldest elements are missing
- in the given realization of the ring buffer the indexing is accepted as in time series, i.e. opposite to the usual
Examples
There are three examples of using the ring buffer to the moment of publication:
- Class for drawing Moving Average
- Class for drawing Average True Range
- Class for drawing Average Directional Movement Index