MOVING AVERAGE EXPERT ADVISOR



INTRODUCTION.

A Moving Average Expert Advisor (EA) is an automated trading system designed to execute trades based on the crossover of two moving averages. Moving averages are widely used in technical analysis to smooth out price data and identify trends. The EA described here uses a combination of a faster moving average with a period of 20 and a slower moving average with a period of 50. When the faster moving average crosses above the slower moving average, it generates a buy signal, and when it crosses below the slower moving average, it generates a sell signal.

The primary purpose of this EA is to take advantage of trending market conditions by entering trades in the direction of the trend. The use of moving averages for generating signals ensures that the EA reacts quickly to changes in price trends, making it suitable for capturing medium to long-term price movements.

Trade Strategy:

Buy Signal: The EA generates a buy signal when the 20-period moving average crosses above the 50-period moving average. This suggests a potential upward trend in the market, and the EA will initiate a long (buy) trade.

Sell Signal: Conversely, the EA generates a sell signal when the 20-period moving average crosses below the 50-period moving average. This indicates a potential downward trend, prompting the EA to initiate a short (sell) trade.

Risk Management:

To protect against potential losses, the EA incorporates a stop-loss and take-profit mechanism:

Stop Loss: The stop-loss level is set at 75 pips from the entry price. If the trade moves against the EA's position, reaching a loss of 75 pips, the EA will automatically close the trade to limit further losses.

Take Profit: The take-profit level is set at 200 pips from the entry price. When the market moves favorably and reaches a profit of 200 pips, the EA will close the trade to lock in the gains.

By using this risk management approach, the Moving Average EA aims to maintain a favorable risk-to-reward ratio while staying disciplined during trades.

The Code

#include <Trade/Trade.mqh>

CTrade trade;

int OnInit(){

   return(INIT_SUCCEEDED);

  }

void OnDeinit(const int reason){

  }

void OnTick(){

    static datetime timestamp;

    datetime time = iTime(_Symbol,PERIOD_CURRENT,0);

    if(timestamp != time){

   timestamp = time;

  static int handleSlowma = iMA(_Symbol,PERIOD_CURRENT,50,0,MODE_SMA,PRICE_CLOSE);

   double slowMaArray[];

   CopyBuffer(handleSlowma,0,1,2,slowMaArray);

   ArraySetAsSeries(slowMaArray,true);

   static int handlefastma = iMA(_Symbol,PERIOD_CURRENT,20,0,MODE_SMA,PRICE_CLOSE);

   double fastMaArray[];

   CopyBuffer(handlefastma,0,1,2,fastMaArray);

   ArraySetAsSeries(fastMaArray,true);

   if(fastMaArray[0]>slowMaArray[0] && fastMaArray[1]<slowMaArray[1]){

   Print("I KNOW YOU WANT ME");

   double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);

   double sl = ask-75*SymbolInfoDouble(_Symbol,SYMBOL_POINT);

   double tp = ask+200*SymbolInfoDouble(_Symbol,SYMBOL_POINT);

   trade.Buy(0.01,_Symbol,ask,sl,tp,"This is a buy");

   }

     if(fastMaArray[0]<slowMaArray[0] && fastMaArray[1]>slowMaArray[1]){

   Print("I KNOW YOU WANT ME 2");

   double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);

   double sl = bid+75*SymbolInfoDouble(_Symbol,SYMBOL_POINT);

   double tp = bid-200*SymbolInfoDouble(_Symbol,SYMBOL_POINT);

   trade.Sell(0.01,_Symbol,bid,sl,tp,"This is a sell");

   }

   Comment("\nslowMaArray[0]:",slowMaArray[0],

            " \nslowMaArray[1]:",slowMaArray[1],

            "\nfastMaArray[0]:",fastMaArray[0],

            " \nfastMaArray[1]:",fastMaArray[1]);

     }

  }

Problem Statement

The goal is to back test the Moving Average Expert Advisor over a 5-year period across major forex pairs, evaluating its performance in generating buy/sell signals based on the crossover of 20-period and 50-period moving averages, and determining its profitability and reliability.

Assumptions

1.       5 yrs. look back period

2.       No forward rate

3.       Initial deposit $5000

4.       Leverage of 1:100

5.       Zero latency on delays

6.       Modelling is done on open prices only

7.       No optimization


 

 





















The Moving Average Expert Advisor was back tested across major forex pairs over a 5-year period. The total trades executed at different timeframes are as follows:

1 MIN: High trading frequency with EUR/USD having 44,229 trades.

5 MIN: Relatively lower trading frequency with USD/JPY and AUD/USD having 9,654 trades each.

30 MIN: Moderate trading frequency with EUR/USD leading at 1,533 trades.

4 HR: Decreased trading frequency with EUR/USD having 216 trades.

DAILY: Further reduction in trading frequency with EUR/USD at 35 trades.

WEEKLY: The lowest trading frequency, with most pairs having less than 6 trades.







 The win/loss rates varied across pairs and timeframes, with profit trades ranging from around 15% to 34.48% and loss trades ranging from approximately 65.52% to 85%. Weekly trades had the lowest win rates, while daily trades showed a higher percentage of profitable trades. The performance of the EA depended on the specific currency pair and the timeframe used for trading.




During the back testing of the Moving Average Expert Advisor its performance in terms of consecutive wins and losses was analyzed. The results showed that the maximum consecutive wins varied across different pairs and timeframes, with the highest recorded at 35 trades for USD/JPY on the 1-minute timeframe. Conversely, the maximum consecutive losses ranged from 56 trades for USD/CHF on the 1-minute timeframe to 114 trades for GBP/USD on the same timeframe. The data indicated that the EA's ability to maintain consecutive wins or losses was influenced by the specific currency pair and the timeframe used for trading.





During the 5-year back testing period of the Moving Average Expert Advisor the gross profit and loss for each pair and timeframe were recorded. Among the shortest timeframes, such as 1-minute and 5-minute charts, the gross profit for USD/JPY was particularly notable, reaching $24,185.99 and $4,890.55, respectively. However, these timeframes also experienced significant gross losses, with USD/JPY recording $26,808.52 for 1-minute and $5,406.00 for 5-minute charts. As the timeframe increased, the gross profit and loss tended to stabilize, with some variations observed across different pairs. For example, on the 4-hour chart, USD/JPY had a gross profit of $104.00 and a gross loss of $111.00.



 





During the back testing period the advisor exhibited varying net profit across major forex pairs and different timeframes. The net profit figures represent the overall profit generated by the EA after accounting for both winning and losing trades. On shorter timeframes, such as 1-minute and 5-minute charts, the net profit tended to be negative for most pairs, with losses recorded for EUR/USD (-$2,990.50 on the 1-minute timeframe) and GBP/USD (-$950.10 on the 5-minute timeframe). As the timeframe increased, the net profit generally improved, showing fewer losses. However, even on longer timeframes like daily and weekly charts, some pairs still experienced negative net profit, indicating overall losses.



 

Risk analysis is a crucial aspect of evaluating the performance of a trading strategy. Let's examine each risk parameter for the Moving Average Expert Advisor's performance on different timeframes and currency pairs:

Profit Factor: This parameter measures the ratio of gross profit to gross loss. A value below 1 indicates that losses outweigh profits. Across most timeframes, the Profit Factor suggests that the EA struggled to generate profits consistently, especially on shorter timeframes like 1-minute and 5-minute charts. The values are relatively better on longer timeframes, but they still indicate room for improvement.

Recovery Factor: The Recovery Factor shows the EA's ability to recover from drawdowns. Negative values suggest a lack of recovery capability. Unfortunately, across all timeframes, the Recovery Factor was consistently negative, indicating that the EA was unable to recover from losses efficiently.

Expected Payoff: This parameter represents the average profit or loss per trade. Negative values indicate that, on average, the EA suffered losses per trade. The Expected Payoff values were mostly negative across all timeframes, signaling a need for optimization to improve the EA's profitability.

Sharpe Ratio: The Sharpe Ratio assesses the risk-adjusted return of the strategy. Negative values imply inadequate risk-adjusted returns. Across all timeframes, the Sharpe Ratio remained mostly negative, indicating that the EA's risk-adjusted returns were unfavorable.

Z Score: The Z Score measures the deviation of the strategy's performance from the mean in terms of standard deviations. Negative Z Scores suggest underperformance relative to the mean. The EA displayed consistently negative Z Scores across different timeframes, indicating poor performance.























In summary, the risk analysis of the Moving Average Expert Advisor's performance reveals significant challenges in generating consistent profits, recovering from drawdowns, and achieving favorable risk-adjusted returns. Further optimization and adjustments are necessary to enhance the EA's overall performance and make it a more robust and profitable trading too.

 

 

The performance analysis of the Moving Average Expert Advisor across different timeframes and major forex pairs indicates significant challenges and limitations. The EA struggled to generate consistent profits, and losses outweighed profits on most timeframes, especially on shorter ones like 1-minute and 5-minute charts. Additionally, the negative Recovery Factor highlights the EA's inability to recover effectively from drawdowns, further compounding its performance issues. The Expected Payoff and Sharpe Ratio values were mostly negative, indicating unfavorable risk-adjusted returns.

 

Based on the risk analysis and performance data, it is evident that the Moving Average Expert Advisor requires substantial improvements and optimizations. Before considering live trading, we recommend the following steps:

Optimization: Conduct extensive optimization by adjusting the parameters of the moving averages and stop-loss/take-profit levels. Test different combinations to identify settings that yield better results.

Filtering Mechanisms: Implement additional filters or conditions to improve trade selection, ensuring trades are taken under more favorable market conditions.

Back testing on Extended Data: Perform back testing on a longer historical dataset to assess the EA's performance under various market conditions and economic events.

Risk Management: Implement strict risk management rules to limit losses and protect the trading account.

Forward Testing: After optimizing the EA, conduct forward testing on a demo account to validate its performance in real-time market conditions.

Continuous Monitoring and Improvement: Regularly monitor the EA's performance and make adjustments as needed based on new market dynamics and changing conditions.

 

It is crucial to remember that no trading strategy is foolproof, and past performance does not guarantee future results. Always exercise caution and consider the risks involved in trading forex. Consulting with experienced traders or financial advisors can provide valuable insights and guidance during the optimization process


Comments

Popular posts from this blog

102 : FINANCIAL MARKETS

104 : INSURANCE