MetaTrader Trading Tools
Showing 358 results in this view

Сode that records balance and equity charts and calculates additional optimization criteria

I decided to share the code from a large project designed in a separate library.

If you have access to the Expert Advisor code, you can save balance and equity charts and calculate additional optimization criteria by adding additional code from this library.Download the Advanced Optimization Report Saver.mqh file from attached link and save it to the terminal folder \MQL5\Include\Add the code that connects the downloaded file: (you can add it below the last line of your Expert Advisor code or anywhere else)

Then, you need to add calls to the exported functions to the existing functions in your Expert Advisor: (if there are no functions, add them)

save_Add functions, allow you to add your own criteria that you want to include to your Report:

For example, let's add this code to the Moving Average Expert Advisor from the Examples folder (...\MQL5\Experts\Examples\Moving Average\Moving Average.mq5). First, copy the original Expert Advisor and name it Moving Average Charts.mq5. Now, add the code from the instructions above to it.The changes are only at the very end of the code, starting from the OnTick() function after CheckForOpen(); line:

As you can see, it's quite simple and only takes a couple of minutes.After that, you can run the optimization:

The last screenshot shows that the connected code added 2 parameters:

  1. Save Statistics - enables or disables the collection of statistics
  2. Pixels in balance and equity charts - specifies the number of pixels in the width of mini-charts.

Once the optimization is complete, you can create a report (using a program that parses saved frames) and see the following:

If there are more than 20 lines, only 3 horizontal lines of average values will be displayed: 3 on top and 3 on the bottom.100 lines are difficult to perceive, so you need to reduce their number.You to use input variables not with the same step, but with a scale through an enumerator (enum), for example: 1,2,3,5,7,10,15,20,30,50,70,100 - there will be only 12 lines instead of 100.

You can download the enum version of the Expert Advisor from attached files.Instead of 1000 optimization passes, there will be 120, and the calculation time will be ~8 times faster, and the file size will be ~8 times smaller.The result is more visible:

The result with MovingPeriod = 15 stands out immediately, with the highest average line and the highest maximum.However, as is often the case, the best results on the backtest are not the best on the forward test.Your program that parses saved frames can display Charts like this:

And additional criteria like this:

If you have a code for other interesting criteria, you can suggest them for adding to the library.

EA Duplicate Detector

Allow the EA to determine whether there are duplicate EAs on the chart based on conditions.

Expert.mqh comes from the library written by fxsaber at .

CIniFile class

    This class will help you if you need to use the Windows *.ini files. It has a standard interface with simple methods.

    Using the library:

    1. Copy the IniFile.mqh file to the MQ5\Include\ folder.
    2. Declare the CIniFil class instance in the code (don't forget to add the  #include <IniFile.mqh> directive).
    3. Call its Init method with file name as parameter.
    4. Call methods for reading/writeing/checking/deleting the data.
    5. If you need to work with data arrays, declare a CArrayString class instance.

    A simple example of use of the library is contained in Test_CIniFile.mq5.

    Good luck and all the best!

    OptimReport v2.15

    If you want to optimize your Expert Advisor using your own characteristics, you can use "Custom max" mode via function.

    This code simplifies to create your own formulae.

    To define the custom optimization parameter, sometimes it's necceary to calculate many trade characteristics.

    This code provides you the following characteristics:

    1. Profit factor;
    2. Profit in deposit currency;
    3. Profit in points;
    4. Total Profit;
    5. Total Loss;
    6. Loss deals;
    7. Profitable deals;
    8. Profit per deal (in percents);
    9. Profit per day (in percents);
    10. Maximal drawdown;
    11. Balance channel width (in points);
    12. Difference between the maximal and minimal slope of the balance line;
    13. Average drawdown (averaged sum of drawdown for all deals);
    14. Recovery factor;
    15. Average points per deal.

    Manual:

    Copy the "OptimReport.mqh" file to the MQL5\Include\ folder

    Add the following line to the code of your Expert Advisor:

    Add this line to OnInit() function:

    Add this line to OnTick() function:

    Add this line to the code when open position:

    Add these 4 lines to OnTester() function:

    Here is an example of Input_Param:

    Recommendations:

    The Lot_Risk variable is the percent of margin used in trading (for increasing volume).

    Note that HTML file with optimization results is saved separately for each agent: С:\Program Files (x86)\MetaTrader 5\Tester\Agent-127.0.0.1-3000\MQL5\Files\

    If you have found errors or need some other characteristics, please inform me. It will be great if you provide your own optimization characteristics.

    PS: I prefer to use the formula № 5

    Hash functions library

    General purpose hash functions:

    • adler32
    • CRC-32 (fast, table implementation)
    • MaHash8v64 (fast, table implementation)

    All three functions are adapted for MQL5 Unicode strings. The results has been verified with .

    • from decimal (ulong) to Base radix
    • inverse transformation

    The possible practical use of the other radix may be the compact form of string representation of a number in names of graphic objects. For example, 64-bit number generally has the following number of chars:

    • decimal: 20 chars (ULONG_MAX)
    • hexadecimal: 16 chars
    • base 36: 11 chars
    • base 128: 10 chars

    the optimal is the base 36 radix.

    cIntBMP - a library for creation of BMP images

    This class is designed for creation of bmp images.

    Examples:

    An example of DrawTriangle() method

    An example of DrawRectangle() method

    An example of DrawCircle() method

    An example of Fill() method

    Usage:

    The cIntBMP.mqh file should be located in MQL5/Include folder. The demo of cIntBMP class usage is located in the eBMP.mq5 file. Copy this file to the MQL5/Experts folder, open it in MetaEditor, compile and attach to the chart.

    Using cIntBMP class:

    1. Include file with class:

    2. Delcare the cIntBMP class variable, for example "bmp":

    3. Set image size and background color (using Create(...) method, see below).4. Draw on the image.5. Save (using the Save(...) method).6. Show (using the Show(...) method);When finished:1. Delete graphic object (using the Hide(...) method).2. Delete the file (using the Delete(...) method).

    Class Methods:

    • Create(int aSizeX, int aSizeY, int aBGColor) - Sets image size and background color.aSizeX - width (in pixels);aSizeY - height (in pixels);aBGColor - background color;
    • SetDrawWidth(int aWidth) - Sets pen width.aWidth - pen width.
    • DrawDot(int aX, int aY, int aColor) - Draws a dot.aX - X coordinate;aY - Y cooordinate;aColor - color;
    • DrawLine(int aX1,int aY1, int aX2, int aY2, int aColor) - Draws a line.aX1, aY1 - starting coordinates;aX2, aY2 - ending coordinates;aColor - color;
    • DrawRectangle(int aX1, int aY1, int aX2, int aY2, int aColor, bool aSolid=false) - Draws a rectangle.aX1, aY1 - coordinates of the upper left corner;aX2, aY2 - coordinates of the lower right corner;aColor - color;aSolid - true - filled.
    • DrawTriangle(int aX1, int aY1, int aX2, int aY2, int aX3, int aY3, int aColor, bool aSolid=false) - Draws a triangle.aX1, aY1, aX2, aY2, aX3, aY3 - edge coordinates;aColor - color;aSolid - true - filled.
    • DrawCircle(int aX, int aY, int aRadius1, int aRadius2, int aColor, double aRatio=1.0, double aAngleFrom=0.0, double aAngleTo, bool aSolid=false) - Draws a circle.aX - X coordinate;aY - Y coordinate;aRadius1 - radius of the 1st circle;aRadius2 - radius of the 2nd circle;aColor - color;aRatio - ratio (ratio=1, circle, overwise ellipse). aAngleFrom - starting angle;aAngleTo - ending angle. if aAngleFrom=aAngleTo, it will draw a circle;aSolid - true - filled circle/ellipse.
    • Fill(int aX, int aY, int aColor) - Fills the area.aX, aY - coordinates of the fill area;aColor - fill color.
    • TypeText(int aX, int aY, int aColor) - Prints text on the image.aX, aY - coordinates of the left upper corner of the text;aColor - text color.
    • Save(string aFileName, bool aToImages=true) - saves the created image to file.aFileName - File name (it isn't necessary to specify the extension) ;aToImages - file will be saved to the MQL5\Images\ folder, overwise it will be saved to the MQL5\Files\ folder.
    • Show(int aX, int aY, string aBMPFileName, string aObjectName) - Shows the image on the chart.aX, aY - coodinates;aBMPFileName - file name of the image;aObjectName - graphic object of OBJ_BITMAP_LABEL type.
    • Hide(string aObjectName) - Deletes graphic object with the specified name.aObjectName - name of the object to delete.
    • Delete(string aFileName, bool aFromImages=true) - Deletes a file.aFileName - Name of the bmp file to delete (without path, it isn't necessary to specify the extension);aFromImages - if true, the file will be deleted from MQL5\Images\ folder, overwise it will be deleted from MQL5\Files\ folder.

    MQL5 Wizard - Candlestick Patterns Class

    The allows creating ready-made Expert Advisors based on the classes delivered together with the client terminal. It allows to check your trade ideas quickly, all you need is to create your own trading signals class. The structure of this class and example can be found in the article .

    The generic idea is the following: the class of trading signals is derived from , the next, it's necessary to override the and virtual methods with your own methods.

    There is a book " (in Russian), there are many trading strategies are considered there, we will focus on reversal candlestick patterns, confirmed by , , and oscillators.

    The best way is to create the separate class, derived from for checking of formation of candlestick patterns. For confirmation of trade signals, generated by candlestick patterns, it's sufficient to write the class, derived from CCandlePattern and add the necessary features (for example, confirmation by oscillators) there.

    Here we will consider the CCandlePattern class, it allows to simplify the creation of trade signal classes with candlestick patterns for MQL5 Wizard.

    CCandlePattern class

    The CCandlePattern class is derived from the class (base class of trading signals)

    Using CCandlePattern in trade signal classes for MQL5 Wizard

    The CCandlePattern class can be used a parent class for trade signal classes for MQL5 Wizard. It's necessary to derive the trade signal class from CCandlePattern class, also it's necessary to add methods for checking of long/short position opening/closing (in addition to indicators, etc...).

    Formation of reversal candlestick pattern can be used as a trade signal, but it's better to check confirmation (for example, using the oscillators).

    • bool CheckOpenLong(double &price,double &sl,double &tp,datetime &expiration) - Checks conditions of long position opening;
    • bool CheckCloseLong(double &price)  - Checks conditions of long position closing;
    • bool CheckOpenShort(double &price,double &sl,double &tp,datetime &expiration) - Checks conditions of short position opening;
    • bool CheckCloseShort(double &price) - Checks conditions of short position closing;

    The details about the structure of trading signal classes, used in MQL5 Wizard, can be found in the article .

    Take a look at the line:

    in the wizard description section.

    The MAPeriod method is used in the CCandlePattern parent class for calculation of average closing price and averaged values of the candle's body. By default, m_ma_period=12 is set in CCandlePattern() class constructor. However, it's better to set it using the input parameter, it will allow you to use it in of MetaTrader 5.

    Don't forget to call ValidationSettings() and InitIndicators() of parent class

    Note, that it's necessary to call the CCandlePattern::ValidationSettings and CCandlePattern::InitIndicators methods of parent class in the corresponding class methods.

    It's better to call these methods first:

    The same is for the InitIndicators() method:

    Checking candlestick patterns

    To check the formation of a certain candlestick pattern it's necessary to call the CheckCandlestickPattern(ENUM_CANDLE_PATTERNS CandlePattern) method with pattern, passed to the function.

    Also you can check formation of one of the bullish/bearish candlestick patterns using the CheckPatternAllBullish() and CheckPatternAllBearish() methods.

    To simplify the work of candlestick patterns, the ENUM_CANDLE_PATTERNS enumeration is used:

    Checking bullish candlestick patterns:

    Checking bearish candlestick patterns:

    Here are examples of use of the methods:

    1. Open long position

    2. Close long position

    3. Open short position

    4. Close short position

    Recommendations

    To reduce false signals, the reversal candlestick patterns must be confirmed by other indicators, such as oscillators.

    The following patterns are considered in the "Strategies of best traders" book:

    • 3 Black Crows/3 White Soldiers
    • Dark Cloud Cover/Piercing Line
    • Morning Doji/Evening Doji
    • Bearish Engulfing/Bullish Engulfing
    • Evening Star/Morning Star
    • Hammer/Hanging Man
    • Bearish Harami/Bullish Harami
    • Bearish Meeting Lines/Bullish Meeting Lines

    confirmed by , , and oscillators.

    Later we will provide the classes of trade signals for use in MQL5 Wizard.

    cIntSpeech

    Example of use of speech engine.

    • cIntSpeech.mqh (cIntSpeech class) should be located in MQL5/Include.
    • sSpeechExample.mq5 is an example of use of the class, it needs to enable of dll use

    The cIntSpeech class has an only Say() method, it has two parameters. The first is the text to speak, the second is used to allow printing the text in "Experts" tab.

    sToken

    The script contains a class, that can be used to solve mathematical and logical expressions, defined as string.

    The script has two classes: cTokenBase and cToken (a member of CTokenBase). The cTokenBase class must be configured before its use (see below).

    The following MQL5 are supported: , , , , , , , , , , , , , , , , , , .

    Logical and math operations:  /, %, *, +, -, >, <, >=, <=, ==, !=, &&, ||.

    The expression may contain numbers, including double numbers, user variables and user arrays. If you will use the user's variables and arrays, you need to add functions, that returns the values of these variables and arrays. The functions should be added into the cTokenBase class.

    The user variables and arrays are named with letters (the case isn't important), the array elements are defined as follows: e[0], e[1], f[0], f[1].

    Examples:

    How to configure cTokenBase class

    It's neccessary to register the name of the user variables and arrays. It must be done in the UsersVariables() function. The list of user variables/arrays contain the names, separated by ";".

    2. You need to add a call of the corresponding function to the UserFunc(string FuncName) function:

    3. Add functions for all of the user's variables:

    4. Add call of the corresponding function (dependent on ArrName) to the UserArray(string ArrName,int aIndex) function. The index of array element is specified in aIndex variable.

    5. Add functions for each of the arrays:

    Use of the class

    1. Declare an external input variable for the expresssion:

    2. Delcare a cToken class variable on the global level:

    3. Initialize class with the expression.

    4. Call SolveExpression() method

    The class can be used to solve several expressions, just use the several instances of cToken class:

    In this case all the class instances will use the same user variables and arrays (declared in cTokenBase class)

    You can add your functions.

    Adding new functions to cToken class

    1. Register a new function. It must be done in the function.
    2. Add the calculation code to the SolveFunc(string Func,string & aRes[]) function. The function arguments are located in aRes[] array. The number of arguments isn't limited.

    CDownLoadHistory class

    The CDownLoadHistory class provides the methods of historical data downloading in two modes: "visual" and "silent".

    1. Visual mode

    The example of use of this mode is downloadhistoryvisualmode.mq5.

    The "history download mode" input parameter can be one of two modes: "current symbol" or "all symbols from Market Watch window":

    For the "All symbols from Market Watch window" mode, it will show two progress bars:

     

    For the case if the "current symbol" mode is selected, the single progress bar will be shown:

     

    It prints the results in "Experts" tab of "Toolbox" window:

     

    2. Silent mode

    The result of downloading is availiable as a return code. The silent mode can be useful in programs, where visualization is not needed. See example in downloadhistorysilentmode.mq5 script.

    It uses the CProgressBar class, described in .

    The class of a module of trade signals, on "inner bar breakthrough" in trend direction

    The provides an opportunity to create a strategy using different modules. For example, the main module can be written by developer, the other modules (money management, trailing stop) can be developed by other programmers.

    The strategy, implemented in this module is following: when outside bar appears, it checks the fact of the inner bar breakthrough in trend direction and generates a signal to open position. The outside (outer) bar is the bar with High price, greater than High of the previous bar and Low, lower than Low price of the previous bar. The "breakthrough" means the extremum crossover of the inner bar.

    The trend direction depends on the color of the outer bar. Position is opened after completion of the bar with a signal.

    Example of a signal to open a long position:

    Description of signals

    To use the module, copy innerbarsignal.mqh to the MQL5\Include\Expert\Signal\Mysignal.

    After restart of the MetaEditor, the module will appear:

    Module of trade signals in MQL5 Wizard

    History backtesting results (EURUSD ,D1, 2010-2011):

    Testing results

    Input parameters:

    • TakeProfit = 300;
    • StopLoss = 300;
    • Trailing Stop = 100.

    Module of Trade Signals, based on BrainTrend1 indicator

    A blue candle is a signal to open a long position, a red candle is a signal to open a short position. The signals are formed on the completed bars (candles).

    The following input parameters were used when testing:

    • ATR period: 7;
    • Stochastic period: 9;
    • Timeframe: H4;
    • Symbol: GBPUSD;
    • Lot: 0.1;
    • Stop Loss, Take Profit, Trailing: not used.

    To use this module of trade signals in , the braintrendsignal.mqh must be placed to terminal_data_folder\MQL5\Include\Expert\Signal\MySignals.

    The module uses the  indicator, the BrainTrend1.mq5 must be placed to terminal_data_folder\MQL5\Indicators.

    Example of trades on the chart

    History backtesting results starting from 2011:

    History backtesting results