Programming tutorials - page 4

 

C++ FUNCTIONS (2020) - What is recursion? Learn recursive functions!


C++ FUNCTIONS (2020) - What is recursion? Learn recursive functions! PROGRAMMING TUTORIAL

Recursion is a process in which a function invokes itself, and the corresponding function is called a recursive function.

Recursion is one of those topics in programming that often confuses students, and in this video, I'm explaining how recursion works and also comparing different solutions to the same problem (using loops and using recursion).

C++ FUNCTIONS (2020) - What is recursion? Learn recursive functions! PROGRAMMING TUTORIAL
C++ FUNCTIONS (2020) - What is recursion? Learn recursive functions! PROGRAMMING TUTORIAL
  • 2020.10.28
  • www.youtube.com
Recursion is a process in which a function invokes itself, and the corresponding function is called a recursive function.Recursion is one of those topics in ...
 

How to build an ATM application in C++? (For beginners)


How to build an ATM application in C++? (For beginners) - PROGRAMMING TUTORIAL (2020)

Welcome to my channel! I'm Saldina, and I create programming-related videos. If you're interested in that, consider subscribing to my channel and giving this video a thumbs up.

In this video, I'll show you how to build an ATM application. First, let's plan the functionalities of the application. We'll need the following:

  1. Check balance
  2. Deposit money
  3. Withdraw money
  4. Show menu

Now, let's start by implementing the "Show Menu" function. We'll create a function called "showMenu" that displays the menu options to the user.

After defining the menu, we'll invoke the "showMenu" function to display it. Then, we'll allow the user to choose an option.

To handle the user's choice, we'll use a switch case. For each case, we'll perform the corresponding action. In the case of option 1, we'll display the balance. In the case of option 2, we'll ask for the deposit amount and update the balance accordingly. In the case of option 3, we'll ask for the withdrawal amount and check if it's valid before updating the balance. Finally, we'll add an option 4 to exit the program.

To enable the user to interact with the menu repeatedly, we'll use a do-while loop. The loop will continue until the user selects option 4.

Feel free to enhance the program by adding more features, such as transferring money between accounts. Share your code in the comments, and I'll review it. Don't forget to like, subscribe, and hit the bell icon. See you in the next video!

How to build an ATM application in C++? (For beginners) - PROGRAMMING TUTORIAL (2020)
How to build an ATM application in C++? (For beginners) - PROGRAMMING TUTORIAL (2020)
  • 2020.08.03
  • www.youtube.com
📚 Learn how to solve problems and build projects with these Free E-Books ⬇️C++ Lambdas e-book - free download here: https://bit.ly/freeCppE-BookEntire Objec...
 

C++ FUNCTIONS (2020) - What are generic functions and templates? PROGRAMMING TUTORIAL


C++ FUNCTIONS (2020) - What are generic functions and templates? PROGRAMMING TUTORIAL

Hello everyone, welcome to my channel! My name is Saldina and I create programming-related videos. If you're interested in programming, please subscribe to my channel and give this video a thumbs up. Your support helps me reach more people and spread programming knowledge.

In this video, I want to talk about generics and templates in C++. Generics allow us to use the same code with different data types. This means that we can have a single function that works with different types of data.

Let's take an example to understand this concept. Suppose we want to create a function that swaps the values of two variables. Initially, we create the function for swapping two integer variables, but we can extend it to work with other data types as well.

To create a generic function, we use templates in C++. We define a template type using the keyword "template" followed by the type name, commonly referred to as "T." Inside the function, we replace the specific data type with "T." This makes the function generic and able to work with different data types.

We no longer need to create separate functions for each data type. The template function can be used with any data type that supports the swapping logic.

To test the function, we create variables of the desired type and pass them to the generic swap function. The type inference mechanism in C++ allows us to omit specifying the type explicitly.

By using generics and templates, we can eliminate code duplication and write more flexible and reusable code. This approach allows us to handle different data types without creating separate functions for each type.

I hope this video has helped you understand the concept of generics and templates in C++. If you found it useful, please subscribe to my channel and give this video a thumbs up. Your support is greatly appreciated. Thank you for watching, and I'll see you in my next video. Goodbye!

C++ FUNCTIONS (2020) - What are generic functions and templates? PROGRAMMING TUTORIAL
C++ FUNCTIONS (2020) - What are generic functions and templates? PROGRAMMING TUTORIAL
  • 2020.11.11
  • www.youtube.com
Generic programming is used to increase the efficiency of the code. The advantage of writing generic code is code reusability (which means that code that was...
 

Lambda expressions in modern C++ (in depth step by step tutorial)


Lambda expressions in modern C++ (in depth step by step tutorial)

Welcome to my channel, everyone! In this video, I'll be discussing a crucial topic in modern C++, which is lambda expressions, also known as lambdas. You've probably heard of lambdas before, and today I'll explain everything you need to know to start writing faster and cleaner code using lambdas in modern C++.

I'll cover the most important concepts, but keep in mind that lambdas are a broad topic with a lot to learn. If you want additional examples and practice, I'll provide a free book in the description that focuses on lambdas in modern C++. Feel free to check it out.

Lambda expressions were introduced in modern C++ and are available in C++11 and above. Their main purpose is to allow you to write inline anonymous functions. So what are inline anonymous functions? Regular functions let you write code once and reuse it by invoking the function whenever you need that code again, eliminating the need for redundant code.On the other hand, an inline function is a small, simple function that is not meant to be reused like regular functions. They are often used for small snippets of code that don't require a name and are not worth the effort of creating a separate function. This is where lambdas shine as they provide a way to write unnamed functions that are concise, easy to read, fast to execute, and keep everything in one place.

Now, let's dive into the code. For this demonstration, I'll be using C++Builder, the ideal IDE for building C++ user interface applications. If you're interested in learning about C++ user interface applications, I'll provide a link in the description where you can download C++Builder.To get started, let's create a console application. Click on "File," then "New Other," and select "Console Application." Make sure C++ is selected and click "OK." Here's our initial code. Let's make a few additions to it.

First, I'll add a "system pause" command to keep the console window open after executing the code. Next, I'll include the "iostream" library for input/output operations. Now, our code is ready to run, and if we execute the program, we'll see the "Hello, World!" message in the console.Now, let's take a look at the structure of a lambda expression. I'll remove the previous code, and we'll start with a simple example. To create a lambda, we use the following syntax: angled brackets (capture clause), parentheses (parameters), and curly brackets (function definition).

Inside the capture clause, we can specify variables from the enclosing scope that we want to use inside the lambda. For now, let's leave the capture clause empty and focus on the parameters. We can define the parameters inside the parentheses. In this example, I'll use a single parameter, "p." Finally, we define the lambda's function body inside the curly brackets. Now, let's create an example where we'll encounter a problem and then solve it using lambdas. We'll work with a vector, so we need to include the "vector" library. I'll create a vector of integers called "v" and initialize it with some values. Next, I'll introduce a useful function from the "algorithm" library called "for_each." This function iterates over elements in a range, such as our vector, and applies a given function to each element.

Inside the "for_each" function, we'll specify the range using "v.begin()" and "v.end()." Now, let's define what we want to do with each element. Initially, I'll show you a problem with the code and then introduce lambdas as a solution. I've added a structure with an overloaded operator that prints the parameter. We expect the "for_each" function to print all the elements in the vector. If we execute the code, we'll see that it doesn't work as expected. It only prints the last element. This is because the overloaded operator is passed by value and copies the parameter for each call, resulting in incorrect output. To fix this, we can replace the overloaded operator with a lambda expression. I'll copy the lambda expression syntax we discussed earlier and paste it inside the "for_each" function. Now, let's execute the code again.

As you can see, the lambda expression works perfectly, and it prints all the elements in the vector. The lambda expression simplifies the code and improves readability. It also ensures that the correct parameter is passed to each call, avoiding the issue we encountered earlier. Now, let's explore another useful feature of lambdas, which is their ability to capture variables from the enclosing scope. This feature allows lambdas to access variables and use them inside the lambda. However, by default, lambdas capture variables by value, meaning they create a copy of the variable.

In our next example, I'll create a variable called "multiplier" and set it to 2. Inside the lambda, I'll use this variable to multiply each element in the vector. This time, I'll use a range-based for loop instead of the "for_each" function for demonstration purposes. If we execute the code, we'll see that the elements in the vector are multiplied by 2, thanks to the captured variable. However, there's a limitation with capturing variables by value. We cannot modify the captured variable inside the lambda.

To overcome this limitation, we can capture the variable by reference, allowing us to modify its value. I'll demonstrate this by adding an increment operation to the lambda expression. Now, if we execute the code, we'll see that the elements in the vector are multiplied by 2 and then incremented by 1. Capturing variables from the enclosing scope provides flexibility and allows lambdas to work with external data seamlessly. It's important to keep in mind that capturing variables by reference can have implications, such as lifetime management and potential data races. So be cautious when using this feature and ensure that the captured variable remains valid during the lambda's execution.

To summarize, lambda expressions are powerful tools in modern C++ for writing concise and readable code. They allow you to create inline anonymous functions, reducing the need for separate functions for small code snippets. Lambdas can also access variables from their enclosing scope, providing flexibility and enhancing code reuse.

I hope you found this video helpful in understanding lambda expressions in modern C++. If you have any questions, feel free to ask in the comments below. Don't forget to like this video and subscribe to my channel for more C++ tutorials. Thank you for watching, and happy coding!

Lambda expressions in modern C++ (in depth step by step tutorial)
Lambda expressions in modern C++ (in depth step by step tutorial)
  • 2021.11.17
  • www.youtube.com
A lambda is an unnamed function that is used for short snippets of code that cannot be reused and are not worth naming. It makes the code cleaner, easier to ...
 

Visual Studio Tips and Tricks for Professionals - Visual Studio Tutorial



Visual Studio Tips and Tricks for Professionals - Visual Studio Tutorial

Hello everyone! My name is Leslie Richardson, and I work as a program manager on the Visual Studio Debugging and Diagnostics team. In this video, I'm excited to discuss a new feature in Visual Studio 2019 called the search feature for Autos, Locals, and Watch windows. This feature is designed to greatly enhance your debugging experience and save you valuable time, making you more productive.

To demonstrate this feature, let's consider a scenario where I have a .NET Core application open in Visual Studio 2019. Within this application, I have a list that contains multiple recipe objects. The challenge I face is locating specific recipes within this list, which can be quite tedious, especially when the list contains 61 objects. Manually expanding each object, finding the title property, and checking if it matches my search criteria, such as "salad," is a time-consuming task.

To simplify this process, I will utilize a feature called "Debugger Display." This feature allows me to customize how objects are displayed in various debugger windows, including Autos, Locals, and Watch windows. By adding the "Debugger Display" attribute to the class definition of my objects, I can specify which property should be shown in the value column of these windows. In this case, I want to view each recipe by its title, so I set the "Debugger Display" attribute to display the recipe title property.

Now, when I expand the recipes list again, I can immediately see the title of each object, making it much easier to locate the desired recipes without expanding each one individually. This is a significant improvement, but with 61 items, it can still take time to find the specific recipes I'm interested in. This is where the search feature for the watch window comes in handy.

Instead of manually scrolling or expanding the list, I can simply use the search functionality provided. I enter my search term, such as "salad," and hit enter. Visual Studio immediately takes me to the first occurrence of the keyword, saving me a lot of time and effort. I can also utilize the "Find Next" button to navigate through other matches found by Visual Studio. To navigate backward and forward through the list of matches, I can adjust the search step parameter, which determines the depth of the search.

In addition to the search feature, I also want to mention that the Debugger Display feature is available for managed code users, such as those using C#, F#, or Visual Basic. For C++ users, there is an equivalent feature called NATVIS available. With NATVIS, you need to create a separate XML file where you can define properties to be displayed in the debugger windows.

I hope this explanation was helpful. Thank you for watching!

Now, let's explore how we can make Visual Studio's interface more organized and improve its performance. When we open solutions in Visual Studio, it remembers the state of documents, scroll positions, and expanded/collapsed sections in Solution Explorer from the last time we used it. While this can be useful, it also consumes CPU cycles and may not always be desirable. To start fresh and improve performance, we can change some settings.

In the Tools > Options menu, under the Projects and Solutions section, there are two settings to consider. The "Reopen documents on solution load" option remembers the previously opened documents, and the "Restore solution explorer project hierarchy state on solution load" option remembers the expanded/collapsed state of Solution Explorer. By unchecking these options, Visual Studio will not restore the previous state when opening a solution. Instead, it will start with a clean slate, without any documents open or expanded sections in Solution Explorer. This can help improve performance and provide a fresh start for each solution.

When working with Git in Visual Studio, there are several features that can improve your productivity and collaboration. The Git Changes window provides a comprehensive view of your Git repository and allows you to stage, commit, and push changes directly from within Visual Studio. You can access this window by going to View > Git Changes. Additionally, Visual Studio provides a built-in Git diff tool that highlights the differences between different versions of your code. You can access this feature by right-clicking on a file in the Solution Explorer and selecting "Compare with Unmodified" or "Compare with Latest."

Another useful feature in Visual Studio is the ability to refactor code. Refactoring helps improve the structure and readability of your code without changing its behavior. Visual Studio provides a variety of refactoring options, such as renaming variables or methods, extracting code into separate methods or classes, and reorganizing code blocks. To access these refactoring options, right-click on the code you want to refactor and select "Refactor" from the context menu. You can also use keyboard shortcuts for common refactoring operations, such as Ctrl + R, Ctrl + R to rename a symbol.

To further enhance your coding experience, you can take advantage of code snippets in Visual Studio. Code snippets are pre-defined code templates that can be quickly inserted into your code by typing a shortcut and pressing the Tab key. Visual Studio provides a wide range of built-in code snippets for different programming languages and frameworks. You can also create your own custom code snippets to automate repetitive coding tasks. To access and manage code snippets, go to Tools > Code Snippets Manager.

Debugging is an essential part of the development process, and Visual Studio offers powerful debugging capabilities. You can set breakpoints in your code to pause execution and inspect the state of variables and objects. While debugging, you can use the Watch window to monitor the values of specific variables or expressions. The Immediate window allows you to execute code and evaluate expressions while debugging. You can also take advantage of conditional breakpoints, which only trigger when a specific condition is met, and tracepoints, which print messages to the Output window without pausing the debugger.

Visual Studio also supports unit testing, which is crucial for ensuring the quality and correctness of your code. You can create unit tests using various testing frameworks, such as MSTest, NUnit, or xUnit. Visual Studio provides a Test Explorer window that displays all the available tests in your solution and allows you to run or debug them individually or in groups. You can use attributes to define test methods and assertions to verify the expected results. Visual Studio also offers code coverage analysis, which shows you how much of your code is covered by unit tests.

When working with large projects or solutions, it can be challenging to navigate and understand the codebase. Visual Studio provides several features to assist with code navigation and comprehension. The Solution Explorer allows you to explore the structure of your solution and quickly navigate to specific files or classes. You can also use the Navigate To feature (Ctrl + ,) to search for symbols, files, or types within your solution. The CodeLens feature displays additional information about your code, such as references, changes, and test coverage, directly within the editor.

For web development, Visual Studio offers excellent support for popular web technologies like HTML, CSS, and JavaScript. The HTML editor provides features like IntelliSense, code formatting, and the ability to preview your HTML pages directly within the editor. The CSS editor offers similar features, including color pickers, IntelliSense for CSS properties, and live preview of CSS changes. Visual Studio also supports JavaScript debugging, allowing you to set breakpoints, inspect variables, and step through your code to identify and fix issues.

Visual Studio has a vast ecosystem of extensions and plugins that can enhance your development experience. These extensions provide additional functionality, language support, and tools for specific frameworks or platforms. You can browse and install extensions directly from within Visual Studio by going to Extensions > Manage Extensions. Some popular extensions include ReSharper, which offers advanced code analysis and refactoring tools, and Visual Studio Code, which provides a lightweight, cross-platform code editor.

When working on collaborative projects, Visual Studio offers integration with collaboration platforms like Azure DevOps and GitHub. You can easily connect your Visual Studio project to a remote Git repository and perform common Git operations like pushing, pulling, and merging changes. Visual Studio also provides tools for code reviews, work item tracking, and continuous integration and deployment workflows.

Visual Studio supports a wide range of programming languages and frameworks, including .NET, C++, Python, JavaScript, and many more. It provides language-specific features like IntelliSense, code snippets, and debugging capabilities tailored to each language. You can install language-specific extensions and SDKs to further enhance the development experience for your preferred programming languages.

For performance optimization and troubleshooting, Visual Studio offers profiling tools that help identify bottlenecks and memory leaks in your applications. The Performance Profiler allows you to analyze the performance of your code and identify areas that can be optimized. The Memory Profiler helps you detect and diagnose memory-related issues in your applications. These profiling tools provide detailed reports and insights to help you optimize your code and improve application performance.

Visual Studio also provides support for mobile app development for platforms like Android and iOS. You can create cross-platform mobile apps using frameworks like Xamarin or React Native. Visual Studio offers tools for designing user interfaces, debugging mobile apps, and deploying them to emulators or physical devices. You can also leverage cloud services like Azure Mobile Apps for backend integration and storage.

In addition to traditional desktop and web applications, Visual Studio supports the development of Internet of Things (IoT) applications. You can build applications for devices like Raspberry Pi, Arduino, and other IoT devices using Visual Studio. The Visual Studio IoT development tools provide project templates, debugging support, and deployment options for IoT scenarios.

Visual Studio also offers cloud development capabilities with integrations for popular cloud platforms like Azure. You can create, manage, and deploy cloud resources directly from within Visual Studio. It provides tools for building and deploying cloud applications, integrating with cloud services, and monitoring your cloud resources.

These are just some of the many features and capabilities that Visual Studio offers to developers. It's a powerful and versatile IDE that can cater to a wide range of development needs and workflows. Whether you're working on small projects or large enterprise solutions, Visual Studio provides the tools and features to streamline your development process and boost your productivity.

Visual Studio Tips and Tricks for Professionals - Visual Studio Tutorial
Visual Studio Tips and Tricks for Professionals - Visual Studio Tutorial
  • 2020.07.01
  • www.youtube.com
Learn to use Visual Studio like pro from creating layouts to keyboard shortcuts.C++ tutorial: https://youtu.be/mUQZ1qmKlLYJava tutorial : https://youtu.be/Wq...
 

Code complete EA for MetaTrader 5 in 20 Minutes!



Code complete EA for MetaTrader 5 in 20 Minutes!

Today, we are excited to start recording our first EA (Expert Advisor) for the MetaTrader trading platform. This EA is designed to be a trading system for MetaTrader, and in our video, we will also perform a quick backtest to evaluate its performance.

To begin, we launch the MetaTrader platform and access the MetaEditor by clicking on "Tools" and selecting "MetaQuotes Language Editor" from the dropdown menu. The MetaEditor is where we create our expert advisors, as well as scripts and indicators for MetaTrader.

To create a new expert advisor, we click on the "New" button in the top left corner of the MetaEditor. In the wizard that appears, we select the first option and click "Next." We can then give our EA a name, such as "First EA," and click "Next" again. We skip selecting any additional options and proceed by clicking "Finish."

Now we have the initial code for our EA. To start, we clean up the code by removing unnecessary comments, such as the gray comments that provide no functionality to the code itself. We delete the first five lines and some other unnecessary lines, as per our preference.

Before we begin coding, let's take a moment to consider what we want our EA to do. For this video, our goal is to have the EA open a buy trade at a specific time and close it at another predetermined hour of the day. To achieve this, we need two input variables: one for the open time and another for the close time.

Returning to the MetaEditor, we declare these two input variables under a new section called "Variables." We use the "input" keyword to specify that these variables can be changed from outside the code. We set their types as integers since we want to enter specific hour values. For example, we can name the variables "openHour" and "closeHour."

After declaring the variables, we compile the code to ensure there are no errors. If everything is correct, we can see that there are no error messages in the toolbox.

Next, we switch back to the MetaTrader platform and drag our EA onto any chart. We can see the EA's name, version, and link in the navigator under "Expert Advisors." By expanding the EA, we can access the input variables and change their values without modifying the code.

Now, let's move on to the "OnTick" function, which is called every time the price changes. We want to check if we have reached the open time specified by the user. To do this, we need to retrieve the current time of the symbol and the server. We create a variable called "time" of type "datetime" and use the "TimeCurrent" function to assign the current time to it.

With the current time stored in our "time" variable, we can now check if it matches the open time. We use an "if" statement to compare the "openHour" variable with the hour component of the current time ("time.hour"). If the condition is true, we enter the "if" block.

Inside the "if" block, we open a position using the "OrderSend" function. We specify the symbol, trade direction (buy), lot size (1 lot), and ask price as parameters. Additionally, we set the stop loss and take profit values as per our preferences.

After compiling the code and running a backtest using the MetaTrader strategy tester, we observe that the EA opens a position at the specified open time. However, we notice that multiple positions are opened due to subsequent price movements triggering the "OnTick" function again.

To prevent multiple positions from being opened, we introduce a boolean variable called "isTradeOpen" to keep track of whether a trade is already open. Initially, we set the value of "isTradeOpen" to false. Before opening a new position, we check if "isTradeOpen" is false. If it is, we proceed to open the position and set the value of "isTradeOpen" to true. This way, even if the "OnTick" function is triggered multiple times, it will only open a new position if there isn't already an open trade.

After implementing this logic, we compile the code again and run a backtest. This time, we observe that the EA opens a position at the specified open time and does not open any additional positions until the previous one is closed.

Moving on to closing the trade at the specified close time, we need to introduce another check in the "OnTick" function. After opening the position, we compare the current time with the close time specified by the user. If they match, we enter an "if" block.

Inside the "if" block, we close the trade using the "OrderClose" function. We provide the ticket number of the position to close, as well as the lot size and bid price as parameters. Additionally, we can set additional parameters such as stop loss and take profit values if desired.

We compile the code again and run a backtest to verify that the trade is closed at the specified close time. During the backtest, we can check the trade history to ensure that the positions are opened and closed according to the specified times.

We have successfully created our first EA for the MetaTrader trading platform. The EA is designed to open a buy trade at a specific open time and close it at a predetermined close time. We have implemented input variables to allow customization of the open and close times without modifying the code. By introducing checks and variables, we ensure that only one trade is opened at a time and that it is closed at the specified close time.

Code complete EA for MetaTrader 5 in 20 Minutes!
Code complete EA for MetaTrader 5 in 20 Minutes!
  • 2022.06.27
  • www.youtube.com
Program your first EA for MetaTrader. I will show you how you can easily code your first Expert Advisor or trading system in Mql5.As an algo trader I develop...
 

Moving Average Crossover EA mql5 Programming



Moving Average Crossover EA mql5 Programming

Hi, this is Toby, and in today's video, I'll show you how to code a simple moving average crossover expert advisor for MetaTrader 5. Let's get started.

First, let's define what we want the expert advisor to do. We want the EA to open a buy position when the fast moving average (blue line) crosses above the slow moving average (red line) and open a sell position when the fast moving average crosses below the slow moving average. We'll also add a stop loss and take profit to the EA, as well as input variables for the periods of the moving averages.

To begin coding, open the MetaEditor in MetaTrader 5. Create a new expert advisor using the template and name it "Moving Average." Clean up the code by removing unnecessary lines and comments. Next, add input variables for the periods of the fast and slow moving averages. Set default values for these variables and display them in the input tab of the EA settings.

Check the user input in the OnInit function to ensure valid values are entered. If the input is invalid (zero or negative), display an alert message and stop the EA. Create handles for the fast and slow moving averages using the ma function. Set the symbol, period, and input variables for each moving average. Check if the creation of handles is successful. If not, display an alert message and stop the EA. Create global variables for storing the indicator values. Use dynamic arrays for the fast and slow buffers. In the OnTick function, copy the latest indicator values into the buffers and check if enough data is available. If not, return and display an alert message.

Print the indicator values on the screen to verify if everything is working correctly. Use the Comment function to display the values of the fast and slow moving averages.

In the Strategy Tester, test the EA to check if the indicator values are displayed correctly. Now, we can check for a crossover of the moving averages. If the fast moving average is below the slow moving average at bar 1 and above the slow moving average at bar 0, we have a crossover. Open a buy position in this case.

To open positions, use the CTrade class. Define a trade variable and proceed with the necessary actions. Compile the code and test the EA in the Strategy Tester to verify if the crossover condition is working correctly and positions are opened accordingly.

That's it for coding the moving average crossover expert advisor in MetaTrader 5. And then we can use the trade.Buy function to open a buy position. We specify the volume of the position, which can be a fixed value or based on your risk management strategy. For now, let's use a fixed volume of 0.1 lots. Now we need to add a condition to check for a sell position. If the fast moving average is above the slow moving average for bar 1 and below for the current bar, we have a crossover in the opposite direction. In this case, we want to open a sell position. We can use the trade.Sell function to do that.

Finally, we can add a stop loss and take profit to our positions. We'll use the trade.SetStopLoss and trade.SetTakeProfit functions. Let's set a stop loss of 100 pips and take profit of 200 pips for this example. Now we have a complete code for our simple moving average crossover expert advisor. We can compile it and test it in the MetaTrader 5 platform.

Once you have compiled the code without any errors, you can save the expert advisor and use it in MetaTrader 5. Remember to backtest and optimize your expert advisor before using it with real money.

Moving Average Crossover EA mql5 Programming
Moving Average Crossover EA mql5 Programming
  • 2022.09.06
  • www.youtube.com
Today I will show you how to code a simple Moving Average Crossover EA for Metatrader 5. If you are new to mql5, just follow my steps and we will create a f...
 

Range Breakout EA mql5 Programming | Part 1/4



Range Breakout EA mql5 Programming | Part 1/4

Hi, this is Toby, and in today's video, I will show you how to code a time range breakout expert advisor (EA) for MetaTrader 5. The goal is to achieve results similar to the strategy shown in the video.

First, let's discuss the logic behind the EA. We will define a simple time range, starting at a specific time and ending at another time. The EA will save the highest and lowest prices within this range. If the price breaks above the highest price after the range, the EA will enter a buy trade. Conversely, if the price breaks below the range, the EA will enter a sell trade. Additionally, we will set a close time to close all positions. This straightforward logic will guide our EA.

To start coding, open MetaEditor and create a new expert advisor. Clean up the template code, as per personal preference, removing unnecessary lines.

Next, define input variables for the start time, range duration, close time, lot size, and magic number. These inputs allow users to customize the EA's behavior. It's important to check the input values to prevent incorrect inputs. For example, we can ensure that the magic number is not zero or negative, lots are not negative, start time and duration are within valid ranges, and the close time is not equal to the start time plus the range duration.

After defining the input variables and checking their values, we move on to the creation of global variables. These variables will be used throughout the EA. We group variables related to the range in a structure called "range structure." This structure contains variables for the start time, end time, close time, high and low prices, and flags for entry, high breakout, and low breakout.

Additionally, we define the structure's constructor, where we predefine the initial values for the variables. This helps initialize the structure with default values. We also add comments after each variable to describe their purpose.

We compile the code to check for any errors and ensure everything is working correctly.

Finally, we create a few more variables, such as "MqlTick" and "last_tick" of the MetaTrader 5 "MqlTick" type. We also define a variable of type "CTrade" to handle trade-related operations.

At this point, we have set up the necessary variables and structures for our EA. In the next part, we will dive into coding the actual logic of the EA in the "OnTick" function. In the next part of the video, we will focus on coding the actual logic of the Expert Advisor in the OnTick function. However, before we proceed, let's first review what we have done so far.

We started by defining the input variables for the EA, such as the start time of the range, duration, close time, lot size, and magic number. We also added input validation checks to ensure that the user enters valid values for these inputs. Next, we created a structure called rangeStructure to store the variables related to the range, including the start time, end time, close time, high and low of the range, and flags for entry, high breakout, and low breakout. We then defined a constructor for the rangeStructure to initialize the variables with default values. Additionally, we declared some global variables, including an instance of the rangeStructure, two variables of type MqlTick to store the current and previous ticks, and a CTrade object to handle trade operations.

Now, let's move on to the implementation of the OnTick function to code the main logic of the EA. Here's the continuation of the video: In the OnTick function, we will first update the current tick information using the SymbolInfoTick function. This allows us to access the bid and ask prices, as well as the time of the tick. Next, we will check if the current tick time is within the range defined by the user. To do this, we compare the current tick time with the start time and end time of the range. If the tick time is within the range, we set the flagEntry to true, indicating that we are inside the range.

After that, we check for a high breakout. If the current tick price exceeds the previous high of the range and the flagHighBreakout is false, we initiate a buy trade. We set the flagHighBreakout to true to avoid repeated entries. Similarly, we check for a low breakout. If the current tick price falls below the previous low of the range and the flagLowBreakout is false, we initiate a sell trade. We set the flagLowBreakout to true to prevent multiple entries. Finally, we check if the current tick time is equal to the close time. If so, we close all open positions using the trade.CloseAll method.

That's the basic logic of the EA. Of course, there are additional elements you can add to enhance its functionality, such as stop-loss and take-profit levels, money management rules, and additional trade filters. However, in this video, we focused on the core concept of the time range breakout strategy.

Remember, this EA is meant to serve as a starting point, and you can customize it further according to your requirements and trading preferences.

In the next part of the video, we will continue with the coding process, adding the necessary code to implement the logic discussed. If you found this video helpful, don't forget to leave a like and subscribe to my channel to stay updated with future videos. If you have any questions or need assistance, feel free to leave a comment, and I'll be glad to help. Thank you for watching, and I'll see you in the next video. Bye!

Range Breakout EA mql5 Programming | Part 1/4
Range Breakout EA mql5 Programming | Part 1/4
  • 2022.09.25
  • www.youtube.com
Today 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 br...
 

Range Breakout EA mql5 Programming| Part 2/4



Range Breakout EA mql5 Programming| Part 2/4

Hi, this is Toby, and in today's video, we will continue coding our time range breakout EA for MetaTrader 5. If you haven't watched the first video yet, you can find the link here. In the previous video, I explained the logic of the EA and what we are trying to code.

Now, let's switch to MetaEditor and resume coding. We will be working on the OnTick function, which is called every time the price changes for our symbol. In this function, we will code our range calculation and the breakout check. First, we need to get the current tick for the symbol. We store the current tick in a variable called currentTick, and we also have a variable previousTick to store the previous tick.

Next, we check if we need to calculate a new range. There are several conditions for calculating a new range.

  1. If we have a range close time set and the current tick time is greater than or equal to the range close time, we calculate a new range.

  2. If both the high breakout and low breakout flags are set to true, we calculate a new range.

  3. If it's the first time running the EA and we haven't calculated a range yet, we calculate a new range.

  4. If the range end time is not zero, and we are after the range and haven't entered the range, we calculate a new range.

We also check if we have any open positions. If there are no open positions, we proceed to calculate a new range.

Once we determine that we need to calculate a new range, we call the CalculateRange function. In this function, we reset all range variables to their default state. We then calculate the range start time by getting the start of the day and adding the input range start time in minutes. If the calculated start time is already passed, we shift it to the next day, considering Saturday and Sunday as weekend days. Similarly, we calculate the range end time by adding the input range duration in minutes to the start time. If the end time falls on a Saturday or Sunday, we shift it to the next valid day.

We also calculate the range close time using the same logic as the start time and end time calculation. To visualize the calculated times on the chart, we create objects using the ObjectCreate function. We create a vertical line object for the range start time and delete any previously drawn objects.

This is the progress we have made so far, and we will continue coding in the next video.

Range Breakout EA mql5 Programming| Part 2/4
Range Breakout EA mql5 Programming| Part 2/4
  • 2022.10.01
  • www.youtube.com
Today 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 br...
 

Range Breakout EA mql5 Programming | Part 3/4


Range Breakout EA mql5 Programming | Part 3/4

Hi, this is Toby, and in today's video, we will continue coding our breakout EA. In the previous videos, we already calculated the range start time, end time, and close time. Now, we want to code the range high and range low, as well as the breakout conditions and position closure. If you haven't watched the previous videos, you can find the links in the description below. Let's jump into MetaEditor and start coding.

First, we'll go to the OnTick function. We'll begin by checking if we are inside the range and save the high and low values. We use an if statement to check if the current time is between the range start and end times. If it is, we update the high and low values accordingly. We also set an entry flag to true to indicate that we had a tick inside the range. We then update the chart objects for the range high and low.

Next, we move to the DrawObject function to draw the high and low levels of the range. We copy the code block for the close time and make the necessary changes for the high level. We use the object name "Range High" and draw a trend line from the range start time to the range high price. We also update the tooltip to display the range high value. We do the same for the range low, changing the object name and drawing a trend line from the range start time to the range low price.

To draw a line from the range end to the close time, indicating a breakout, we copy the code block again and modify it accordingly. We change the object name and draw a trend line from the range end time to the close time. We also set the line style to dotted.

After compiling and running a visual test, we can see the range high, range low, and breakout lines displayed on the chart. Now, let's code the breakout conditions. We add a new function called CheckBreakouts within the OnTick function. First, we check if we are after the range end time. We also ensure that the entry flag is set to true, indicating that we had a tick inside the range. If these conditions are met, we proceed to check for high and low breakouts.

For a high breakout, we check if the high breakout flag is false and if the last tick's ask price is greater than or equal to the range high. If so, we open a buy position using the PositionOpen function. Similarly, for a low breakout, we check if the low breakout flag is false and if the last tick's bid price is below or equal to the range low. If these conditions are met, we open a sell position.

We compile the code and run a visual test to confirm that the positions are opened when a breakout occurs. Next, we implement the position closure. Before calculating a new range, we check if the current time is greater than or equal to the range close time. If so, we call the ClosePositions function. This function loops through all open positions with the specified magic number and closes them using the PositionClose function. We use a countdown loop to ensure that all positions are closed even if the total number of positions changes during the loop.

Finally, we compile the code and run a visual test to confirm that the positions are closed when the range close time is reached.

That's it for this video. If you have any questions, feel free to leave them in the comments below. Don't forget to like and subscribe for more coding videos. Thanks for watching!

Range Breakout EA mql5 Programming | Part 3/4
Range Breakout EA mql5 Programming | Part 3/4
  • 2022.10.09
  • www.youtube.com
Today 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 br...
Reason: