Programming tutorials - page 6

 

Stunning high / low breakout trading bot in mql5! | Part 1



Stunning high / low breakout trading bot in mql5! | Part 1

Toby, in this video, I want to introduce a new project that involves using highs and lows to create a profitable breakout strategy. The main idea is to identify the highest and lowest prices of the current symbol and use these levels to determine potential breakout points. Let's take a look at the chart to understand how this works.

To begin, we observe the last n bars and identify the highest and lowest prices. If the price breaks above the high level, we take a buy position. Conversely, if the price breaks below the low level, we take a sell position. It's a simple concept, but we'll enhance it by adding stop loss and take profit levels in points. Additionally, we'll implement filters to refine the strategy and avoid trading on every high and low.

Let's wait for a trading opportunity to demonstrate the concept. Here, we have a sell position as the price broke below the low level, and we closed the trade with a profit. This serves as the basic foundation for our strategy, and we can further improve it by incorporating additional components.

Now, let's switch to the Meta Editor and begin coding. We'll create a new file in the YouTube folder and name it "Toby's Breakout EA." In the file, we'll define the necessary inputs for our EA. These include the magic number, lot size, number of bars to consider, stop loss, and take profit. We'll set appropriate default values and provide comments to explain each input.

Next, we'll move on to the onInit function, where we'll check the user inputs to ensure they are valid. We'll create a separate function called checkInputs to handle this validation. If any of the inputs are incorrect, we'll display an error message and prevent the EA from starting.

Within the onInit function, we'll also set the magic number of our trade object using the input provided. This will allow us to filter and manage positions opened by our EA later on.

Now, let's examine the onTick function. We'll begin by saving the current tick and the previous tick values. This will help us track price movements and determine if we cross any important levels. We'll use the SymbolInfoTick function to retrieve the current tick, and if any error occurs, we'll display an error message and stop the EA.

Afterward, we'll include three custom functions: countOpenPositions, normalizePrice, and closePositions. These functions will help us manage our positions, count the number of open positions, normalize prices, and close positions when necessary.

Returning to the onTick function, we'll start by counting the open positions for both buy and sell. If an error occurs during this process, we'll stop the EA without displaying an error message since it's already handled in the custom function. We'll then check if there are any open buy positions and if the high level is not zero. This ensures that we have set the high level and there are no existing buy positions.

From here, we can continue coding the logic of the breakout strategy. We'll implement similar checks for the sell positions and the low level. These if statements will help us determine whether to take a buy or sell position based on the breakout of the respective levels.

Once we have a basic structure in place, we can further enhance the strategy by adding more components and filters. This can include additional input parameters and conditions to refine the trading signals and improve overall performance.

That covers the initial coding process. By following these steps, we can create a breakout EA based on highs and lows, which can serve as a starting point for further development and optimization.

The algorithm:

  1. First, we define the levels at which we want to open and close positions: the high level and the low level.
  2. We initialize variables to keep track of the number of open buy and sell positions (count_buy and count_sell).
  3. In each tick of the market, we retrieve the previous tick's data, including the bid and ask prices.
  4. To check for a potential buy position, we compare the previous tick's ask price with the high level. If the ask price is greater than the high level and there are no open buy positions, we open a buy position using the specified lot size, stop loss, and take profit. We increment the count_buy variable and display a message indicating that a buy position has been opened.
  5. To check for a potential sell position, we compare the previous tick's bid price with the low level. If the bid price is less than the low level and there are no open sell positions, we open a sell position using the specified lot size, stop loss, and take profit. We increment the count_sell variable and display a message indicating that a sell position has been opened.
  6. We also need to consider closing positions if necessary. If there are any open buy positions and the previous tick's ask price falls below the high level, we close all buy positions. We decrement the count_buy variable and display a message indicating that a buy position has been closed.
  7. Similarly, if there are any open sell positions and the previous tick's bid price goes above the low level, we close all sell positions. We decrement the count_sell variable and display a message indicating that a sell position has been closed.

The algorithm continuously checks for potential entry and exit points based on the bid and ask prices in relation to the predefined high and low levels. It opens positions when the conditions are met and closes positions when the prices move in the opposite direction.

Stunning high / low breakout trading bot in mql5! | Part 1
Stunning high / low breakout trading bot in mql5! | Part 1
  • 2023.02.09
  • www.youtube.com
Today I will show you how to code a simple high / low breakout trading bot for Metatrader 5. In this first part we will calculate the high and low level. Th...
 

High / low breakout trading bot mql5 | Part 2



High / low breakout trading bot mql5 | Part 2

In this video, we continue working on our black Audi with a high-low coating. As a follow-up to our previous session, we will now incorporate the trade logic and introduce some additional components.To begin, we'll calculate the stop loss for our positions. If the stop loss input is zero, we set the variable "SL" to zero, indicating that there is no stop loss. Otherwise, we set it to the current bid price minus the input stop loss multiplied by the points value.

Next, we calculate the take profit. If the take profit input is zero, we set the variable "TP" to zero. Otherwise, we set it to the current ask price plus the input take profit multiplied by the points value. To ensure consistent price values, we normalize the stop loss and take profit using the "normalized price" function.

With the trade logic in place, we use the trade object, which was declared previously using the cTrade class, to open positions. For a buy position, we use the current symbol, input lots for lot size, current bid price for the price, stop loss variable for the stop loss, and take profit variable for the take profit. Similarly, for a sell position, we use the current ask price for the price. To differentiate this position from others, we add a comment indicating that it belongs to our "High-Low Record EA" expert advisor.

After compiling the code, we switch to MetaTrader for testing. We set up a visual test, specifying the time frame and period. With the default inputs, we run the test and observe the high and low values. By using the "Open Price Only" mode, we can see the positions being opened when the high or low level is crossed. In the next step, we change the tick mode of the EA to only take action on open ticks. This provides a more reliable and faster testing environment for creating stable systems.

Moving forward, we implement an index filter to prevent trading on extreme points at the very beginning or end of the lookback period. We introduce an input called "Index Filter," which represents the percentage of bars within the lookback period that should be filtered. For example, if the lookback period is 50 bars and the index filter is set to 10, extreme points within the first five or last five bars will be filtered out. To visualize this range, we draw a rectangle on the chart. We add the necessary global variables, set their initial values, and make changes in the "OnTick" function to calculate the high and low indices using the "I Highest" and "I Lowest" functions.

Additionally, we update the "CheckInputs" function to include the "Index Filter" input and validate its value. We also create a new function called "CheckIndexFilter" that checks if an extreme point should be filtered based on the index and the filter settings. To complete the implementation, we compile the code and proceed to a visual test. We verify if the positions are opened only when the extreme points are within the defined range, as per the index filter. In the following segment, we plan to modify the EA's tick mode to better suit our requirements. We will switch to open tick mode, allowing the EA to operate exclusively on open ticks, enhancing system reliability and efficiency.

After modifying the tick mode to open tick mode, we proceed with further enhancements to our EA. One of the improvements we'll make is the addition of a time filter. To implement the time filter, we introduce two new inputs: "Start Hour" and "End Hour." These inputs allow us to specify the time range during which trading should be allowed. For example, if we set the start hour to 8 and the end hour to 18, the EA will only open positions between 8 AM and 6 PM. To incorporate the time filter, we update the "CheckInputs" function to validate the new inputs and ensure that the start hour is less than the end hour. We also modify the "OnTick" function to check the current time against the specified range before opening positions.

With the time filter in place, we compile the code and run a visual test to verify that positions are only opened within the specified time range. Next, we move on to another enhancement: adding a spread filter. The spread filter allows us to define a maximum allowable spread, beyond which the EA will refrain from opening positions. To implement the spread filter, we introduce a new input called "Max Spread." In the "OnTick" function, we include a check to ensure that the current spread is within the allowed range before opening positions.

We also update the "CheckInputs" function to validate the "Max Spread" input and make sure it is a positive value. Once the spread filter is implemented, we compile the code and perform a visual test to confirm that positions are only opened when the spread is below the specified maximum. Lastly, we introduce a feature to track and display the number of opened positions on the chart. We create a new global variable called "Position Count" and initialize it to zero. In the "OnTick" function, we increment the position count each time a position is opened.

To display the position count on the chart, we utilize the "ObjectSetText" function to create a text object that shows the current count. We update the text object with the latest count value on each tick. Once the code is compiled, we run a visual test to observe the position count displayed on the chart and ensure it accurately reflects the number of opened positions.

With these enhancements implemented, we have significantly improved the functionality and performance of our EA. The time filter, spread filter, and position count display provide greater control and visibility over the trading process.

In the next video, we will explore additional optimizations and fine-tuning techniques to further enhance the performance of our EA.

High / low breakout trading bot mql5 | Part 2
High / low breakout trading bot mql5 | Part 2
  • 2023.02.12
  • www.youtube.com
Today I will show you how to code a simple high / low breakout trading bot for Metatrader 5. In this second part we will code the trade logic to open positi...
 

Amazing high / low breakout trading bot mql5 | Part 3



Amazing high / low breakout trading bot mql5 | Part 3

In today's video, Toby continues the development of the high-low breakout EA for MK5. He introduces two new components to the strategy and also performs multiple backtests at the end.

Toby starts by compiling the EA to ensure it is in working condition. He then adds an input for a trailing stop loss to enhance the strategy's effectiveness as a breakout and trend-following system. The input is a boolean variable that can be activated or deactivated. Toby also creates a function called "updateStopLoss" to calculate and update the stop loss values for each position.

To implement the trailing stop loss, Toby copies the "updatePosition" function from another EA and modifies it accordingly. He adds a parameter for the stop loss distance and adjusts the calculation of the new stop loss value based on this input. He also incorporates a function called "normalizedPrice" to ensure the stop loss value is normalized. After making these changes, Toby compiles the code again to ensure there are no errors.

Next, Toby moves to the "OnTick" function, where he integrates the "updateStopLoss" function. He adds an if statement to check if the trailing stop loss is active, and if so, calls the "updateStopLoss" function to trail the stop loss values. He also ensures that the function is applied to both buy and sell positions.

After compiling the code, Toby proceeds to add the next component, a size filter, to the strategy. The size filter allows filtering out channels where the high and low values are too far apart, indicating a larger range. Toby adds an input for the size filter in points and adjusts the code accordingly to check if the channel size exceeds the specified limit. He also incorporates the size filter into the visualization of the high and low lines.

Toby then does a visual test using the Strategy Tester to confirm that both the trailing stop loss and size filter are working correctly. He observes the behavior of the stop loss and the color changes in the lines based on the size filter condition.

In the final part of the video, Toby performs backtests to evaluate the performance of the EA over the past 10 years. He sets the optimization criteria as the recovery factor and uses a specific symbol and time frame. Toby plans to use the remaining years as an out-of-sample test.

Toby makes several improvements to the high-low breakout EA, including the addition of a trailing stop loss and a size filter. He also demonstrates how to conduct backtests to assess the EA's performance.

Amazing high / low breakout trading bot mql5 | Part 3
Amazing high / low breakout trading bot mql5 | Part 3
  • 2023.02.16
  • www.youtube.com
Today I will show you how to code a simple high / low breakout trading bot for Metatrader 5. In this third part we will code a trailing stop loss and add a ...
 

Let's code the ultimate candlestick pattern EA in mql5! | Part 1



Let's code the ultimate candlestick pattern EA in mql5! | Part 1

Hey, this is Toby, and in this video, I'm starting a new EA coding project on my channel. We'll be focusing on Candlestick patterns and creating an EA that can trade various patterns such as Doji, Morning Star, Rising Star, and many others. The EA will also have a panel to display different conditions. I've already conducted some preliminary testing with the EA, and the results have been quite interesting, especially across different symbols. I believe this approach can lead to a highly effective strategy. Let's dive in!

Before we begin coding the EA, let's discuss the general strategy idea. It's crucial to understand what we aim to create as we progress. To illustrate the concept, I've created a simple diagram. Our EA will work exclusively with the open price of each bar. For example, let's consider the current bar (index 0) and the previous bar (index 1). We want to create an EA that can trade various chart patterns or Candlestick patterns, like Doji, Morning Star, Evening Star, Rising Star, and many more.

To achieve this, we'll define different conditions. For instance, we can set a condition where the high price of bar 2 must be higher than the highest price of bar 1. Another condition could be that the open price of bar 3 must be lower than the close price of bar 3, indicating a bullish candle. By combining these conditions, we can trigger a buy trade at the open of the next bar. We can apply similar conditions in reverse for sell signals.

Additionally, I want to consider not only the Open, High, Low, and Close prices of each Candlestick but also other factors like the range size or body size. For example, we can calculate the body size by dividing it by the total range of the Candlestick. This calculation can help us identify Doji bars. We can even set specific values, like requiring a body size greater than 50 points. With these options, we can create and test various patterns using a single EA. It promises to be an exciting journey!

Now, let's move on to the MetaEditor and start coding. But before we begin, I'd like your feedback. If you find these videos helpful and would like to sleep well tonight, please leave a like. Also, I'm considering switching between dark mode and the default white background. I'll create a poll for you to vote on your preference. Let me know in the comments if you can read everything correctly in dark mode.

Alright, let's get coding! In the MetaEditor, I'll create a new EA under my YouTube folder. I'll name it 'Candle Pattern EA.' We'll start with a clean template, removing unnecessary comments and organizing the code structure. After compiling and ensuring there are no errors, we'll proceed with the next steps.

We'll define some key parameters in the inputs section, such as the magic number, which should be a unique identifier for this EA to avoid conflicts with other EAs running on the same MetaTrader instance. Let's assign a random number to it.

That covers the initial setup and input parameters. We're now ready to move on to the next part. Stay tuned!

Let's code the ultimate candlestick pattern EA in mql5! | Part 1
Let's code the ultimate candlestick pattern EA in mql5! | Part 1
  • 2023.03.01
  • www.youtube.com
Today I will show you how to code a candlestick pattern trading bot for Metatrader 5. In this first part we will create the conditions for the candlestick pa...
 

Candlestick pattern EA in mql5! | Part 2



Candlestick pattern EA in mql5! | Part 2

In today's video, I'm Toby, and we'll continue coding our simple Candlestick pattern Expert Advisor (EA) in MetaTrader 5. We're now in the second part of this coding series, so if you missed the first part where I explained the strategy idea in more detail, you can find the link to that video here. Before we start coding, I want to share the results of a recent poll I conducted on YouTube about the preferred color theme for recording videos. Out of 140 votes, the majority of people (90) preferred the dark background, while 50 people preferred the white background. I personally find the dark background easier on the eyes and use it for recording my own EAs as well.

Another thing I wanted to mention is that I recently set up Visual Studio Code for MQL5. If you're interested in using Visual Studio Code for your coding projects, let me know in the comments, and I'll make a video about it.

Now, let's get back to coding our EA. In the previous video, we left off at the inputs for condition one. We'll now create another condition and add an input for condition two. We'll copy the section for condition one and rename it to condition two, making the necessary changes to the input variables. For now, we'll keep it simple with just two conditions, but we can add more in the future. After making these changes, we'll compile the code to ensure there are no errors or warnings.

Some viewers requested an increase in the font size for better readability. While I prefer seeing more code on the screen, I understand the need for larger font sizes. However, for now, we'll stick with the current font size. If necessary, I can make adjustments in the future.

Next, we'll link the inputs to our condition array, which we created in the global variable section. We'll create a custom function called "setInputs" to accomplish this. This function will be called before checking the inputs. After writing the code for the setInputs function, we'll compile the code again to verify its correctness.

Moving on, we'll check the inputs to ensure they meet the required criteria. We'll use an if statement for each input to perform the necessary checks. If any input is found to be invalid, we'll display an alert to the user and return false from the checkInputs function. We'll start by checking the magic number, ensuring it's not below or equal to zero. Then we'll proceed to check the lot size, stop loss, and take profit inputs. Additionally, we'll need to add a check for the condition array, which we'll address later.

To make the code more modular, we'll use a setInputs function to set the magic number for our trade object. This will be beneficial when searching for positions or handling trade-related operations. After making this change, we'll compile the code again to confirm its accuracy.

Now, let's move to the onTick function, where the EA's main operations take place. Firstly, we'll check if the current tick is a bar open tick using our isNewBar function. If it returns false, indicating it's not a bar open tick, we'll simply return and wait for the next tick.

Next, we'll obtain the current symbol's tick. This will provide access to bid, ask, and other tick-related information. We'll use the SymbolInfoTick function and store the result in a variable. If this operation fails, we'll display a message indicating the failure and return from the onTick function.

Following that, we'll count the open positions using our countOpenPositions function. This will give us the number of open buy and sell positions at the current time. If this operation fails, we'll display an error message indicating the failure and return from the onTick function.

After obtaining the open position count, we'll check if there are any open positions. If there are, we'll display a message indicating the number of open positions. Otherwise, we'll proceed to the next step.

Now, we'll loop through each open position using a for loop. Inside the loop, we'll retrieve the position information using the PositionGetTicket function. We'll store the ticket number in a variable and display a message with the ticket number for debugging purposes.

Next, we'll check the position's type (buy or sell) using the PositionGetInteger function and the POSITION_TYPE property. If the position is a buy position, we'll execute the necessary code for buy positions. Similarly, if the position is a sell position, we'll execute the code for sell positions.

For buy positions, we'll check if the current bid price is lower than the stop loss level of the position. If it is, we'll display a message indicating that the stop loss level has been hit and close the position using the PositionClose function.

Similarly, for sell positions, we'll check if the current ask price is higher than the stop loss level of the position. If it is, we'll display a message indicating the stop loss level has been hit and close the position.

After closing any necessary positions, we'll move on to the next step, which is checking our conditions to determine if we should open a new position. We'll use the checkConditions function for this purpose. If the checkConditions function returns true, indicating that all conditions are met, we'll execute the necessary code to open a new position. Otherwise, we'll continue to the next tick.

In the code for opening a new position, we'll set the volume, stop loss, take profit, and other necessary parameters. We'll use the OrderSend function to send the trade request and open the position. If the trade request is successful, we'll display a message indicating the successful opening of the position. Otherwise, we'll display an error message.

Finally, we'll compile the code to ensure there are no errors or warnings, and if everything is successful, we'll be ready to test our EA on a demo or live account.

That concludes this video. In the next part, we'll continue building our EA by adding additional features and refining our strategy. If you have any questions or suggestions, please leave them in the comments below. Thank you for watching, and I'll see you in the next video!

Candlestick pattern EA in mql5! | Part 2
Candlestick pattern EA in mql5! | Part 2
  • 2023.03.05
  • www.youtube.com
Today I will show you how to code a candlestick pattern trading bot for Metatrader 5. This is a step by step coding tutorial for mql5.As an algo trader I dev...
 

Awesome candlestick pattern EA in mql5! | Part 3



Awesome candlestick pattern EA in mql5! | Part 3

In this video, Toby introduces himself and announces that the focus will be on continuing to develop the Candlestick pattern Expert Advisor (EA) in MetaTrader5. The goal is to write the core logic necessary for conducting the first backtest and obtaining a result. Toby encourages viewers to check out the previous parts of the series if they haven't already.

Toby opens the Meta Editor and begins coding where he left off in the previous video. He explains that they have already implemented the code for opening buy and sell positions, but now they need to add the condition checks. To do this, Toby plans to create a custom function that can be called to check the conditions for both buy and sell trades.

Before starting the coding process, Toby wants to ensure there are no mistakes in the existing code. He compiles the code to check for errors or warnings.

Next, Toby proceeds to write the logic for the custom function called "check conditions." This function will iterate through each condition using a for loop. Inside the loop, they will call another custom function called "check one condition" to evaluate each individual condition.

Toby creates the "check one condition" function, which takes parameters for the buy/sell trade and the index of the condition to be checked. Inside this function, various checks are performed, such as determining if the condition is active. If a condition is inactive, the function will return true, indicating that it is not relevant.

To check the conditions, Toby needs to obtain the bar data. He declares a variable of type mql rates, which is a predefined structure containing the open, high, low, and close prices. They set the rates array as series and use the copy rate function to retrieve the necessary data for the conditions.

After successfully obtaining the bar data, Toby proceeds to set the values for variables A and B, which will be used for comparing and evaluating the conditions. The values are determined based on the mode of the condition, such as open, high, low, close, range, body, ratio, or value. The values are assigned accordingly, taking into account whether it is a buy or sell trade.

Once the values are set, Toby compiles the code to check for any mistakes or errors.

Toby repeats the process for the mode B conditions, making the necessary adjustments to variables and cases.

Finally, Toby concludes the video by ensuring there are no mistakes in the code and emphasizing the importance of understanding the code's logic.

Awesome candlestick pattern EA in mql5! | Part 3
Awesome candlestick pattern EA in mql5! | Part 3
  • 2023.03.09
  • www.youtube.com
Today I will show you how to code a candlestick pattern trading bot for Metatrader 5. This is a step by step coding tutorial for mql5. With this EA you can t...
 

Surprising results! Candlestick pattern EA in mql5! | Part 4


Surprising results! Candlestick pattern EA in mql5! | Part 4

Hi, I'm Toby. In today's video, we will continue coding the Candlestick pattern expert advisor (EA). We have some specific goals for this video. First, we will add a panel to the EA, which will display various conditions and their corresponding buy/sell signals. We will also perform additional input checks to ensure the EA's functionality. Finally, we will conduct a few backtests and share some interesting results with you. So let's get started.

Before we proceed, if you haven't watched the previous parts of this Candlestick pattern coding series, I recommend checking them out first. You can find the links in the description.

In this video, we will begin by creating a graphical panel for our EA. The panel will contain lines representing different conditions, with crosses indicating buy and sell signals. If the conditions are met, the EA will take trades in the specified direction. Additionally, we will implement input checks to facilitate optimization in the strategy tester.

To begin coding the panel, we'll open the MetaEditor and navigate to the include folder. Inside the include folder, we'll create a new folder named YouTube. Within the YouTube folder, we'll create the graphical panel file. We'll clear the default content of the file and include the necessary files for our panel.

Next, we'll define the necessary labels for our panel. Each label will represent a specific element, such as number, condition, buy, sell, etc. We'll also create arrays of labels to display multiple lines for each condition.

After defining the labels, we'll proceed to code the Panel class. This class will inherit from the CAppDialog class, granting us access to its members. We'll create a private section for the panel's labels and a few methods, including a constructor, destructor, onInit, update, and bannerChartEvent.

The constructor will initialize the panel, while the destructor will handle its cleanup. The onInit method will be called from the EA's onInit function and will create the panel. The update method will be invoked at every tick to update the panel's content. Finally, the bannerChartEvent method will handle events related to the panel.

Inside the createPanel method, we'll create the actual panel with the desired parameters, such as chart ID, name, sub-window, and coordinates. We'll ensure the panel is created successfully and return true if it is, or false otherwise.

Once the panel class is coded, we'll include it in our expert advisor file. We'll create an instance of the panel object and call its onInit method after setting the magic number. If the panel creation fails, we'll return an appropriate error message.

That's it for this part of our Candlestick pattern coding series. In the next video, we'll continue adding functionality to our EA and perform further testing. Stay tuned for more interesting results.

Surprising results! Candlestick pattern EA in mql5! | Part 4
Surprising results! Candlestick pattern EA in mql5! | Part 4
  • 2023.03.13
  • www.youtube.com
Today I will show you how to code a candlestick pattern trading bot for Metatrader 5. This is a step by step coding tutorial for mql5. With this EA you can t...
 

Code a custom criteria in mql5



Code a custom criteria in mql5

Hi, this is Toby. In this video, I will demonstrate how to code a custom criteria for your Expert Advisor Optimization in MQL5. We'll be using the Hilo bracket EA as an example. The goal is to create a custom criteria that considers both the profit factor and the number of trades in ranking the optimization results.

To begin, open your EA in the coding environment (such as Visual Studio Code) and save it with a new name. Next, add a predefined function called "OnTester" to your EA. This function will calculate the custom criteria and return its value. You can use the "TestStatistics" function to obtain the number of trades and the profit factor. Multiply these two values to calculate the custom criteria.

Compile the code to ensure there are no errors. Now, switch to MetaTrader and perform an optimization. Select your EA and choose "Custom Max" as the optimum search criteria to use your custom criteria. Start the optimization and wait for the results. You will see that the custom criteria is calculated based on the number of trades multiplied by the profit factor.

If you want to adjust the weight of the profit factor, you can use the "MathPower" function in your code. For example, you can raise the profit factor to the power of 4 to give it more weight. Recompile and run the optimization again to see the updated ranking.

Additionally, you can add an if statement to the code to exclude combinations with less than 100 trades. If the number of trades is below 100, you can return a value of zero. This ensures that only combinations with a sufficient number of trades are considered.

By following these steps, you can create your own custom criteria to rank and select the best optimization results for your Expert Advisor. Remember to save your modified EA with a new name before making any changes. If you found this video helpful, please leave a like, and feel free to share your requests or ideas for future videos in the comments. Thank you, and see you in the next video!

Code a custom criteria in mql5
Code a custom criteria in mql5
  • 2023.03.31
  • www.youtube.com
In this video I show you step by step how to code a custom criteria for the Metatrader 5 strategy tester. With a custom criterion, you can create your own ra...
 

Stochastic trading bot in mql5! | Part 1



Stochastic trading bot in mql5! | Part 1

In this video, I will demonstrate how to code a simple stochastic EA in MetaTrader 5. Towards the end of the video, we will also perform backtesting to evaluate the strategy's performance over the past 10 years.

Let's begin by understanding the general strategy idea. We will use the stochastic indicator, which is widely known. The EA will execute a buy trade when the stochastic crosses the lower level and a sell trade when it crosses the upper level. While looking at the chart, it's essential to remember that our brain tends to focus on the profitable trades, so it's crucial to code and backtest the strategy to evaluate its effectiveness.

Now, let's switch to Visual Studio Code to start coding the EA. We'll create a new file in the YouTube folder using the default MetaEditor and name it "Stochastic EA." Then, we'll open the file in Visual Studio Code and make some formatting adjustments to improve readability.

We'll organize the code into sections and start with the includes. We only need to include one file, "trades.mqh," which contains the CTrade class. After that, we'll define the inputs for our EA. We'll have a general section for inputs like magic number and lot size, followed by a trading section for stop loss, take profit, and closing trades on an opposite signal. Then, we'll have an input section specifically for the stochastic indicator, including the K period and upper level.

Once the inputs are defined, we'll move on to the global variables section, where we'll declare variables for the stochastic indicator handle, buffer, current tick, and trade object. After the global variables, we'll implement the onInit function. We'll start by checking the user inputs using the checkInputs function, which will ensure that the input values are within the allowed range. If any inputs are incorrect, we'll return "Init parameters incorrect."

Next, we'll set the magic number for the trade object using the input value provided by the user. Then, we'll create the indicator handle using the built-in stochastic function, specifying the symbol, period, K period, D period (set to 1 for no signal line), slowing value, MA method (SMA), and price field (low/high). We'll check if the creation of the indicator handle was successful. If it returns an invalid handle, we'll display an alert message and return "Init failed." Finally, we'll set the buffer using the arraySetAsSeries function to indicate that it is a time series.

Next, we'll define the checkInputs function, which will verify the validity of each input. We'll check if the magic number and lot size are within the allowed range and return false if they are not. Additionally, we can add further checks, such as ensuring the lot size is not greater than 10. With the onInit function and checkInputs function completed, we can now compile the code and proceed to the next steps in the video.

The function is designed to perform several steps. Firstly, it retrieves the current tick and stores it in the global variable "CT". Then, it proceeds to obtain the indicator values by using the "CopyBuffer" function. The function checks for errors and if successful, stores the values in the "Main" buffer. If there is an error, it prints a message and exits the function.

The next step involves counting the number of open positions. This is done using the "CountOpenPositions" function, and the count is stored in two integer variables, "CountBuy" and "CountSell". If there is an error in counting the positions, a message is printed and the function exits.

The function then checks for a buy or sell trade. If there is no open buy position (CountBuy is zero), it checks the indicator values to determine if a buy trade should be opened. The conditions for opening a buy trade are that the current indicator value is below a specified lower level and the previous indicator value is above the lower level. If these conditions are met, a message indicating the opening of a buy position is printed. Similarly, the function checks for a sell trade if there is no open sell position (CountSell is zero). The conditions for opening a sell trade are that the indicator value is above a specified upper level and the previous indicator value is below the upper level. If these conditions are met, a message indicating the opening of a sell position is printed.

After the trade logic is implemented, the function closes all sell positions if the input parameter "ClosedSignal" is set to true. It uses the "ClosePositions" function with the parameter value of 2 to close all sell positions. If there is an error in closing the positions, the function exits and prints a message. Next, the function calculates the stop loss and take profit values based on the input parameters. If the input stop loss value is zero, the stop loss is set to zero; otherwise, it is calculated based on the current tick price and the input stop loss value. The same process is followed for calculating the take profit value.

Before opening a position, the function normalizes the stop loss and take profit prices using the "NormalizePrice" function. If there is an error in normalization, the function exits. Finally, the function opens a position using the "PositionOpen" method of the trade object. The position is opened based on the type (buy or sell), volume, price, stop loss, and take profit values. An order comment is also included.

The function is compiled to ensure there are no errors, and then it can be tested in MetaTrader using historical data to see if the desired trade openings and closings occur according to the specified conditions. After opening a position, the function checks for errors using the "GetLastError" function. If there is an error, it prints a message and exits.

Finally, the function updates the global variables "LastTick" and "LastSignal" with the current tick and the signal type (buy or sell) respectively. This is done to keep track of the last processed tick and signal for future calculations.

This function retrieves the current tick, obtains indicator values, counts the number of open positions, checks for trade opportunities, opens positions based on specified conditions, closes sell positions if required, calculates stop loss and take profit values, normalizes the prices, opens positions, handles errors, and updates global variables.

To use this function in a MetaTrader 5 environment, you would need to integrate it into an expert advisor or script and customize the input parameters and indicator values according to your trading strategy. Additionally, you may need to implement other functions for managing positions, handling errors, and performing other trading operations.

Please note that the provided explanation is a general understanding based on the information provided, and the actual implementation may vary depending on the specific trading platform and programming language used.

Stochastic trading bot in mql5! | Part 1
Stochastic trading bot in mql5! | Part 1
  • 2023.04.13
  • www.youtube.com
Today I will show you how to code a stochastic trading bot for Metatrader 5. In this video we will create a fully working stochastic Expert Advisor for Metat...
 

Stochastic EA for MetaTrader 5 | Part 2



Stochastic EA for MetaTrader 5 | Part 2

In this video, Toby introduces himself as the host and mentions that they will be discussing a simple filter to improve trading strategies using the stochastic indicator. Toby mentions that the filter can be applied not only to the stochastic indicator but also to other indicators.

Toby explains that in the first part of the coding tutorial, they covered the core logic of the EA (Expert Advisor) and the indicator. In this part, they plan to add different entry signals and a filter to enhance the strategy. Before diving into coding, Toby emphasizes the importance of understanding the objective. They explain the components they want to add to the EA, including a second type of entry signal based on exiting the lower and upper zones of the indicator and the option to reverse the signals.

Toby then suggests switching to Visual Studio Code, an editor they recommend for MQL5 coding. They mention that the code they will be working on is the EA created in the first part. After compiling to ensure it's working correctly, they proceed with the coding.

The first step is to add an input for the signal mode using an enum (enumeration) for the different modes. They create the enum called "signal mode" with options such as "exit cross normal," "entry cross normal," "exit cross reversed," and "entry cross reversed." Toby explains the meaning of each option and how it affects the trading strategy.

After adding the enum, Toby adds it as an input in the code and assigns the default option as "exit cross normal." They also make sure to compile the code to check for any errors.

Next, Toby plans to use the signal mode in the OnTick() function to check for new signals. To simplify the code and avoid complex if statements, Toby decides to write a separate function called "check signal" to handle the signal logic. They explain that this function will return a Boolean value indicating whether a trade should be opened or not.

Toby creates the "check signal" function, which takes two parameters: a Boolean parameter to specify whether it's checking for a buy or sell signal and an integer parameter for the count of open positions. They add a comment explaining the purpose of the function and the parameters. They also add a check to return false if a position is already open.

Next, Toby adds code to check for crossovers based on the selected signal mode. They create Boolean variables for each crossover option, such as "upper exit cross," "upper entry cross," "lower exit cross," and "lower entry cross." They explain the logic behind each crossover condition, referencing the values of the stochastic indicator buffers.

After adding the crossover checks, Toby compiles the code to ensure there are no errors. They also add the missing if statement and fix the compilation errors.

With the "check signal" function and crossover checks in place, Toby returns to the OnTick() function and replaces the existing if statements for checking buy and sell positions with calls to the "check signal" function. They pass the appropriate parameters and open positions count to the function and check if it returns true before opening a trade.

After compiling the code again, Toby switches to MetaTrader to test the logic of the EA. They select the EA, choose the open price only mode, and enable the visual mode for testing. They configure the input parameters for each signal mode and run the visual test. Toby explains that it's important to test the EA thoroughly to ensure it behaves as expected.

Toby concludes that all signal modes are working correctly based on the visual test results. They suggest moving on to adding a filter in the next part of the tutorial.

Currently, we retrieve the values "one" and "two" to check for a signal. However, I want to modify this so that we start at index 0 with our buffer. Additionally, we should retrieve three values for the check signal. If our check clear bars filter is active, we may need additional values. To implement these changes, we need to modify the code.

First, let's scroll up to where we retrieve the indicator values. In the "untick" function, where we have the line "get indicator values," we need to make some changes. The first parameter represents the buffer number of the indicator. We are only interested in the main line, which is at index 0. So that remains the same. However, the start position is currently set to index 1, and we retrieve two values. We want to change the start position to index 0 and retrieve at least three values. So we modify the code to start at index 0 and retrieve three values: zero, one, and two.

If our check clear bars filter is active, we need to retrieve additional indicator values to check the filter. We need to retrieve "three" plus our input clear bars value. For example, if the input clear bars value is set to 5, we need a total of eight values. So we modify the code accordingly to retrieve values starting from index 0 up to the required number of values.

After making these changes, we need to store the retrieved values in the buffer named "Main." Additionally, we should check if the function was successful in retrieving the requested values, which is three plus our input clear bars value. We modify the code to include this check.

Next, we need to update the code where we check the signal. Instead of accessing buffer Main at index 0, we now need to access it at index 1 and 2 for the crossover check. We replace all instances of index 0 with 1, and index 1 with 2.

Now we have the correct indicator values, and we can proceed to the for loop. We should compile the code to ensure there are no mistakes.

In the for loop, we want to check our clear bars filter starting at index 3. This is the position after the signal crossover check. We continue this loop until our counter is below three plus the clear bars value. For example, if the clear bars value is set to 5, the counter would be 8. This means we check up to index 7, the last value in our loop. The purpose of this loop is to ensure that there are no crossovers of the upper line within these bars. We update the code to reflect these changes.

Inside the for loop, we first check the upper level. We compare the value at buffer Main[i-1] with the input upper level. If it is greater and the value at buffer Main[i] is less than or equal to the input upper level, we have a crossover. We also check the opposite condition for a crossover in the other direction. We modify the code accordingly.

After the for loop, we add another if-else statement. If our input clear bars reverse is true, we return true because we want a crossover when the filter is reversed. Otherwise, we return false.

Finally, we add a similar if-else statement for the lower level check. We copy the existing if statement and make the necessary changes for the lower level check.

After making these changes, we compile the code again to ensure there are no mistakes. Now, we can use the check clear bars function in our OnTick function.

In the OnTick function, we add the check clear bars function in the if statement where we check the signal.

Let's continue with the optimization process. We have selected the Euro/Dollar symbol and the time frame starting from 2019. We will use the open price only and the fast generic algorithm. Our optimization goal is to find the best parameters for our clearbars filter.

Before starting the optimization, let's define the parameters we want to optimize. In this case, we will optimize the clearbars filter's lookback period, which determines the number of bars to consider for the filter. We will test values ranging from 5 to 20, incrementing by 5. Additionally, we will optimize the upper and lower level thresholds for the filter, testing values from 50 to 150, incrementing by 25.

Now, let's run the optimization and analyze the results. We will look at the net profit, total trades, and the profit factor to evaluate the performance of each parameter combination. Based on these metrics, we can identify the best parameter values that yield the highest profit.

After running the optimization, we can examine the results and identify the parameter values that performed the best. We might find that a lookback period of 10, upper level threshold of 100, and lower level threshold of 75 provided the highest net profit and profit factor.

Once we have identified the optimal parameter values, we can use them to backtest our strategy on a larger data set or deploy it on a live trading account.

Remember that optimization results are based on historical data and may not guarantee future performance. It is important to continuously monitor and evaluate the strategy's performance and adjust the parameters as needed.

With the optimized parameters, we can further refine our strategy and explore other possibilities for improvement. We can consider adding additional filters or conditions to enhance the strategy's effectiveness.

In conclusion, the optimization process helps us find the best parameter values for our clearbars filter, improving the strategy's performance and potentially increasing profitability. It is a valuable tool in the development and refinement of trading strategies.

Stochastic EA for MetaTrader 5 | Part 2
Stochastic EA for MetaTrader 5 | Part 2
  • 2023.05.01
  • www.youtube.com
Today I will show you how to code a stochastic trading bot for Metatrader 5. In this video we will improve our stochastic Expert Advisor for Metatrader 5. We...
Reason: