Introduction
The Expert Advisor discussed in this article is a multi-currency trading robot that uses the Zigzag and RSI indicators. It follows a strategy of opening Buy trades when the price dips below the RSI oversold line and Sell trades when the price rises above the RSI overbought line. It also includes pending limit orders and a lot size multiplier Martingale system.
The multi-currency Expert Advisor is a trading robot capable of executing trades (opening, closing, and managing orders, including Trailing Stop Loss and Trailing Profit) for multiple currency pairs on a single chart. In this article, the Expert Advisor will trade 30 pairs.
This article will explore a strategy that combines the Zigzag and RSI indicators. Buy trades will be initiated when the price dips below the RSI oversold line, and Sell trades will be opened when the price rises above the RSI overbought line. Additionally, pending limit orders will be employed.
To mitigate potential losses, a lot size multiplier with a staged Martingale system will be utilized. For each market order opened, the Expert Advisor will open a maximum of 4pending limit orders, progressively increasing the lot size with each subsequent order.
1. Trading Currency Pairs
The Multi-Currency Expert Advisor is designed to trade the following 30 pairs:
For Forex:
EURUSD,GBPUSD,AUDUSD,NZDUSD,USDCAD,USDCHF,USDJPY,EURGBP, EURAUD, EURNZD, EURCAD, EURCHF, EURJPY, GBPAUD, GBPNZD, GBPCAD, GBPCHF,GBPJPY,AUDNZD,AUDCAD,AUDCHF,AUDJPY,NZDCAD,NZDCHF, NZDJPY, CADCHF, CADJPY, CHFJPY = 28 pairs
Plus 2 Metal pairs: XAUUSD (Gold) and XAGUSD (Silver)
Total is 30 pairs.
To ensure compatibility with various MetaTrader 5 brokers and their specific symbol naming conventions, the Expert Advisor employs a function that automatically manages symbol names with prefixes and/or suffixes. This allows for seamless operation regardless of any broker-specific symbol variations.
2.1. Single and Multi-Currency Expert Advisor
Single Currency Mode allows the Expert Advisor to focus on trading a single currency pair, providing a more targeted and potentially less complex trading strategy.
By selecting this mode, the trader can choose a specific pair from the list of available pairs and configure the Expert Advisor's parameters to optimize performance for that particular pair.
This approach can be beneficial for traders who prefer to specialize in a few specific pairs or who want to minimize the risk associated with trading multiple pairs simultaneously.
In the Select Trading Pairs Mode (Multi or Single) options, there are 2 options which in this option trader can choose trading pair conditions, whether to trade on single-currency or trade on multi-currency:
- 1. Single Pair (single-currency)
- 2. Multi Pairs (multi-currency)
The Expert Input Parameters need to be set as shown in the following figure.
1. Single Pair Mode
When the "Single Pair" option is selected, the Expert Advisor will be restricted to trading solely on the specific currency pair where it is attached. For example, if the EA is placed on the EURUSD chart, it will exclusively trade the EURUSD pair.
This mode is ideal for traders who want to focus on a particular pair and fine-tune the EA's settings to optimize performance for that specific market.
2. Multi-Pair Mode
When the "Multi-Pair" option is selected, the Expert Advisor will trade a maximum of 10 currency pairs simultaneously, chosen from the predefined list of 30 pairs.
Trader's Choice:
The ten predefined pairs: The Expert Advisor can be configured to trade a fixed set of 10 pairs from the list. Custom Pair Selection: Alternatively, traders can manually input up to 10 desired pairs in the Expert Advisor's input parameters. These pairs must be selected from the 30 available pairs. This mode is suitable for traders who want to diversify their trading across multiple pairs while still maintaining a manageable level of risk. By carefully selecting the pairs to trade, traders can potentially increase their overall profitability.
Trader's Wishes Pairs:
The "Trader's Wishes Pairs" option provides flexibility to focus the Expert Advisor on a specific currency pair or operate independently. By manually entering the desired pair name (e.g., "XAUUSD"), the EA will prioritize trading that particular pair, disregarding the other 29 pairs. This allows for tailored trading strategies and risk management.
2.2. Trade on Specific Time
The "Trade on Specific Time" feature allows traders to align their trading activities with specific time zones. This is particularly useful for traders who want to focus on particular trading sessions, such as the London, New York, or Tokyo sessions.
By enabling this feature, the Expert Advisor can be configured to trade only during specific time frames, potentially reducing exposure to market volatility during less active periods.
No Specific Time:
If "Trade on Specific Time Zone" is set to "No," the Expert Advisor will trade 24/5, from 00:15 to 23:59, based on the MT5 server time.
Specific Time Zones:
If "Trade on Specific Time Zone" is set to "Yes," the trader can select from the following options:
Custom Session:
- Traders can specify custom start and end times for the trading session.
- The EA will only execute trades within this specified time.
Predefined Sessions:
- New Zealand Session: Trades during New Zealand trading hours.
- Australia Sydney Session: Trades during Australian trading hours.
- Asia Tokyo Session: Trades during Asian trading hours.
- Europe London Session: Trades during European trading hours.
- America New York Session: Trades during US trading hours.
Trading Session Duration Calculation:
For trades initiated during the New Zealand to New York session, the Expert Advisor calculates the duration of the trade, which can be useful for various trading strategies and analysis.
2.3. Martingale system
The Expert Advisor employs a staged Martingale system to manage risk and potentially increase profits. Here's how it works:
- Initial Trade: When a trading signal is identified, the EA opens an initial market order (either a Buy or Sell).
- Pending Limit Orders: Simultaneously, the EA places up to 4 pending limit orders in the same direction as the initial market order. These limit orders are placed at progressively wider price levels.
- Lot Size Multiplier: Each subsequent pending limit order has a larger lot size than the previous one. This lot size increase is calculated using a predefined multiplier factor.
- Martingale Principle: The goal of this strategy is to recover potential losses from previous trades by increasing the position size of subsequent trades. If the initial market order and the first few pending orders result in losses, the larger subsequent orders have a higher chance of recouping those losses.
Important Considerations:
- 1. Risk Management: While the Martingale system can be effective in certain market conditions, it's essential to use it with caution. It's a high-risk strategy that can lead to significant losses if a series of consecutive losing trades occurs.
- 2. Account Balance: It's crucial to have sufficient funds in your trading account to cover potential losses from multiple consecutive losing trades.
- 3. Market Conditions: The Martingale system may not be suitable for all market conditions. It's important to consider market volatility and trends when using this strategy.
- 4. Proper Risk Management: It's recommended to use appropriate stop-loss and take-profit orders to limit potential losses and secure profits.
- 5. Remember: Martingale strategies are inherently risky, and it's essential to conduct thorough back testing and risk assessment before using them in live trading.
Note:
Because this expert advisor will open multiple orders, by default we set the lot size when opening market order with a minimum lot size of 0.01.
This note indicates that the Expert Advisor will use a minimum lot size of 0.01 for the initial market order. This is a common practice to minimize risk and avoid excessive exposure to market volatility.
This note indicates that the Expert Advisor will use a minimum lot size of 0.01 for the initial market order. This is a common practice to minimize risk and avoid excessive exposure to market volatility.
The subsequent pending limit orders will have larger lot sizes, determined by the Martingale system. This means that as the number of open orders increases, the potential risk also increases.
It's important to note that while the Martingale system can potentially increase profits, it also carries significant risks. It's crucial to use this strategy with caution and to have a solid understanding of risk management principles.
2.4. Expiration Time for Pending Orders.
The Expert Advisor offers flexibility in setting expiration times for pending orders. This feature allows traders to control the duration of open positions and limit potential risk.
Here are the available expiration time options:
- No Expiration: Pending orders will remain open indefinitely until manually closed or triggered by a market event.
Time-Based Expiration: Pending orders will expire after a specific time period, which can be set to:
- H1: 1 hour
- H4: 4 hours
- H8: 8 hours
- H12: 12 hours
- D1: 1 day
- D5: 5 days
The SetPOExpiry() function is responsible for calculating and setting the expiration time for pending orders based on the selected time frame and the current symbol. The function determines whether a specified expiration time or a daily expiration is more appropriate and sets the expiration time accordingly.
By using this feature, traders can implement risk management strategies and avoid potential losses from unforeseen market events or prolonged periods of adverse price movements.
The IsExpirationTypeAllowed() function is a crucial component of the Expert Advisor, as it ensures that the expiration time settings are compatible with the specific symbol being traded.
Function Purpose:
- Symbol Compatibility: The function checks if the desired expiration type (e.g., H1, H4, D1) is allowed for the current symbol.
- Expiration Mode: Different symbols may have different expiration mode settings, such as allowing only specific expiration types or no expiration at all.
- Validating Settings: The function helps to prevent invalid settings and ensures that the Expert Advisor operates correctly.
How it Works:
- Retrieves Expiration Mode: The function obtains the current symbol's expiration mode setting.
- Compares Expiration Types: It compares the specified expiration type with the allowed expiration modes for the symbol.
- Returns Result: If the specified expiration type is allowed, the function returns true; otherwise, it returns false.
By using this function, the Expert Advisor can dynamically adjust its behavior based on the specific symbol being traded, ensuring that the expiration time settings are appropriate and effective.
2.5. Check Free Margin from Equity to Trade (in Percent)
The GoodMarginTrade() function is a crucial component of the Expert Advisor's risk management system. It ensures that there is sufficient free margin in the trading account to open a new trade.
How it Works:
- Calculates Required Margin: The function calculates the required margin for the proposed trade, taking into account factors like the lot size, leverage, and current market price.
- Checks Available Margin: It compares the calculated required margin with the available free margin in the trading account.
- Margin Check: If there is enough free margin, the function returns true, allowing the trade to proceed. If there is insufficient free margin, the function returns false and generates an alert message to notify the trader.
- Default Margin Equity Setting: By default, the Expert Advisor is set to use a maximum of 80% of the account's equity for trading. This helps to maintain a healthy risk-reward ratio and avoid excessive risk exposure.
- Margin Checks at Key Points: The GoodMarginTrade() function is called before opening both market orders and pending limit orders. This ensures that there is sufficient margin available at the time of order placement, reducing the risk of margin calls and account liquidation.
By implementing this robust margin check, the Expert Advisor helps to protect the trader's account balance and maintain a disciplined trading approach.
2.6. Check Maximum Pair's Spread to Trade.
The CheckSpread() function is another essential component of the Expert Advisor's risk management system. It ensures that the spread for a particular trading pair is within acceptable limits.
- Retrieves Spread: The function retrieves the current spread for the specified symbol.
- Compares to Maximum Spread: It compares the retrieved spread to the maximum allowed spread, which is typically set to 9 pips or 90 points.
- Spread Check: If the spread is within the limit, the function returns true, allowing the trade to proceed. If the spread exceeds the limit, the function returns false and generates an alert message to notify the trader.
Why Check Spread?
- 1. Trading Costs: A high spread can significantly impact profitability, especially for short-term trading strategies.
- 2. Market Conditions: Wide spreads often occur during periods of high volatility or low liquidity.
- 3. Risk Management: By avoiding trades with excessive spreads, traders can reduce the risk of adverse price movements.
By implementing this spread check, the Expert Advisor helps to filter out unfavorable trading opportunities and improve overall trading performance.
3.1. Zigzag Indicator.
Understanding the Zigzag Indicator.
The Zigzag indicator is a valuable tool for technical analysis, helping traders identify significant price swings and potential trend reversals. By filtering out minor price fluctuations, it provides a clearer view of the underlying trend.
How the Zigzag Indicator Works?
- 1. Identifying Extrema: The indicator identifies significant highs and lows in the price chart.
- 2. Connecting the Dots: It connects these extreme points with straight lines, creating a series of peaks and troughs.
- 3. Filtering Noise: By focusing on these major price swings, the Zigzag indicator reduces the impact of noise and random price fluctuations.
Key Benefits of the Zigzag Indicator:
- Trend Identification: It helps to identify the overall trend direction, whether it's uptrend, downtrend, or sideways.
- Potential Reversal Points: It can signal potential trend reversals by forming distinct tops and bottoms.
- Clear Price Structure: It simplifies the complex price chart, making it easier to analyze.
Limitations of the Zigzag Indicator:
- Lag: The Zigzag indicator can lag behind price movements, especially in fast-moving markets.
- Subjectivity: The indicator's parameters (Depth, Deviation, and Backstep) can influence its sensitivity and accuracy.
- False Signals: In choppy markets, the Zigzag indicator may generate false signals, leading to incorrect trading decisions.
Optimizing Zigzag Indicator Settings.
The three primary parameters of the Zigzag indicator are:
- Depth: with default value 12. This setting determines the minimum number of bars required to form a new extreme point. A higher Depth value can filter out more noise but may also introduce more lag.
- Deviation: with default value 5. This setting defines the percentage price change required to identify a new extreme point. A higher Deviation value can make the indicator less sensitive to minor price fluctuations.
- Backstep: with default value 3. This setting specifies the minimum number of bars between two consecutive extreme points. The minimal number of bars between swing highs and lows. A higher Backstep value can reduce the frequency of false signals but may also delay the identification of trend changes.
In conclusion, the Zigzag indicator is a useful tool for technical analysis, but it's essential to use it in conjunction with other indicators and confirmation signals to make informed trading decisions. By understanding its strengths and limitations, traders can effectively leverage this indicator to improve their trading strategies.
The Zigzag indicator formula is a bit more complex than the simplified explanation provided earlier. It involves a recursive calculation to identify significant price swings.
Here's a breakdown of the Zigzag indicator formula:
- Zigzag (HL, %change=X, retrace=FALSE, LastExtreme=TRUE)
- If %change>=X,plot ZigZag
- where: HL = High-Low price series or Closing price series
- %change = Minimum price movement, in percentage
- Retrace = Is change a retracement of the previous move or an absolute change from peak to trough?
- Last Extreme = If the extreme price is the same over multiple periods, is the extreme price the first or last observation?
- A Boolean value indicating whether to consider the last extreme point in the calculation.
Calculation:
Initial Extreme Point: The first extreme point is identified based on the initial price data. Subsequent Extreme Points for each subsequent price bar:
- Calculate the price difference between the current bar's high/low and the previous extreme point.
- If the price difference exceeds the specified percentage change (%change), a new extreme point is identified.
- If the retracement option (retrace) is enabled, the indicator will consider potential retracements and adjust the extreme point accordingly.
- The LastExtreme option determines whether the last identified extreme point is considered in the calculation.
Visualization:
The Zigzag indicator plots a series of line segments connecting these significant high and low points. The resulting chart pattern can help identify trends, potential reversals, and support and resistance levels.
Important Note:
While the formula provides a mathematical basis for the Zigzag indicator, the actual implementation in trading platforms may involve additional optimizations and adjustments to improve performance and accuracy.
3.2. The Relative Strength Index (RSI) Indicator
Understanding the RSI.
The Relative Strength Index (RSI) was developed by J. Welles Wilder and first introduced in his 1978 book, "New Concepts in Technical Trading Systems," as well as in the June 1978 issue of Commodities magazine (now Modern Trader magazine). Over time, it has emerged as one of the most widely used oscillator indices.
The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements. It oscillates between 0 and 100.
The RSI is a technical indicator employed in financial market analysis to assess the current and historical strength or weakness of a stock or market based on recent closing prices. It operates as a price-following oscillator that fluctuates between 0 and 100. Initially, Wilder recommended using a 14-period RSI, but variations such as the 9-period and 25-period RSI have also gained popularity since then.
- Overbought: When the RSI is above 70, it suggests the asset is overbought, and a potential price decline may occur.
- Oversold: When the RSI is below 30, it suggests the asset is oversold, and a potential price increase may occur.
Furthermore, in the technical analysis MQL5 it is stated that the RSI signal is used for chart analysis:
- Tops and Bottoms
- Chart Formations
- Failure Swing (Support or Resistance breakout)
- Support and Resistance levels
- Divergences
Combining RSI with Zigzag for Trading Signals.
In this article we will use the RSI indicator signal Tops and Bottoms combined with the Zigzag indicator, with period 7 bars and High levels (overbought) 76.0 and Low levels (oversold) 24.0.
By combining the RSI with the Zigzag indicator, we can create a powerful trading strategy:
- 1. Identifying Trend Direction: Use the Zigzag indicator to determine the overall trend direction.
- 2. Generating Buy Signals:
- RSI Oversold: When the RSI falls below 24.0, indicating an oversold condition.
- Zigzag Bottom: The Zigzag indicator forms a bottom, suggesting a potential reversal to the upside.
- 3. Generating Sell Signals:
- RSI Overbought: When the RSI rises above 76.0, indicating an overbought condition.
- Zigzag Top: The Zigzag indicator forms a top, suggesting a potential reversal to the downside.
Additional Considerations:
- Divergences:
- Bullish Divergence: The price makes a lower low, but the RSI forms a higher low. This suggests potential buying opportunity.
- Bearish Divergence: The price makes a higher high, but the RSI forms a lower high. This suggests potential selling opportunity.
- Time Frame: The choice of timeframe can significantly impact the effectiveness of the strategy. Shorter timeframes can be used for day trading, while longer timeframes can be used for swing trading or position trading.
- Risk Management: Always use stop-loss and take-profit orders to manage risk.
- Backtesting: Backtest your strategy on historical data to evaluate its performance and optimize parameters.
Remember:
While this combination of indicators can be a powerful tool, it's essential to use it in conjunction with other technical analysis tools and fundamental analysis to make informed trading decisions.
3.3. The Strategy.
- Strategy Overview.
- The strategy implemented by the Expert Advisor involves a combination of RSI and Zigzag indicators to identify potential entry points.
- Buy Signal:
- RSI Oversold: The RSI dips below the oversold level (24.0).
- Zigzag Bottom: The Zigzag indicator forms a bottom, suggesting a potential uptrend.
- Sell Signal:
- RSI Overbought: The RSI rises above the overbought level (76.0).
- Zigzag Top: The Zigzag indicator forms a top, suggesting a potential downtrend.
The strategy employed with the Expert Advisors in this article involves opening Buy positions below the RSI oversold line and Sell positions above the RSI overbought line. This strategy includes additional pending limit orders and a lot size multiplier using the Martingale system to help mitigate losses.
It is important to note that the most recent Zigzag line may not remain fixed, as it may repaint when the price changes direction. Similarly, the Tops and Bottom RSI indicator may not always accurately indicate overbought conditions when the RSI line is above 76.0 or oversold conditions when the RSI line is below 24.0.
To address ongoing price movements in either direction, we implement a strategy involving the placement of Buy Limit pending orders for upward price trends and Sell Limit pending orders for downward price trends.
If an Expert Advisor initiates a Buy market order and the price subsequently declines, the Buy market order in curs a loss. Similarly, if a Sell market order is executed by the Expert Advisor and the price continues to increase, the Sell market order experiences a loss.
As mentioned earlier, to mitigate larger losses, we implement a lot size multiplier with the Martingale system in stages for each open limit pending order. For every market order opened, the Expert Advisor will also open a maximum of 4 limit pending orders.
Additionally, we configure an option to determine whether the triggering of a pending limit order will result in the closure of the previous market order that is already at a loss. By default, the setting is configured to close market orders in a loss condition if the pending limit order is triggered.
In the meantime, we have configured an option to determine whether triggered limit pending orders will result in the closure of previous market orders that are already in a loss condition. By default, the setting is configured to close market orders in a loss condition if the pending limit order is triggered.
Risk Management:
- Pending Limit Orders: To mitigate potential losses, the Expert Advisor places pending limit orders in the direction of the expected trend.
- Martingale System: A lot size multiplier is used to increase position size after consecutive losses, aiming to recover losses with larger profits.
Important Considerations:
- Market Dynamics: The effectiveness of this strategy can vary depending on market conditions. It may perform better in trending markets and less effectively in range-bound markets.
- Indicator Lag: Both the RSI and Zigzag indicators can lag behind price movements, which may lead to delayed entry or exit signals.
- Risk Management: It's crucial to implement robust risk management techniques, such as stop-loss and take-profit orders, to limit potential losses.
- Back testing: Thorough back testing is essential to evaluate the strategy's historical performance and optimize its parameters.
Note:
The dynamic nature of the market and the potential for indicator repainting highlights the importance of careful monitoring and adjustments to the strategy. It's recommended to use this strategy in conjunction with other technical analysis tools and fundamental analysis to make informed trading decisions.
3.4. Martingale System and Loss Mitigation.
The Expert Advisor incorporates a Martingale system to manage risk and potential losses. This involves increasing the position size of subsequent trades to recover previous losses.
Key Points:
- Limit Pending Orders: The EA opens up to 4 pending limit orders for each market order, with increasing lot sizes.
- Loss Mitigation: The EA is configured to close existing losing market orders when a pending limit order is triggered. This helps to limit potential losses from multiple consecutive losing trades.
- Martingale Risk: While the Martingale system can be effective in certain market conditions, it's important to use it with caution. It's a high-risk strategy that can lead to significant losses if a series of consecutive losing trades occurs.
Important Considerations:
- Risk Management: Implement robust risk management techniques, such as stop-loss and take-profit orders, to limit potential losses.
- Account Balance: Ensure that your trading account has sufficient funds to cover potential losses from multiple consecutive losing trades.
- Market Conditions: The Martingale system may not be suitable for all market conditions. It's essential to consider market volatility and trends when using this strategy.
- Psychological Impact: The Martingale system can be emotionally draining, as it requires disciplined adherence to the strategy, even during periods of consecutive losses.
- Remember: It's crucial to conduct thorough back testing and risk assessment before using the Martingale system in live trading. Always be aware of the inherent risks and adjust your strategy accordingly.
Lastly, the image below illustrates the signal generated by the Zigzag indicator in conjunction with the RSI indicator when the Expert Advisor is about to open a market order for the first time.
By understanding the interplay between the Zigzag and RSI indicators, you can make informed trading decisions and potentially improve your trading outcomes.
4.1. The Challenge of Multi-Currency Trading
The Challenge of Multi-Currency Trading.
When dealing with a multi-currency Expert Advisor that trades multiple pairs on a single chart, managing and monitoring individual pair performance can be cumbersome.
The Solution: A Dedicated Button Panel.
A well-designed button panel can significantly enhance the trading experience. By providing quick access to different chart symbols and timeframes, traders can:
- Monitor Individual Pair Performance: Easily switch between charts to assess the accuracy of entry and exit signals.
- React to Market Changes: Quickly identify opportunities and risks in specific pairs.
- Optimize Trading Strategies: Fine-tune strategies based on real-time market data.
Key Features of an Effective Button Panel:
- Symbol Selection: A dropdown menu or a list of buttons to quickly switch between different currency pairs.
- Timeframe Selection: Options to adjust the timeframe for each symbol, allowing for different time-frame analysis.
- Chart Navigation: Buttons to navigate between charts.
- Order Management: A clear overview of open and closed orders, including profit and loss information on that currency.
4.2. Manual Order Management.
Several manual buttons have been incorporated into this multi-currency expert advisor to enhance efficiency and effectiveness for traders in monitoring the advisor's operations.
- 4.2.1. Set SL / TP All Orders
- This button is beneficial if the trader has initially set the parameters to Use Order Stop Loss (No)and/or Use Order Take Profit (No), but later decides to apply Stop Loss or Take Profit to all orders. By clicking the "Set SL / TP All Orders" button, all orders will be adjusted, and a Stop Loss and/or Take Profit will be implemented across the board.
- 4.2.2. Close All Orders
- If a trader wants to close all orders, they can simply click on the "Close All Orders" button to close all open orders.
- 4.2.3. Close All Orders Profit
- If a trader wishes to close all orders that are currently profitable, they can click on the "Close All Orders Profit" button to close all open orders that have generated profit.
4.3. Managing Orders and Chart Symbols.
For multi-currency expert advisors that trade 30 pairs using only one chart symbol, having a button panel for all symbols would be highly beneficial and convenient. This feature would allow traders to switch between chart timeframes or symbols with a single click, enabling them to quickly assess the accuracy of the indicator signal when the expert advisor opens or closes an order.
4.4. Expert Timeframe, Pair Selection, and Symbol Management
- Expert Timeframe.
- The Expert Timeframe setting determines the timeframe on which the Expert Advisor will calculate indicators and generate trading signals. By default, it's set to PERIOD_H1, meaning the EA will analyze hourly data.
- Adjusting this setting can influence the sensitivity of the strategy to market movements. A shorter timeframe, like PERIOD_M15 or PERIOD_M30, can lead to more frequent signals, while a longer timeframe, like PERIOD_H4 or PERIOD_D1, can produce fewer, but potentially more reliable signals.
- Pair Selection.
- The Select Pairs to Trade property allows traders to choose from a predefined list of currency pairs. The default option is typically to trade all 30 pairs, but traders can customize this selection based on their preferences and risk tolerance.
- Symbol Management with HandlingSymbolArrays()
- The HandlingSymbolArrays() function plays a crucial role in managing the symbols that the Expert Advisor will trade.
- It performs the following tasks:
- Symbol Initialization: Initializes an array to store the selected symbols.
- Symbol Filtering: Filters the selected symbols based on market conditions or other criteria.
- Symbol Validation: Ensures that the selected symbols are valid and supported by the trading platform.
- Symbol Assignment: Assigns the selected symbols to the Expert Advisor's internal variables.
- By effectively managing symbols, the EA can optimize its performance and reduce the risk of errors.
- Validating Pair Names and Error Handling.
- The Expert Advisor's ability to validate pair names is a critical feature to ensure smooth operation and prevent potential errors.
- Here's a breakdown of how this process might work:
- User Input: The trader enters a list of desired pairs in the Expert Advisor's input parameters.
- Symbol Check: The EA iterates through each pair name and checks its validity
- Symbol Existence: The EA verifies if the specified symbol exists in the trading platform's symbol list.
- Symbol Format: The EA ensures that the symbol adheres to the correct format (e.g., EURUSD, GBPUSD, XAUUSD).
- Error Handling:
- If a symbol is invalid, the EA generates a warning message in the journal or displays an alert to the trader and the EA will removed from the chart.
- By incorporating robust symbol validation and error handling, the Expert Advisor can maintain its reliability and prevent unexpected issues.
- Trade Info.
- In the "Other Expert Advisor Parameters" group of input properties, traders can choose whether to display trading information on the chart by selecting either "Yes" or "No". If the option "Yes" is chosen, trade information will be shown on the chart where the Expert Advisor is applied by using the TradeInfo() function. Additionally, we have included a function within the TradeInfo() function to provide a description of the time based on the trading time zone conditions.
- The TradeInfo() function that displays various trading-related information on the chart. It includes details such asserver date and time, broker information, account details, trading parameters, current trading pairs, order statistics, and profit information.
- Within the TradeInfo() function, there is a call to the TodayOrders() function. The TodayOrders() function is responsible for fetching and analyzing trading data for the current day. It computes the overall count of deals, orders, positions, and their categories (buy/sell). It also determines the total count of active market and pending orders. Furthermore, it calculates the cumulative profit by factoring in profits from deals, swaps, and commissions.
In order to enhance the effectiveness and efficiency of using Multi-Currency Expert Advisors, it is advisable to create one or more manual buttons for managing orders and changing chart timeframes or symbols. The OnChartEvent() function that handles various events on a trading chart. It checks for different button clicks on the chart and performs corresponding actions such as setting stop loss/take profit, closing orders, removing expert advisor, changing symbol, and creating manual panels.
The interface of the Multi-Currency Expert Advisor Zigzag RSI MCEA is depicted in the figure below.
There are buttons labeled "M", "C", and "R" under the Expert Advisor named ZigZag_RSI_MCEA.
When the M button is clicked, a panel of manual clicking buttons will be displayed as shown below.
The trader can manually manage orders when the manual click button panel is displayed:
- 5.1. Set SL/TP All Orders
- Set Stop Loss/Take Profit for All Orders: If the trader has set the parameters to not use stop loss or take profit for individual orders but later decides to apply stop loss or take profit to all orders, they can do so by clicking the "Set SL/TP All Orders" button. This action will modify all orders accordingly.
- The SetSLTPOrders() function it iterates through all open positions with a specific magic number, sets stop loss and take profit levels based on current price and position open price, and modifies the position if stop loss or take profit levels are not set.
- 5.2. Close All Orders
- If the trader wants to close all orders, they can do so by clicking the "Close All Orders" button. The CloseAllOrders() function that closes all open positions and orders. It iterates through all positions and orders, closes positions with a specific magic number, and deletes pending orders of specific types.
- 5.3. Close All Profits
- If a trader wants to close all orders that are currently profitable, they can do so by clicking the "Close All Profits" button.
- The ManualCloseAllProfit() function it iterates through open positions with a specific magic number, calculates the total profit including swap and commission, and closes positions with a profit greater than 0.02.
Moreover, when the C button is clicked, a panel displaying 30 symbol names or pairs will appear, allowing traders to select one by clicking on it.
The function code for creating a panel with 30 pairs of symbols is as follows. The CreateSymbolPanel() function it creates a symbol panel with buttons to change the chart symbol. The function sets button styles, labels, positions, and actions for each symbol in the panel. Finally, it redraws the chart.
Clicking on a pair or symbol name will promptly change the chart symbol to the selected one. In this scenario, the OnChartEvent() function will call the ChangeChartSymbol() function when one of the symbol names is clicked.
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//---
//--- handling CHARTEVENT_CLICK event ("Clicking the chart")
ResetLastError();
//--
ENUM_TIMEFRAMES CCS=mc.TFt;
//--
if(id==CHARTEVENT_OBJECT_CLICK)
{
int lensymbol=StringLen(Symbol());
int lensparam=StringLen(sparam);
//--
//--- if "Set SL All Orders" button is click
if(sparam=="Set SL/TP All Orders")
{
mc.SetSLTPOrders();
Alert("-- "+mc.expname+" -- ",Symbol()," -- Set SL/TP All Orders");
//--- unpress the button
ObjectSetInteger(0,"Set SL/TP All Orders",OBJPROP_STATE,false);
ObjectSetInteger(0,"Set SL/TP All Orders",OBJPROP_ZORDER,0);
CreateManualPanel();
}
//--- if "Close All Order" button is click
if(sparam=="Close All Order")
{
mc.CloseAllOrders();
Alert("-- "+mc.expname+" -- ",Symbol()," -- Close All Orders");
//--- unpress the button
ObjectSetInteger(0,"Close All Order",OBJPROP_STATE,false);
ObjectSetInteger(0,"Close All Order",OBJPROP_ZORDER,0);
CreateManualPanel();
}
//--- if "Close All Profit" button is click
if(sparam=="Close All Profit")
{
mc.ManualCloseAllProfit();
Alert("-- "+mc.expname+" -- ",Symbol()," -- Close All Profit");
//--- unpress the button
ObjectSetInteger(0,"Close All Profit",OBJPROP_STATE,false);
ObjectSetInteger(0,"Close All Profit",OBJPROP_ZORDER,0);
CreateManualPanel();
}
//--- if "X" button is click
if(sparam=="X")
{
ObjectsDeleteAll(0,0,OBJ_BUTTON);
ObjectsDeleteAll(0,0,OBJ_LABEL);
ObjectsDeleteAll(0,0,OBJ_RECTANGLE_LABEL);
//--- unpress the button
ObjectSetInteger(0,"X",OBJPROP_STATE,false);
ObjectSetInteger(0,"X",OBJPROP_ZORDER,0);
//--
DeleteButtonX();
mc.PanelExtra=false;
DisplayManualButton();
}
//--- if "M" button is click
if(sparam=="M")
{
//--- unpress the button
ObjectSetInteger(0,"M",OBJPROP_STATE,false);
ObjectSetInteger(0,"M",OBJPROP_ZORDER,0);
mc.PanelExtra=true;
CreateManualPanel();
}
//--- if "C" button is click
if(sparam=="C")
{
//--- unpress the button
ObjectSetInteger(0,"C",OBJPROP_STATE,false);
ObjectSetInteger(0,"C",OBJPROP_ZORDER,0);
mc.PanelExtra=true;
CreateSymbolPanel();
}
//--- if "R" button is click
if(sparam=="R")
{
Alert("-- "+mc.expname+" -- ",Symbol()," -- expert advisor will be Remove from the chart.");
ExpertRemove();
//--- unpress the button
ObjectSetInteger(0,"R",OBJPROP_STATE,false);
ObjectSetInteger(0,"R",OBJPROP_ZORDER,0);
if(!ChartSetSymbolPeriod(0,Symbol(),Period()))
ChartSetSymbolPeriod(0,Symbol(),Period());
DeletePanelButton();
ChartRedraw(0);
}
//--- if Symbol button is click
if(lensparam==lensymbol)
{
int sx=mc.ValidatePairs(sparam);
ChangeChartSymbol(mc.AS30[sx],CCS);
mc.PanelExtra=false;
}
//--
}
//--
return;
//---
} //-end OnChartEvent()
//---------//
void ChangeChartSymbol(string c_symbol,ENUM_TIMEFRAMES cstf)
{
//---
//--- unpress the button
ObjectSetInteger(0,c_symbol,OBJPROP_STATE,false);
ObjectSetInteger(0,c_symbol,OBJPROP_ZORDER,0);
ObjectsDeleteAll(0,0,OBJ_BUTTON);
ObjectsDeleteAll(0,0,OBJ_LABEL);
ObjectsDeleteAll(0,0,OBJ_RECTANGLE_LABEL);
//--
ChartSetSymbolPeriod(0,c_symbol,cstf);
//--
ChartRedraw(0);
//--
return;
//---
} //-end ChangeChartSymbol()
//---------//
This code snippet checks if a chart object click event (CHARTEVENT_OBJECT_CLICK) has occurred. It compares the lengths of the current symbol and the parameter "sparam". If the lengths match, it validates the symbol and changes the chart symbol to the validated symbol from the arrays predefined list "mc.AS30".
The ChangeChartSymbol() function it un-presses the button associated with the symbol, deletes all objects related to buttons, labels, and rectangles, changes the chart symbol and timeframe, redraws the chart.
Lastly, clicking on the R button will remove the Multi-Currency Expert Advisor ZigZag_RSI_MCEA from the chart, eliminating the need for traders to manually remove the experts.
This code snippet checks if a chart object click event (CHARTEVENT_OBJECT_CLICK) has occurred. If the parameter "sparam" is equal to "R", it displays an alert message, removes the expert advisor from the chart, un-presses the "R" button, resets its z-order, sets the chart symbol and period back to the original values, deletes panel buttons, and redraws the chart.
6. Strategy Tester
The advantage of MetaTrader5 Strategy Tester is that it supports and enables us to test strategies that can tradeon multiple currencies symbols, test automated trading for all available currencies symbols, and across allavailable timeframes.
Therefore, on the MetaTrader5 Strategy Tester platform, we will test the ZigZag_RSI_MCEA Multi-Currency ExpertAdvisor on a single pair (single currency) as well as on multiple pairs (multi-currency).
Because this expert advisor will open multiple orders, by default we set the lot size when opening a market orderwith a minimum lot size of 0.01.
First, we will test the MetaTrader5 Strategy Tester in single pair mode using the EURUSD pair on the H1 timeframe from January 1, 2024, to April 13, 2024.
The results are as shown in the images below:
The results are as shown in the images below:

Key Parameters to Monitor:
- Net Profit: The overall profit or loss generated during the testing period.
- Profit Factor: The ratio of gross profit to gross loss.
- Drawdown: The maximum peak-to-trough decline in equity.
- Sharpe Ratio: A measure of risk-adjusted return.
- Recovery Factor: The ratio of gross profit to maximum drawdown.
Interpreting the Results:
- Positive Net Profit: Indicates a profitable strategy during the testing period.
- High Profit Factor: Suggests that the strategy generates significant profits relative to losses.
- Low Drawdown: Implies that the strategy minimizes risk and avoids large drawdowns.
- High Sharpe Ratio: Indicates a strong risk-adjusted return.
- High Recovery Factor: Shows the strategy's ability to recover from losses.
Multi-Pair Testing.
Key Considerations for Multi-Pair Testing:
- Correlation: Consider the correlation between different pairs to avoid overexposure to specific market movements.
- Diversification: Diversifying across multiple pairs can help reduce overall risk.
- Risk Management: Implement robust risk management strategies, such as position sizing and stop-loss orders, to manage risk effectively.
- Monitoring and Adjustment: Continuously monitor the performance of the strategy and make necessary adjustments to adapt to changing market conditions.
By carefully testing the ZigZag_RSI_MCEA strategy on both single-pair and multi-pair setups, you can gain valuable insights into its performance and identify potential areas for improvement.
The conclusion of creating a Multi-Currency Expert Advisor with signals from the Zigzag indicator in conjunction with the RSI indicator for forex trading using MQL5 is as follows:
- 1. Creating a multi-currency Expert Advisor in MQL5 is straightforward and not significantly different from creating a single-currency Expert Advisor.
- 2. Creating a Multi-Currency Expert Advisor will enhance traders' efficiency and effectiveness by eliminating the need to open multiple chart symbols for trading.
- 3. Applying the right trading strategy will increase the probability of profit compared to using a single-currency Expert Advisor. This is because losses in one pair will be covered by profits in other pairs.
- 4. The Zigzag_RSI_MCEA Multi-Currency Expert Advisor is provided as a sample for learning and idea generation. The test results on the Strategy Tester have not been satisfactory. Therefore, it is possible to improve the strategy and achieve more profitable results by experimenting with different timeframes, indicator period calculations, and signal selections.
- 5. Further research should be conducted on the Multi-Currency Expert Advisor that utilizes signals from the Zigzag indicator and the RSI indicator for forex trading. This research should include exploring the "limit pending order" strategy and the lot size multiplier. Various experiments should be carried out, starting from analyzing different timeframes to adjusting the differentiation value of the Zigzag indicator input parameters.
- 6. Applying the lot size multiplier with the Martingale system, when done wisely, carefully, and based on the right indicator signals rather than speculation, can effectively reduce losses and potentially increase profits, based on my observations.
Here are some additional points to consider for further improvement:
Additional Considerations:
- Risk Management:
- Emphasize the importance of robust risk management techniques, such as stop-loss and take-profit orders, to protect capital.
- Discuss the role of position sizing and money management strategies in optimizing risk-reward ratios.
- Backtesting and Optimization:
- Highlight the significance of thorough backtesting to evaluate the strategy's historical performance and identify optimal parameters.
- Encourage the use of optimization techniques to fine-tune the strategy's settings.
- Forward Testing:
- Stress the importance of forward testing to assess the strategy's performance in real-time market conditions.
- Consider using a demo account to test the strategy before risking real capital.
- Continuous Learning:
- Encourage continuous learning and adaptation to evolving market conditions.
- Stay updated on the latest trading techniques and technological advancements.
- Potential Future Directions:
- Advanced Trading Strategies: Explore more complex strategies, such as trend-following, mean-reversion, or volatility-based approaches.
- Machine Learning: Incorporate machine learning techniques to improve prediction accuracy and optimize trading parameters.
- AI-Powered Trading: Utilize artificial intelligence to automate decision-making processes and adapt to changing market conditions.
By combining technical analysis, risk management, and continuous learning, traders can enhance trading strategies and improve overall performance.
We hope that this article and the MQL5 Multi-Currency Expert Advisor program will be beneficial for traders in learning and generating new ideas, which can ultimately make money from forex trading.
Thanks for reading this article.
Please download the Expert Advisor: ZigZag_RSI_MCEA
If you are subscribed to my YouTube Channel, and would like to receive the source program of this article, please send a request via the Contact Us form page, and I will send it to your email, source code: ZigZag_RSI_MCEA.
Don't forget to stop by and subscribe to Forex Home Experts YouTube Channel:
YouTube Channel: @ForexHomeExperts YouTube Playlist: @ForexHomeExperts YouTube Playlist
0 comments:
Post a Comment