# Programming tutorials - page 5

### Range Breakout EA mql5 Programming | Part 4/4

Range Breakout EA mql5 Programming | Part 4/4

Toby excited to announce that today we will be wrapping up our breakout expert advisor (EA) for MetaTrader 5. This video marks the final part of our comprehensive series on the breakout EA. If you haven't had a chance to watch the previous videos, I will provide links in the description so you can catch up.

In the previous segments, we covered important aspects such as range calculation, buy and sell breakout checks, and position closure logic. Now, in this concluding video, we have a few more features to add to our EA. Specifically, we will incorporate a stop loss and take profit functionality based on a percentage of the range. Additionally, we will introduce a day of the week filter and implement a breakout mode, allowing users to switch between one or two breakouts per range.

Let's dive right into the coding process. So far, this is the code we have developed. Our first task is to include inputs for the stop loss and take profit percentages. We will define them as integers since they are represented in percentages. Let's set the default stop loss input to 150 and the take profit input to 200. We will also update the comments to reflect these changes. To ensure the user provides valid inputs, we need to perform input checks. We will add an additional if statement in the on init function to validate the stop loss and take profit inputs. If the stop loss input is below zero or greater than 1000, we will display an error message. The same validation process applies to the take profit input. These checks will help protect the EA from erroneous inputs.

Moving on, let's calculate the stop loss and take profit values for each position. For buy positions, the stop loss will be calculated as a percentage of the range below the current price. We will use the bid price and multiply it by the input stop loss value divided by 100. To ensure a normalized price, we will apply the NormalizeDouble function. Similarly, for sell positions, the stop loss will be calculated as a percentage of the range above the current price. We will use the ask price and add the calculated stop loss value to it. This will determine the appropriate level for the stop loss.

For the take profit calculation, we will follow the same logic. For buy positions, the take profit will be the range above the current price, while for sell positions, it will be the range below the current price. With the stop loss and take profit values calculated, we will incorporate them into the open position calls. Instead of using a static value of zero, we will replace it with the calculated stop loss and take profit values. This adjustment ensures that the EA accurately sets the stop loss and take profit levels for each position.

To provide flexibility, we will introduce the ability to disable the stop loss and take profit functionality. If the user enters zero for either input, it will indicate that they want to turn off that feature. We will add if statements to check these conditions and adjust the calculation accordingly. Now, let's address the optional close time feature. By entering -1 as the close time input, the EA will only close positions based on the stop loss and take profit levels. This modification allows users to choose whether they want to include a specific time for position closure or rely solely on the stop loss and take profit parameters.

To implement this, we will update the close time check in the on tick function. If the close time is less than zero, indicating it is turned off, we will skip the position closure check based on time and rely solely on the stop loss and take profit conditions. Furthermore, we will make adjustments to the range visualization in the draw object function. If there is no close time set, the range lines will extend all the way to the current candle, indicating that the breakout mode is active until the stop loss or take profit levels are reached. On the other hand, if a close time is set, the range lines will only extend up to that specific candle, signifying that the breakout mode is active until the designated time.

To enhance the EA's versatility, we will introduce a day of the week filter. This filter allows users to specify the days on which they want the EA to be active. We will add an input parameter for the day of the week filter, where the user can select multiple days from a predefined list. By default, all days of the week will be selected. To implement the day of the week filter, we will modify the on tick function. We will introduce an if statement to check if the current day is included in the user's selected filter. If the day is not included, the EA will skip the position opening logic and proceed to the next tick.

Finally, we will implement the option to switch between one or two breakouts per range. Currently, the EA opens one position per range breakout. However, some traders may prefer to have the flexibility of opening two positions for stronger breakouts. To accommodate this, we will introduce an input parameter that allows the user to select either one or two breakouts per range.

To implement this feature, we will adjust the position opening logic. If the user selects two breakouts per range, the EA will open an additional position in the opposite direction of the initial breakout. This way, both a bullish and bearish breakout can be captured within the same range. With all these new features implemented, our breakout expert advisor will provide traders with enhanced functionality and flexibility. The stop loss and take profit functionality based on a percentage of the range will help manage risk and capture profits. The day of the week filter will allow users to specify the active trading days, while the breakout mode can be tailored to one or two breakouts per range, depending on their trading strategy.

We hope you found this comprehensive series on the breakout expert advisor helpful and informative. If you have any questions or need further assistance, please don't hesitate to reach out. Happy trading!

Range Breakout EA mql5 Programming | Part 4/4
• 2022.10.14
I will show you how to code a Time Range Breakout EA for Metatrader 5. If you are new to mql5, just follow my steps and we will create a time range breakout...

### Bollinger bands EA MT5 Programming

Bollinger bands EA MT5 Programming

In this video, Toby introduces a step-by-step process for creating a custom expert advisor for a bowling event on Twitter. He starts by explaining the strategy: selling when a candle opens above the upper Bollinger band, setting stop loss and take profit levels, and exiting the trade if the middle line of the Bollinger Bands is crossed. The same logic applies for buying.

Toby then switches to MetaEditor, where he creates a new expert advisor using a template. He cleans up the template and adds input parameters for the EA, such as magic number, lot size, period, deviation, stop loss, and take profit. He sets default values for these parameters and compiles the code.

Next, Toby defines global variables for the EA, including the handle of the Bollinger band indicator and buffers for upper, mean, and lower bands. He also creates variables for the current tick and trade.

Moving on to the OnInit function, Toby checks if the user inputs are valid. If any of the inputs are invalid, he displays an error message and returns. He sets the magic number for the trade object and creates the indicator handle for the Bollinger band indicator. If the handle creation fails, he displays an error message and returns. He then sets the buffers as series and compiles the code.

In the OnTick function, Toby checks if the current tick is a bar open tick using a custom function. If it's not a bar open tick, he returns. If it is a bar open tick, he retrieves the current tick using the SymbolInfoTick function and stores it in the currentTick variable. He then retrieves the latest indicator values using the CopyBuffer function and stores them in the respective buffers. If the number of copied values is not equal to 3, indicating an error, he displays an error message and returns.

At this point, Toby has completed the initial steps of coding the expert advisor. He compiles the code and uses a visual backtest in MetaTrader to verify the indicator values and ensure the code is functioning correctly.

Next, we need to implement the logic for generating trade signals based on the Bollinger Bands strategy. We'll start by checking if a candle opens above the upper band, indicating a sell signal. If this condition is met, we'll execute a sell trade with a stop loss and take profit level. Similarly, we'll check if a candle opens below the lower band for a buy signal, executing a buy trade with the same exit conditions.

Here's the explanation of the code:

• We first check if the current tick is a bar open tick using the isNewBar() function. If it returns false, we skip the trade signal generation for the current tick.

• We then retrieve the latest indicator values: upperBand, baseLine, and lowerBand from the respective buffers.

• Next, we check if the opening price of the previous candle is above the upper band (open[1] > upperBand). If this condition is true, we generate a sell signal by opening a sell trade using the Sell() method of the trade object. We set the lot size, stop loss, and take profit levels using the respective methods.

• Similarly, we check if the opening price of the previous candle is below the lower band (open[1] < lowerBand). If true, we generate a buy signal by opening a buy trade using the Buy() method of the trade object. Again, we set the lot size, stop loss, and take profit levels.

• Finally, if there is an open trade, we check if the current candle's closing price crosses the middle line (base line). If this condition is true, we close the trade using the Close() method of the trade object.

Remember to compile the code and test it in MetaTrader to ensure it works as expected.

In the given code, there are several tasks being performed. Here is a detailed explanation of each step:

1. Initialize variables:

• Set the count of buy positions and sell positions to zero.
• Set the current cell to zero.
2. Count open positions:

• Loop through all currently open positions.
• Get the ticket of each position and check if the operation is successful.
• If successful, get the magic number of the position.
• If the magic number matches the input magic number, increment the respective counter for buy or sell positions.
3. Check if a new position can be opened:

• Check if there are no open buy positions.
• Check if the current price is below or equal to the lower buffer of the Bollinger Bands.
• Check if the open time for the buy position is different from the current bar's open time.
4. Calculate stop loss and take profit:

• Calculate the stop loss by subtracting the input stop loss (in points) from the current price.
• Calculate the take profit by adding the input take profit (in points) to the current price.
• If the input take profit is zero, set the take profit variable to zero.
5. Normalize stop loss and take profit:

• Define a function to normalize the stop loss and take profit based on the tick size.
• Get the tick size for the current symbol.
• Normalize the stop loss and take profit values by dividing them by the tick size.
6. Open a new buy position:

• Use the Trade object to open a buy position with the specified parameters, including the normalized stop loss and take profit.
7. Check for upper band cross to open a sell position:

• Check if there are no open sell positions.
• Check if the current price is above or equal to the upper buffer of the Bollinger Bands.
• Check if the open time for the sell position is different from the current bar's open time.
• Calculate the stop loss and take profit for the sell position using the current bid price.
• Normalize the stop loss and take profit values.
• Open a sell position with the specified parameters, including the normalized stop loss and take profit.
8. Close positions if the middle line of the Bollinger Bands is crossed:

• Count the open buy and sell positions.
• If the count of buy positions is greater than zero and the current bid price is above the upper buffer, close all buy positions.
• If the count of sell positions is greater than zero and the current ask price is below or equal to the lower buffer, close all sell positions.
9. Define the function to close positions:

• Copy the existing code for counting open positions and modify it to close positions based on the input parameter (0 for all positions, 1 for buy positions, 2 for sell positions).

The code performs various checks and calculations to count and manage open positions, open new positions, and close positions based on specific conditions.

Bollinger bands EA MT5 Programming
• 2022.11.28
Today I will show you how to code a simple Bollinger bands EA for Metatrader 5. If you are new to mql5, just follow my steps and we will create a fully work...

### How to create a graphical panel in mql5 | Part 1/2

How to create a graphical panel in mql5 | Part 1/2

Toby will demonstrate how to create a simple graphical panel in MQL5 to display information and add a button to change the background color of the chart. He mentions that this panel can be created for any expert advisor, but he will use the time range breakout EA as an example. Toby states that the video topic was requested by a user in the comments and encourages viewers to suggest topics for future videos.

Toby opens the Meta Editor and loads the file for the time range breakout EA. He saves it as a new expert advisor called "time range EA panel" and compiles it. He explains that he will write the panel as a separate class in an include file, making it easy to use in any expert advisor. Toby creates a new include file called "graphical panel" and defines the inputs for the panel size, font size, and font color.

He includes the "dialog.mqh" file from the controls folder, which will allow him to use the functions from that class. Toby defines a class called "CGraphicalPanel" that inherits from the "CAppDialog" class. He adds a private section for the class's methods, a public section for the constructor, destructor, initialization function, and chart event handler. He also includes a comment section for the class methods.

Next, Toby writes the body of the class methods after the class definition. He specifies that the methods belong to the class and writes the constructor, destructor, initialization function, and chart event handler. He adds comments to describe each method's purpose. Toby compiles the code to check for errors or warnings.

Toby implements the create panel function, which creates a dialog panel using the CFDialog class. He sets the panel's name, sub-window, position, and size based on the input parameters. If the panel creation fails, he prints a message and returns false. He also adds a chart refresh function to update the chart. Toby compiles the code again to ensure it's error-free.

In the expert advisor file, Toby includes the graphical panel include file and creates an object of the panel class called "panel" in the global variable section. He initializes the panel in the onInit function and adds a chart event handler to pass the chart events to the panel. Toby writes the body of the chart event handler, calling the panel's chart event function with the appropriate parameters.

Finally, Toby adds a destroy panel function to the onDeinit function, which destroys the panel and specifies the reason. He compiles the code again and tests it in MetaTrader. Toby demonstrates dragging and dropping the expert advisor onto the chart, showing the panel's functionality. He also closes the expert advisor using the panel's button.

Hey, I'm Toby, and today I'll show you how to create a graphical panel in MQL5. This is actually the second part of the tutorial. In the first part, we created a simple panel on the left side, and if you missed it, you can find the link in the description. In today's video, we'll add some labels and a button to the panel. For this example, we'll be using the time range breakout EA. If you're interested in learning how to code this expert advisor, I have a coding series on my channel. You can find the link to the first part in the description as well.

To get started, let's switch to the MQL5 editor and begin coding. We have our graphical panel include file here, and we also have the time range breakout EA, which we modified to display the panel. Let's go to the include file and check the input values from the user. We'll create a method called "check inputs" under the private method section in our class. After the OnInit function, we'll call this method. If the method returns false, we'll also return false from the OnInit function. This way, if the inputs are invalid, we won't proceed further. Let's compile and move on.

Now, let's start adding labels to the panel. We need to include the necessary class files for labels and buttons. We'll go to the include section and include "controls/label.mqh" for labels and "controls/button.mqh" for buttons. After that, we'll define our label variables. We'll have labels for inputs, magic number, lots, start time, duration, and close time. Let's compile and move on.

In the createPanel function, we'll add the labels to the panel. We'll create the input label using the variable "M_L_Input". We'll set the text, color, and font size for the label. Then, we'll attach the label to the panel. We'll repeat this process for the other labels as well. Once we've added all the labels, we'll compile and check the panel on the left side. We might need to adjust the positions of the labels for better alignment. Let's compile and check.

Now, let's add the button to the panel. We'll define a variable "M_B_ChangeColor" of type "CButton". We'll set the position, text, text color, background color, and font size for the button. Finally, we'll add the button to the panel. After compiling, we'll see the button on the panel. At this stage, the button doesn't have any functionality, but we'll add that later.

Next, let's change the background color and font name of the panel. To do this, we'll include the "Defiance.mqh" file and define new values for the default settings. We'll undefine the default font name and background color settings, and then define new values for them. We'll use the font name "Consolas" and a dark gray background color. After compiling, we'll see the updated panel with the new background color and font.

Finally, let's display the actual values from the expert advisor on the panel. We'll include the expert advisor file in our include file and access the input variables. We'll update the labels with the actual values from the expert advisor. After compiling, we'll see the input values displayed on the panel.

That's it for today's tutorial on creating a graphical panel in MQL5. In the next part, we'll add functionality to the button and complete the panel. Stay tuned for more!

How to create a graphical panel in mql5 | Part 1/2
• 2022.12.04
Today I will show you how to code a simple graphical panel for Metatrader 5. If you are new to mql5, just follow my steps and we will create a fully working...

### How to create a graphical panel in mql5 | Part 2/2

How to create a graphical panel in mql5 | Part 2/2

Hi, this is Toby. Today I'll show you how to create a graphical panel in MQL5. This is the second part of the tutorial series. In the first part, we created a simple panel on the left side. If you missed it, I'll link it here. In today's video, we'll add labels and a button to the panel. For this example, we'll be using the time range breakout EA. If you want to learn how to code this expert advisor, I have a coding series on my channel. I'll link the first part here as well.

Let's switch to the Media editor and start coding. We have our graphical panel include file and the modified time range breakout EA file, which displays the panel. In the include file, we'll create a method called "checkInputs" to validate the user's input values. We'll call this method before creating the panel in the OnInit function. If any of the inputs are invalid, we'll display an error message and return false. Otherwise, we'll proceed with creating the panel.

Next, we'll add labels and a button to the panel. To use labels and buttons, we need to include their class files. We'll add the necessary include statements for labels and buttons in the class. Then, we'll define private variables for the labels and the button.

In the CreatePanel function, after creating the panel, we'll add the labels and button to the panel. We'll set their positions, text, color, and font size. Finally, we'll add them to the panel using the Add method.

We'll compile the code and check the panel. The labels and button should be displayed on the panel. We'll also change the background color and font name of the panel for better appearance. To display the actual values from the expert advisor on the panel, we'll include the expert advisor file in the include section. Then, in the CreatePanel function, we'll retrieve the input values from the expert advisor and display them on the labels. We'll compile the code and check the panel again. The labels should now display the actual input values from the expert advisor. We'll repeat this process for all the input values.

Once we complete these steps, the graphical panel with labels and a button will be ready. Now we can proceed with adding the values for the remaining labels on the panel. We'll do this in the same manner as we did for the magic number label. Let's go back to our include file and locate the section where we create the labels. Here, we'll add the code to display the values for lots, start time, duration, and close time.

For the lots label, we'll replace the text "magic number" with "lots" and update the y-coordinate to 70. For the start time label, we'll change the name to "start time" and update the y-coordinate to 90. For the duration label, we'll change the name to "duration" and update the y-coordinate to 110. Lastly, for the close time label, we'll change the name to "close time" and update the y-coordinate to 130.

After making these changes, we can compile the code.

Now, if we take a look at our expert advisor and compile it, we should be able to see the actual values for lots, start time, duration, and close time on the panel. Next, let's implement the functionality for the button. Currently, when we click the button, it doesn't perform any action. Let's change that. In our include file, we'll locate the section where we create the button. Here, we can add an event handler for the button click. We'll use the OnChartEvent function for this purpose. Inside the event handler, we can specify the action we want to take when the button is clicked.

For now, let's display a message when the button is clicked. We can use the Print function to output a message to the terminal. After adding the event handler, we can compile the code.

Now, if we run the expert advisor and click the button, we should see the message displayed in the terminal.

That's it! We have successfully created a graphical panel in MQL5 with labels and a button. The labels display the input values from the expert advisor, and the button has a click event handler.

Feel free to add more functionality to the button or customize the panel according to your requirements. Remember to compile both the include file and the expert advisor file to see the changes take effect.

How to create a graphical panel in mql5 | Part 2/2
• 2022.12.12
Today I will show you how to code a simple graphical panel for Metatrader 5. If you are new to mql5, just follow my steps and we will create a fully working...

### Dynamic position sizing in mql5 | MT5 programming

Dynamic position sizing in mql5 | MT5 programming

Hello, this is Toby. Today, I will show you how to calculate the dynamic lot size in MQL5 so that you can achieve results like the one shown here. You can try it out for yourself.

Alright, let's get started. In this video, we will add a dynamic lot size calculation to a strategy that currently uses a fixed lot size. This will allow us to risk a specific amount per trade, such as \$100 or a percentage of the account balance. Additionally, we will perform a backtest to determine if the strategy can be further improved with the dynamic lot size calculation. I will also walk you through the strategy and its settings.

To begin, let's switch to MetaEditor and start coding. Here we are in MetaEditor, and for this demonstration, I will use the 'Time Range EA' to incorporate the dynamic lot size calculation. However, you can use any other expert advisor of your choice. We have previously coded this EA in a series on our channel. If you'd like to use the same expert advisor, I will provide a link to the first part.

First, let's open the 'Time Range EA' file. Now, let's save it with a new name. Click 'Save As' and name it 'Time Range EA Dynamic Lots.' Great, the file has been saved.

This expert advisor is where we will add the dynamic lot size calculation. Let's compile the file and examine the inputs in the strategy tester. Open the strategy tester in the MetaTrader 5 platform, and if needed, refresh the expert advisors. Now, select the 'Time Range EA Dynamic Lots.' In the Inputs tab, you will notice the 'Lot Size' input, which currently accepts a fixed value. We need to modify this so that we can enter values to risk \$100 per trade or a percentage of the account balance.

Switching back to MetaEditor, we will add a dynamic lot size input under the 'input' section. Create some space after the 'Magic Number' and define an enumeration (enum) called 'Lot Mode Enum.' This enum will have three options: 'Fixed,' 'Money,' and 'Percent of Account.' This will allow us to choose the desired lot mode easily. Provide comments for each option to improve readability.

Next, we'll use this enum as an input. Define an 'input' with the type as our 'Lot Mode Enum' and name it 'Input Lot Mode,' for example. Set the default value to 'Lot Mode Fixed,' and add a comment to describe the purpose of this input.

Compile the code and check how it appears in the strategy tester. You'll notice the 'Lot Mode' dropdown menu, allowing you to select between 'Fixed,' 'Lot based on Money,' and 'Lot based on Percent of Account.'

Now, let's modify the 'Lot Size' input to accommodate different values depending on the selected lot mode. Change the input type to 'double,' and modify the comment to reflect the options: 'Lot/Money/Percent.' Compile the code again and check the strategy tester to ensure the changes are reflected.

To validate the user's input, we'll modify the 'CheckInput' function. Add checks for each lot mode option to ensure the input is within the acceptable range. For the 'Fixed' lot mode, the lot size should be above zero and not exceed a certain limit (e.g., 10 lots). Display an appropriate error message if these conditions are not met. Repeat this process for the 'Money' and 'Percent of Account' lot modes, adjusting the limits accordingly. Additionally, if either of these two lot modes is selected, we'll need to check if the stop loss is active.

A concise summary of the steps involved in implementing dynamic lot size calculation in MQL5:

1. Determine the minimum and maximum allowed lot sizes for your trading strategy.
2. Define the desired lot step size, which represents the increment by which lots can change.
3. Calculate the stop loss distance for the trade.
4. Use the stop loss distance to calculate the initial lot size.
5. Check if the calculated lot size is below the minimum allowed value and adjust it if necessary.
6. Check if the calculated lot size exceeds the maximum allowed value and adjust it if necessary.
7. Check if the calculated lot size is a valid step size and adjust it to the nearest valid step size if necessary.
8. Return the final calculated lot size.
9. Use the calculated lot size to open the trade.

By following these steps, you can ensure that your lot size is dynamically calculated based on your desired risk per trade and the constraints of your trading strategy.

Dynamic position sizing in mql5 | MT5 programming
• 2022.12.18
Today I will show you how to code dynamic position sizing for Metatrader 5 in mql5. We create two functions to calculate a dynamic position size for any Expe...

### Trailing stop loss in mql5 | MT5 programming

Trailing stop loss in mql5 | MT5 programming

Today, I will guide you step-by-step on how to add a training stop loss to any expert advisor in MQL5. By the end of this video, we will also perform a backtest to evaluate if our strategy can be enhanced with a trading stop loss. So let's get started.

Before we begin coding, let's understand the basic concept of a trading stop loss. Imagine we enter a position at a specific price. Initially, our stop loss is set at a certain level. As the price moves in our favor, we trail the stop loss behind the price, always maintaining the same distance. If the price retraces, the stop loss remains in place. As the price continues to move in our direction, we continue trailing our stop loss. Eventually, the price may reverse, leading to our position being stopped out. The main idea is to profit from significant market trends and exit the position when the trend ends.

Now, let's switch to MetaEditor to start coding. You can use any expert advisor for this purpose, but for this video, we will use the "Timeline GA" with dynamic lot size, which we coded in the previous video. Open the file and save it as a new expert advisor named "Stop Loss." Compile the code to ensure everything is error-free.

To add a trading stop loss to our expert advisor, we need to follow a few steps. First, let's add an additional input for the trailing stop loss. Within the input section, add a boolean input variable called "EnableTrailingStopLoss" and set its default value to "false." This input will allow us to activate or deactivate the trading stop loss. Compile the code to incorporate the changes.

Now, switch back to the MetaTrader platform and open the Strategy Tester. Select our expert advisor "Dynamic Lots with Trailing Stop Loss." In the input tab, you will find the newly added input "EnableTrailingStopLoss." Toggle it from "false" to "true" to activate the trading stop loss.

Next, let's write the function that will update our stop loss. We'll place this function before the "ClosePosition" function. Within the function, first, check if we have enabled the trading stop loss and if there is an existing stop loss for the position. If not, there is no need to proceed, so return from the function.

Now, let's loop through all open positions. For each position, we'll check if it belongs to our expert advisor. Retrieve the position type (buy or sell), the current stop loss, and take profit values. Calculate the new stop loss based on the current price and the range of the symbol, multiplied by the user-defined stop loss percentage. Adjust the stop loss based on the position type.

Before modifying the position with the new stop loss, we need to perform a few checks. First, ensure that the new stop loss is different from the current stop loss to avoid errors. Additionally, some brokers impose a stop level, preventing setting the stop loss too close to the current price. Check if the new stop loss adheres to the stop level, and if not, continue to the next position.

Finally, modify the position with the new stop loss and the current take profit value. If the modification fails, print an error message indicating the issue encountered. Return from the function to avoid processing any further positions.

Compile the code to ensure there are no errors or warnings. Now, the update stop loss function is complete.

To integrate this function into our expert advisor, we need to call it within the "OnTick" function. Place the function call after checking for breakouts. This ensures that the stop loss is updated for each tick received.

Compile the code one last time to confirm the changes. Now, our expert advisor has the ability to trail the stop loss based on the user-defined parameters. We have added the input variable to enable or disable the trailing stop loss feature, and we have implemented the function to update the stop loss for open positions.

Now, let's proceed to backtest our expert advisor to evaluate the effectiveness of the trading stop loss. In the MetaTrader platform, open the Strategy Tester and select our expert advisor "Stop Loss" for testing. Choose the desired symbol and timeframe for the test.

In the Inputs tab, you will find various parameters to configure, including the trailing stop loss percentage and the lot size. Adjust these parameters according to your preferences and trading strategy.

Click the Start button to begin the backtest. The expert advisor will execute trades based on the specified parameters, and the stop loss will be dynamically adjusted as the price moves in our favor.

Once the backtest is complete, you can review the results in the Results and Graph tabs. Pay attention to the profit and loss, drawdown, and other performance metrics to assess the impact of the trailing stop loss on the strategy.

If the backtest results are satisfactory, you can consider using the expert advisor with the trading stop loss in your live trading account. However, it's crucial to thoroughly evaluate the performance of the strategy and conduct further testing or optimization before making any trading decisions.

In conclusion, we have successfully added a trading stop loss to our expert advisor using MQL5. By trailing the stop loss behind the price, we aim to maximize profits during favorable market trends and minimize losses when the trend reverses. Remember to thoroughly test any modifications or strategies before applying them to live trading accounts.

Please note that this is a general guide, and it's essential to have a good understanding of programming and trading principles before implementing such changes. Always exercise caution and consider consulting with a professional financial advisor if needed.

Trailing stop loss in mql5 | MT5 programming
• 2022.12.31
Today I will show you how to code a trailing stop loss in mql5. You can use the same function to add a trailing stop loss to any other Expert Advisor for Met...

### Code a simple RSI EA in mql5 | MT5 Programming

Code a simple RSI EA in mql5 | MT5 Programming

In this tutorial, Toby introduces himself and explains the goal of the tutorial, which is to demonstrate how to code a simple Expert Advisor (EA) using the MetaEditor. The EA will use the RSI indicator to generate buy and sell signals based on oversold and overbought conditions. Toby also mentions that a stop loss, take profit, and an option to exit trades on a reverse signal will be included in the EA.

Toby starts by creating a new EA file in MetaEditor and cleans up the existing code. He then defines the input parameters for the EA, such as the magic number, lot size, RSI period, RSI level, stop loss, take profit, and the option to close trades on a reverse signal. He assigns default values to these input parameters and adds comments to describe each one.

After defining the input parameters, Toby moves on to creating the global variables section. He declares variables for the RSI indicator handle, a buffer to store RSI values, a tick type variable to store the current tick, a trade object to open and close positions, and two datetime variables to ensure only one trade is opened per bar. He also includes the necessary #include directive to access the CTrade class.

Next, Toby implements input parameter validation in the OnInit() function. He checks if each input parameter meets the specified criteria and displays an error message if any input is invalid. He uses the Alert() function to print the error messages and returns from the OnInit() function if an error is encountered.

In addition to input validation, Toby sets the magic number for the trade object and creates the RSI indicator handle. He checks if the handle creation was successful and displays an error message if it fails. He also sets the series for the RSI buffer to simplify working with the values.

In the OnDeinit() function, Toby releases the RSI indicator using the IndicatorRelease() function to free up resources.

Moving on to the OnTick() function, Toby begins by getting the current tick using the SymbolInfoTick() function. He checks if the tick retrieval was successful and displays an error message if it fails. He assigns the ask and bid prices of the current tick to the global variable currentTick for future use.

Next, Toby retrieves the RSI indicator values using the CopyBuffer() function. He assigns the values to a variable called rsiValues and checks if the retrieval was successful. He stores the two RSI values in the buffer for further analysis.

With the necessary data retrieved, Toby can now proceed to implement the trading logic in the OnTick() function. However, the code provided in the text is cut off, and the remaining details are missing.

The tutorial covers the initial setup of the EA, including input parameter definition, input validation, global variable declaration, RSI indicator handling, and current tick retrieval. The tutorial sets the foundation for implementing the trading logic in subsequent steps.

Code a simple RSI EA in mql5 | MT5 Programming
• 2023.01.08
Today I will show you how to code a simple RSI EA for Metatrader 5. If you are new to mql5, just follow my steps and we will create a fully working RSI Expe...

### Amazing RSI trading bot in mql5! | MT5 programming

Amazing RSI trading bot in mql5! | MT5 programming

Hey, this is Toby, and today I'll show you how to code a strategy with a 100% win rate. In this tutorial, we'll modify an existing Expert Advisor (EA) and add a filter to the RSI indicator. I'll guide you through the coding process step by step. Let's get started!

Step 1: Setting Up the Strategy We'll be working in the MetaEditor. Open the EA we created in the previous video. If you haven't watched it yet, I'll link it for you to catch up. Save the file with a new name, such as "RSI_MA_Filter_EA".

Step 2: Modifying the Inputs To implement the filter, we need to add a moving average period input. We'll also include an input for the time frame on which the moving average runs. We'll keep the stop loss, take profit, and opposite signal inputs as they are.

Step 3: Adjusting Global Variables In the global variables section, we need to rename the handle and buffer for the RSI indicator to differentiate them from the moving average. We'll add a handle and buffer for the moving average. Additionally, we can remove unnecessary variables related to open time buy and open time sell.

Step 4: Making Changes in the onInit Function In the onInit function, we'll add a check for the moving average period input. We'll also modify the RSI handle to use the price open instead of price close. Then, we'll create the handle and buffer for the moving average indicator.

Step 5: Updating the Untick Function Within the untick function, we'll first check if the current tick is a new bar open tick. If not, we'll return and wait for the next bar open tick. We'll add a custom function to perform this check. Then, we'll retrieve the values for the moving average and store them in the buffer. We'll also adjust the conditions for opening buy and sell positions to include the moving average filter.

Step 6: Compiling and Testing After making all the necessary changes, we'll compile the code to check for any errors. If everything compiles successfully, we can proceed to test the EA in the strategy tester. We'll run a visual test using historical data from 2012 to the present, selecting appropriate inputs for RSI and moving average periods, stop loss, take profit, and the option to close trades on an opposite signal.

By following this tutorial, you've learned how to code a strategy with a 100% win rate. We modified an existing EA and added a moving average filter to the RSI indicator. Remember to save your file and compile it without any errors. You can now test the strategy in the MetaTrader 5 platform using the strategy tester. Good luck with your future coding endeavors!

Amazing RSI trading bot in mql5! | MT5 programming
• 2023.01.15
Today I will show you how to code a RSI trading bot for Metatrader 5. If you are new to mql5, just follow my steps and we will create a fully working RSI Ex...

### Donchian channel custom Indicator EA | MT5 programming

Donchian channel custom Indicator EA | MT5 programming

Hey, this is Toby. Today, I'll show you how to code a custom indicator in MQL5. We'll be creating a Donchian Channel indicator and later use it to develop a profitable Expert Advisor (EA). Once the EA is ready, we'll run some backtests to evaluate its performance. As you can see from the results, the strategy performs remarkably well. Let's get started!

Now, let's analyze the results in the Strategy Tester. The Donchian Channel Expert Advisor shows promising outcomes. So, our first step is to define the strategy. We'll code a custom Donchian Channel indicator and use it to create the Expert Advisor. Let's outline the basic strategy idea on the chart.

The blue lines represent the Donchian Channel indicator we'll be coding in this video. The Donchian Channel displays the highest high and lowest low of the previous n-bars. Many traders use the Donchian Channel to develop breakout strategies, where they enter a buy trade when the price crosses above the upper band. However, for this EA, we'll explore the opposite approach. We'll take a sell trade whenever the price crosses above the upper band of the Donchian Channel. Similarly, we'll take a buy position when the price crosses below the lower band of the Donchian Channel. We'll also set a stop-loss based on points or a percentage of the channel. Additionally, we might add a filter to the Donchian Channel EA to consider the size of the channel.

Now, let's jump into the Meta Editor to start coding our custom Donchian Channel indicator.

In the Meta Editor, let's begin by creating a new custom indicator file. We'll clean up the code a bit by removing unnecessary comments and aligning the brackets. Next, we'll define the indicator's properties. We'll specify that it should be displayed in the main chart window rather than a separate window. We'll also declare the number of buffers and plots our indicator will have, which in this case is two.

Moving on, we'll define the inputs for our custom indicator. These inputs allow users to customize the indicator when applying it to a chart. We'll create inputs for the period of the Donchian Channel, the offset of the channel (as a percentage), and the color of the channel.

After compiling the code, we'll proceed to the Global variables section, where we'll define the necessary variables for the indicator. We'll create buffers for the upper and lower values of the Donchian Channel and additional variables to store the upper and lower values, as well as the first bar index.

In the OnInit function, we'll initialize our buffers and set the indicator short name, which will be used to identify the indicator on the chart.

Finally, in the OnCalculate function, we'll perform the calculation for the Donchian Channel indicator. We'll check if there are enough bars in the chart to proceed. If not, we'll return zero. Otherwise, we'll calculate the upper and lower values for each bar using the open prices. We'll store these values in the corresponding buffers.

Once the code is compiled without any errors or warnings, we can test our custom indicator. Open a chart, navigate to the Navigator, and find the My Donchian Channel indicator. Drag and drop it onto the chart. In the indicator's settings, specify the desired period, offset, and color.

Donchian channel custom Indicator EA | MT5 programming
• 2023.01.29
Today I will show you how to code a Donchian channel custom indicator EA for Metatrader 5. If you are new to mql5, just follow my steps and we will create a...

### Awesome Donchian Channel trading bot in mql5! | MT5 programming

Awesome Donchian Channel trading bot in mql5! | MT5 programming

Once you have added the custom indicator to the chart, you will see the Donchian Channel displayed as blue lines. The Donchian Channel indicator shows the highest high and lowest low of the previous 'n' bars. It is commonly used to create breakout strategies, where traders enter buy trades when the price crosses above the upper band of the Donchian Channel, and sell trades when it crosses below the lower band.

However, for this EA (Expert Advisor), we want to test the opposite approach. Instead of buying when the price crosses above the upper band, we will sell, and vice versa. So, whenever the price crosses above the upper band of the Donchian Channel, we will take a sell position, and when it crosses below the lower band, we will take a buy position.

In addition, we will set a stop loss for each trade, either in points or as a percentage of the channel. We may also consider adding a filter to the Donchian Channel EA based on the size of the channel. Now, let's jump into the MetaEditor to start coding our custom Donchian Channel indicator.

In the MetaEditor, create a new custom indicator file by clicking on "New" in the top left corner, selecting "Custom Indicator," and clicking on "Next." Name the file "MyDonchianChannel" and click on "Next" and "Finish" to complete the process. Once the file is created, clean up the code by removing unnecessary comments and aligning the brackets. Next, compile the code to check for any errors or warnings.

Now, let's define the properties of our custom indicator. We want it to be displayed in the main chart window, so set the property "indicator_chart_window" to true. We also need to define the number of buffers and plots for our indicator. Since we have two lines (upper and lower), set "indicator_buffers" to 2, and "indicator_plots" to 2.

Next, we will define the input parameters for our custom indicator. We need inputs for the period of the Donchian Channel, the offset percentage, and the color of the indicator lines. Define these inputs using the appropriate types (integer for period and offset, and color for color), and set default values and comments for each input.

Compile the code again to ensure there are no errors or warnings.

Now, let's move on to coding the "onCalculate" function of the custom indicator. First, check if the number of bars in the chart is less than the input period plus one. If so, there are not enough bars to calculate the indicator, so return with zero. Next, set the "first" variable, which represents the first bar for which we want to start calculating the Donchian Channel. If the previous calculation has not been done (previous_calculated is zero), set "first" to the input period. Otherwise, set it to previous_calculated minus one. Now, we need to loop through the bars using a for loop. Start the loop from the "first" bar and continue until the current bar is less than the total number of bars in the chart. Increase the bar counter at the end of each loop iteration.

Inside the loop, calculate the upper and lower values of the Donchian Channel using the open prices of each bar. Store these values in the "upper" and "lower" variables, respectively.

To calculate the offset, subtract the lower value from the upper value and multiply it by the input offset divided by 100. This will give us the offset value in points or as a percentage of the channel. Finally, store the calculated values in the corresponding buffers using the buffer index and the bar counter. After calculating and storing the values in the buffers, we need to set the indicator labels for each plot. These labels will be displayed in the indicator's properties window.

Assign the labels for the upper and lower plots using the SetIndexLabel() function, passing the buffer index and the label as parameters. Next, we'll set the colors for the indicator lines using the SetIndexStyle() and SetIndexColor() functions. Specify the buffer index, line style (e.g., STYLE_SOLID), and the desired color for each line.

Finally, we'll add some additional code to make the indicator more visually appealing. We can hide the indicator's name by setting the indicator_shortname property to an empty string. Additionally, we can add a chart label with the current value of the upper band using the ObjectCreate() and ObjectSetText() functions.

Compile the code once again to ensure there are no errors or warnings.

Congratulations! You have successfully coded the custom Donchian Channel indicator. Now, you can use this indicator in your Expert Advisor to implement your trading strategy.

In the next step, we'll move on to coding the Expert Advisor (EA) that will utilize the Donchian Channel indicator for executing trades based on the breakout strategy. Open a new file in the MetaEditor, name it "DonchianChannelEA," and select the "Expert Advisor" option. Click "Next" and "Finish" to create the file. Clean up the initial code by removing unnecessary comments and aligning the brackets.

First, we'll define the input parameters for our EA. These will include the lot size, stop loss, take profit, and the period and offset for the Donchian Channel. Define these inputs using the appropriate types and set default values and comments for each input. Next, we'll code the OnInit() function. Inside this function, we'll initialize the Donchian Channel indicator by calling the iCustom() function with the necessary parameters.

Create variables to store the indicator handle, upper band values, and lower band values. Use the ArraySetAsSeries() function to set the arrays as series to ensure correct indexing. Now, let's move on to coding the main OnTick() function, which will handle the trading logic.

Start by checking if there are enough bars to calculate the Donchian Channel. If not, return with zero. Get the current upper and lower band values from the indicator using the CopyBuffer() function. Now, we'll check for a buy signal. If the price crosses above the upper band, open a sell position using the OrderSend() function. Set the appropriate order type (OP_SELL), lot size, stop loss, and take profit levels. Remember to handle potential errors returned by the OrderSend() function.

Similarly, check for a sell signal. If the price crosses below the lower band, open a buy position using the OrderSend() function. Set the appropriate order type (OP_BUY), lot size, stop loss, and take profit levels.

Compile the code to ensure there are no errors or warnings.

That's it! You have completed the coding for the Donchian Channel Expert Advisor. You can now test the EA on a demo account or backtest it using historical data to evaluate its performance. Remember to thoroughly test your EA and consider implementing risk management techniques before using it on a live trading account. Please note that the code provided is a basic implementation and may require further modifications or enhancements to suit your specific trading requirements.

Awesome Donchian Channel trading bot in mql5! | MT5 programming
• 2023.02.02