top of page

HOW TO CONFIGURE YOUR METATRADER'S EXPERT ADVISOR

MetaTrader's Expert Advisors (EAs) offer traders a powerful way to automate their trading strategies. They allow for emotion-free, consistent execution even when you're not actively monitoring the market.

This guide delves into everything you need to know about setting up an EA.

Last Update

4.10.24

  • X
  • LinkedIn

How to Configure Your MetaTrader's Expert Advisor Using fxDreema


fxDreema is a powerful visual programming tool designed for creating automated trading strategies, known as Expert Advisors (EAs), for the MetaTrader trading platforms (MT4 and MT5). With fxDreema, traders can build complex trading algorithms without manually writing code, using a drag-and-drop interface to connect predefined blocks representing various trading conditions, actions, and logic. This guide will delve into how to set up an EA using fxDreema, starting with the crucial initialization phase.


Introduction to the On Init Section


The On Init section in fxDreema is a foundational step for setting up all the configurations your Expert Advisor (EA) requires to function effectively. This section is executed only once when the EA is first attached to a chart or when MetaTrader starts. Proper setup in the On Init section is essential for ensuring that all components of the EA are ready and operational, allowing the EA to execute the trading strategy as intended from the beginning.


Setting Up Constants (Inputs)


Constants, also known as inputs, are parameters that define the customizable aspects of your EA. These constants allow for quick adjustments to the EA’s behaviour without modifying the actual code, making the EA flexible and adaptable to different market conditions. Examples of constants include the size of each trade (lot size), stop-loss levels, take-profit levels, or the periods used for indicators like Moving Averages.


In fxDreema, you can define constants using the "Constants (Inputs)" block. These constants become adjustable parameters that users can modify in the EA's settings before running it. Setting these values as inputs ensures the EA can be easily optimized for various trading scenarios, increasing its effectiveness and efficiency.


Initializing Variables


Variables store and manage data throughout the EA's lifecycle. These variables might include the current price, indicator outputs, counters for specific conditions, or flags to control the EA's flow. Proper variable initialization ensures the EA starts with the correct values and operates smoothly.


In the On Init section, you define and initialize these variables to set their initial state. fxDreema allows the use of system variables, which are predefined by MetaTrader, as well as custom variables that you can create to handle specific tasks or calculations. For instance, you might initialize a variable to track the highest price reached during the day or to count the number of trades executed.


Setting Up Indicators


Indicators play a crucial role in decision-making within trading strategies. In the On Init section, you initialize any technical indicators your EA will use to analyze the market. Common indicators include Moving Averages, Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), Bollinger Bands, and more.


By setting up indicators in the On Init section, you ensure that the EA has access to these tools as soon as they start running. In fxDreema, you can add and configure indicators using the appropriate blocks, specifying parameters such as the period, applied price, and calculation mode. This setup allows the EA to gather and use indicator data to make informed trading decisions.


Example: Initializing a Moving Average


To illustrate, consider initializing a Simple Moving Average (SMA) in fxDreema. First, you would define the period of the SMA as a constant input. Depending on your trading strategy, this could be any period, such as 10, 20, or 50. Next, you create a variable to hold the SMA's value. Using the iMA function, you set up the SMA with the specified period, applied price (such as the close price), and other necessary parameters. This initialization allows the EA to access the SMA value on every tick, enabling it to make trading decisions based on the SMA's position relative to the price.

Ongoing Trading Logic for MetaTrader's Expert Advisor Using fxDreema


Once the Expert Advisor (EA) is initialized and set up, the next critical phase is managing the ongoing trading logic. In fxDreema, the On Tick, On Timer, On Trade, and On Chart sections are used. These sections handle the real-time execution of trading strategies, responding to market conditions, and user interactions. Let's explore how these sections contribute to the EA's functionality.



Introduction to the On Tick Section


The On Tick section is the heartbeat of the EA in fxDreema. It runs every time a new market tick is received and is triggered continuously as long as the market is open, and the EA is active. The On Tick section executes the primary trading logic, making it essential for real-time trading decisions. This section allows the EA to respond to changes in price and other market data, execute trades, and manage existing positions.


Using Conditions to Define Trading Logic


In the On Tick section, you can define the criteria under which the EA should act using blocks such as Condition & Formula. These conditions can involve various factors, including price levels, indicator values, time of day, or relevant market data. For example, you might set up a condition to check if the price has crossed above a moving average, indicating a potential buy signal, or if the RSI is above a certain threshold, suggesting overbought conditions.


By combining multiple conditions, you can create complex trading strategies that respond to various market scenarios. This flexibility allows traders to design EAs that adapt to different market conditions, increasing their chances of executing profitable trades.


Executing Buy and Sell Orders


Once the defined conditions are met, the EA needs to execute trades. This is where the Buy / Sell blocks come into play. You can configure these blocks to open new buy or sell orders based on your defined conditions. For instance, if a moving average crossover indicates a buy signal, the EA can use a Buy block to open a long position. Conversely, a sell condition might trigger a Sell block to open a short position.


Additionally, you can set parameters such as lot size, stop-loss, and take-profit levels directly in these blocks. fxDreema makes connecting these blocks to conditions easy, ensuring that trades are executed precisely when your strategy requires them. This level of automation allows the EA to operate efficiently, capitalizing on trading opportunities without manual intervention.


Trade Management


Managing open trades is as crucial as executing them. In the On Tick section, you can use blocks for Trailing Stop / Break Even to protect profits and manage risk. A trailing stop, for example, automatically adjusts the stop-loss level as the market moves in your favour, locking in profits while still allowing the trade to run. This dynamic adjustment can help maximize gains in trending markets while minimizing losses in case of a reversal.


Using the Loop for Trades & Orders blocks, you can iterate through all open trades to apply specific management rules, such as closing trades that reach a certain profit or loss level or adjusting stop-loss levels based on predefined criteria. This ensures that all trades are managed according to your strategy's risk management guidelines, reducing the chances of significant losses.


Example: A Basic Crossover Strategy


A common example is a Moving Average Crossover strategy. You could set up a condition that checks if a short-term moving average crosses above a long-term moving average, which is often considered a buy signal. If this condition is met, the EA opens a buy order. Conversely, if the short-term moving average exceeds the long-term moving average, the EA opens a sell order. Using fxDreema’s visual interface, you can easily set up these conditions and actions by dragging and connecting the appropriate blocks, making the EA responsive to these key market signals.


Introduction to the On-Timer Section


The On Timer section in fxDreema allows the EA to execute actions at specific intervals, independently of market ticks. This section is particularly useful for strategies that require periodic checks or actions based on time rather than reacting to every market movement. For example, you might want the EA to perform certain tasks regularly, such as every hour or at the close of each trading day.


Setting Up Timer Events


To use the On Timer section, you first need to set the time interval for the events. This is done by configuring the timer settings in fxDreema. The interval can be set in seconds, providing precise control over how often the EA performs the actions defined in this section. For instance, setting a timer to 3600 seconds (one hour) would cause the EA to execute its logic every hour, regardless of market activity.


Using Timer to Manage Trades


One common use of the On Timer section is to manage trades based on time rather than price movements. For example, you might set up a timer to close all trades at the end of the trading day to avoid overnight exposure or to check every hour if certain conditions are met to adjust stop-loss levels. This approach is particularly useful for strategies that involve regular reviews or adjustments, ensuring that trades are managed consistently over time.


Example: Periodic Condition Check


For example, you might want the EA to check every 15 minutes whether a specific indicator has reached a certain level and then execute a trade if the conditions are met. In fxDreema, you would set the timer to 900 seconds (15 minutes) and create blocks that check the indicator value. If the conditions are satisfied, the EA will execute the trade, ensuring that your strategy is applied consistently without relying solely on market ticks.



Introduction to the On Trade Section


The On Trade section in fxDreema is specifically designed to handle events related to trading activities, including actions triggered by opening, closing, or modification. This section is crucial for managing trade lifecycle events and implementing strategies that need to respond to specific trading actions.


Managing Trade Lifecycle Events


You can set up blocks in the On Trade section to respond to various trade-related events. For example, you might want the EA to adjust the stop-loss of a trade immediately after it is opened or to log details of trades as they are closed. You can also use this section to implement trailing stops or to handle special conditions that arise during the life of a trade.


Example: Handling Trade Modifications


A practical example is setting up a trailing stop mechanism. When a trade is opened, the EA could set an initial stop-loss. The On Trade section could trigger a block to adjust the stop-loss, following the price and locking in profits as the trade moves into profit. This dynamic adjustment helps protect gains while allowing the trade to continue as long as it remains profitable.



Introduction to the On Chart Section


The On Chart section in fxDreema handles events related to the chart, such as creating, modifying, or deleting chart objects. This section is useful for visual feedback and for managing objects that display information or interact with the user. The On Chart section enables the EA to interact with the visual aspects of the trading environment, providing a dynamic and informative interface.


Interacting with Chart Objects


Using the On Chart section, you can add blocks to create, modify, or delete various chart objects, such as trend lines, text labels, arrows, and more. These objects can provide valuable visual cues for the trader, indicating important levels, marking trade entries and exits, or displaying messages and alerts. For example, the EA might draw support and resistance lines based on recent price action, helping the trader to identify key levels to watch.


Example: Drawing Trend Lines


An example use case for the On Chart section is drawing trend lines to highlight market trends. The EA could calculate the high and low points over a specified period and use these points to draw a trend line. The EA can update or remove these lines as the market evolves, ensuring that the chart reflects current market conditions. This visual representation can aid traders in understanding market trends and making informed decisions.

Robot trading in MT5

EAs are automated trading robots integrated into the MetaTrader platforms (MT4 and MT5). These automated trading systems can execute trades on behalf of traders based on a predefined set of strategies and rules. Understanding how these bots work and their potential benefits is crucial for anyone looking to automate their trading activities.

Cleanup and Maintenance of the Expert Advisor


After the initialization and ongoing trading phases, the final critical aspect of an Expert Advisor (EA) is the cleanup and maintenance phase. This phase ensures that the EA terminates gracefully, leaving no loose ends that could affect future operations. fxDreema manages this through the On Deinit section, which handles all the necessary cleanup tasks when the EA is removed from a chart, or MetaTrader shuts down.



Introduction to the On Deinit Section


The On Deinit section in fxDreema is designed to handle the cleanup and finalization tasks required when the EA is being deinitialized. This might occur due to the EA being removed from the chart, the chart being closed, or MetaTrader itself shutting down. The On Deinit section ensures that the EA exits gracefully, handling all necessary tasks to maintain data integrity and system stability.


Handling Open Trades


One of the primary tasks in the On Deinit section is managing open trades. Leaving trades open when the EA is deinitialized can lead to unwanted market exposure and potential losses. In fxDreema, you can set up blocks to loop through all open trades and close them. This ensures that the EA does not leave any positions unmanaged, which could affect the trading account when the EA is no longer active.


By closing all open trades, you ensure that the trading account remains neutral, reducing the risk of unintended market exposure. This is especially important for strategies that involve high leverage or volatile instruments, where unmanaged positions can quickly lead to significant losses.


Removing Chart Objects


If your EA uses chart objects to display information or provide visual cues, removing them when the EA is deinitialized is good practice. This prevents the chart from becoming cluttered with outdated or irrelevant information. In fxDreema, you can use blocks to select and remove chart objects during the On Deinit process. This cleanup ensures that the chart remains clear and ready for future use without being overlaid with unnecessary elements.


For example, if the EA draws lines to indicate support and resistance levels, these lines should be removed when the EA is no longer active. This prevents the trader from relying on outdated information that may no longer be relevant to the current market conditions.


Saving Data for Future Use


Sometimes, specific data points need to be saved for future analysis or to use when the EA is restarted. This might include information such as the current account balance, indicator values, or trading results. In the On Deinit section, you can use file operations to write this data to external files, ensuring that it is preserved for future use. fxDreema includes blocks for writing to and reading from files, making it easy to maintain a record of the EA's activity even after it is deinitialized.


Saving data is particularly useful for strategies that require continuity, such as tracking cumulative performance over time or using historical data to make decisions. By preserving key data points, you can ensure the EA has the information it needs to continue operating effectively when restarted.


Logging and Error Handling


Logging is an essential component of EA development. It provides valuable insights into the EA's performance and helps diagnose issues. During the On Deinit phase, you can log important events such as the reasons for the EA's shutdown, any errors encountered during execution, and the status of open trades. This information is valuable for troubleshooting and refining your trading strategies.


Using fxDreema, you can set up logging blocks to capture these details and store them in a log file or display them in MetaTrader's Experts tab. This detailed record allows you to analyze the EA's behaviour, identify potential issues, and make necessary adjustments to improve performance. Effective logging and error handling are crucial for ensuring the reliability and robustness of your EA, enabling you to respond quickly to unexpected situations and maintain consistent performance.


Example: Saving Log Data


An example of effective logging is saving data related to the EA's trading decisions. For instance, you might log the reasons for entering or exiting trades, including the market conditions, indicator values, and other relevant factors. This data can be invaluable for post-analysis, helping you to understand why certain trades were successful or unsuccessful and providing insights for optimizing the EA's strategy.


Maintaining a comprehensive log allows you to track the EA's performance over time, identify patterns and trends, and refine your trading approach to maximize profitability. Logging also helps to ensure transparency and accountability, providing a clear record of the EA's actions and decisions.



Conclusion


The cleanup and maintenance phase is a critical aspect of the EA's lifecycle, ensuring that the EA terminates gracefully and that all necessary data and trades are handled appropriately. By effectively managing the On Deinit section, you can maintain the integrity of your trading account, preserve valuable data, and ensure that the EA is ready to restart and operate effectively. Proper cleanup and maintenance are essential for the long-term success and reliability of any Expert Advisor, helping to protect your trading capital and optimize your trading performance.

bottom of page