SCALPING STRATERGY

 


INTRODUCTION

In the dynamic world of financial markets, traders constantly seek effective strategies that capitalize on short-term price movements. One such strategy is scalping, which aims to profit from small price changes within a tight timeframe. This back testing study focuses on a scalping strategy that employs exponential moving averages (EMA) to identify potential market trends and capitalize on pullback opportunities. By combining the 1-hour and 5-minute charts, this strategy aims to strike a balance between identifying broader trends and seizing short-term price movements. The strategy utilizes EMAs of different periods to enhance its sensitivity to price changes and employs a systematic approach to risk management through stop loss and take profit levels.

The Code

#include <Trade/Trade.mqh>

 

int handletrademafast;

int handletrademaslow;

 

int handlemafast;

int handlemamiddle;

int handlemaslow;

 

CTrade trade;

 

int eamagic=2;

 

double ealots = 0.05;

 

int OnInit(){

 

     trade.SetExpertMagicNumber(eamagic);

 

     handletrademafast = iMA(_Symbol,PERIOD_H1,8,0,MODE_EMA,PRICE_CLOSE);

     handletrademaslow = iMA(_Symbol,PERIOD_H1,21,0,MODE_EMA,PRICE_CLOSE);

    

     handlemafast = iMA(_Symbol,PERIOD_M5,8,0,MODE_EMA,PRICE_CLOSE);

     handlemamiddle = iMA(_Symbol,PERIOD_M5,13,0,MODE_EMA,PRICE_CLOSE);

     handlemaslow = iMA(_Symbol,PERIOD_M5,21,0,MODE_EMA,PRICE_CLOSE);

   return(INIT_SUCCEEDED);

}

 

void OnDeinit(const int reason){

 

  

}

 

void OnTick(){

    double matrendfast[],matrendslow[];

     CopyBuffer(handletrademafast,0,0,1,matrendfast);

     CopyBuffer(handletrademaslow,0,0,1,matrendslow);

    

     double mafast[], mamiddle[], maslow[];

     CopyBuffer(handlemafast,0,0,1,mafast);

     CopyBuffer(handlemamiddle,0,0,1,mamiddle);

     CopyBuffer(handlemaslow,0,0,1,maslow);

    

     double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);

     int trenddirection = 0;

     if(matrendfast [0] > matrendslow [0] && bid > matrendfast [0]){

       trenddirection = 1;

  }else if(matrendfast [0] < matrendslow [0] && bid < matrendfast [0]){

       trenddirection = -1;

}

 

     int positions =0;

     for(int i = PositionsTotal() -1; i>=0; i--){

      ulong posTicket = PositionGetTicket(i);

      if(PositionSelectByTicket(posTicket)) {

      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC)== eamagic){

        positions = positions+1;

       

        if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY){

        if(PositionGetDouble(POSITION_VOLUME)>= ealots){

          double tp = PositionGetDouble(POSITION_PRICE_OPEN) + PositionGetDouble(POSITION_PRICE_OPEN) - PositionGetDouble(POSITION_SL);

         

          if(bid >= tp){

             if(trade.PositionClosePartial(posTicket,NormalizeDouble(PositionGetDouble(POSITION_VOLUME)/2,2))){

              double sl = PositionGetDouble(POSITION_PRICE_OPEN);

              sl = NormalizeDouble(sl,_Digits);

              if(trade.PositionModify(posTicket,sl,0)) {             

      }

   }   

 }

      }else{

         int lowest =iLowest(_Symbol,PERIOD_M5,MODE_LOW,3,1);

         double sl = iLow(_Symbol,PERIOD_M5,lowest);

         sl = NormalizeDouble(sl,_Digits);

        

         if(sl > PositionGetDouble(POSITION_SL)){

         if(trade.PositionModify(posTicket,sl,0)){

      }

    }

  }

          }else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL){

          if(PositionGetDouble(POSITION_VOLUME)>= ealots){

          double tp = PositionGetDouble(POSITION_PRICE_OPEN) -PositionGetDouble(POSITION_SL)- PositionGetDouble(POSITION_PRICE_OPEN);

         

          if(bid <= tp){

             if(trade.PositionClosePartial(posTicket,NormalizeDouble(PositionGetDouble(POSITION_VOLUME)/2,2))){

              double sl = PositionGetDouble(POSITION_PRICE_OPEN);

              sl = NormalizeDouble(sl,_Digits);

              if(trade.PositionModify(posTicket,sl,0)) {

          }

        }

     }

  }

   

          }else{

         int highest =iHighest(_Symbol,PERIOD_M5,MODE_HIGH,3,1);

         double sl = iHigh(_Symbol,PERIOD_M5,highest);

         sl = NormalizeDouble(sl,_Digits);

        

         if(sl <PositionGetDouble(POSITION_SL)){

         if(trade.PositionModify(posTicket,sl,0)){    

            }

          }

       }

     }  

   }

 }

     

      int orders =0;

     for(int i = OrdersTotal() -1; i>=0; i--){

      ulong orderTicket = OrderGetTicket(i);

      if(OrderSelect(orderTicket)) {

      if(OrderGetString(ORDER_SYMBOL) == _Symbol && OrderGetInteger(ORDER_MAGIC)== eamagic){

        if(OrderGetInteger(ORDER_TIME_SETUP) < TimeCurrent() - 30 * PeriodSeconds(PERIOD_M1)){

           trade.OrderDelete(orderTicket);

 }

        orders = orders +1;

      }  

    }

  }

     if(trenddirection ==1){

        if(mafast [0] >mamiddle [0] && mamiddle [0] > maslow [0]){

        if(bid <= mafast [0]){

          if(positions + orders <= 0){

            int indexHighest = iHighest(_Symbol,PERIOD_M5,MODE_HIGH,5,1);

            double highprice =iHigh(_Symbol,PERIOD_M5,indexHighest);

             highprice =NormalizeDouble(highprice,_Digits);

            

            double sl = iLow(_Symbol,PERIOD_M5,0) - 30 * _Point;

            sl = NormalizeDouble(sl,_Digits);

           

           

            trade.BuyStop(ealots, highprice,_Symbol,sl);

     }

   }  

 }

  }else if(trenddirection== -1){

        if(mafast [0] < mamiddle [0] && mamiddle [0] < maslow [0]){

        if(bid >= mafast[0]){

          if(positions + orders <= 0){

           int indexLowest = iLowest(_Symbol,PERIOD_M5,MODE_LOW,5,1);

           double lowestprice = iLow(_Symbol,PERIOD_M5,indexLowest);

           lowestprice = NormalizeDouble(lowestprice,_Digits);

          

            double sl = iHigh(_Symbol,PERIOD_M5,0) + 30 * _Point;

            sl = NormalizeDouble(sl,_Digits);

                      

          

            trade.SellStop(ealots, lowestprice,_Symbol, sl);   

       } 

     }

   }       

 }

    

     Comment("\nFast Trend ma : ", DoubleToString (matrendfast[0],_Digits),

             "\nSlow Trend ma : ", DoubleToString (matrendslow[0],_Digits),

              "\nTrend Direction : ",trenddirection,

              "\n",

              "\nFast ma : ",DoubleToString(mafast[0],_Digits),

              "\nMiddle ma : ",DoubleToString(mamiddle[0],_Digits),

              "\nSlow ma : ",DoubleToString(maslow[0],_Digits),

              "\n",

              "\nPositions :", positions,

              "\nOrders : ", orders);

  

} 

Problem Statement

The problem addressed in this back testing study is to assess the effectiveness and viability of the proposed scalping strategy utilizing 1-hour and 5-minute charts with specific EMA settings. While scalping strategies have the potential to capture numerous quick trades, they also require precision in execution and a robust risk management approach due to their short holding periods. This study aims to investigate whether the use of EMAs for trend identification, combined with specific entry and exit rules, can consistently generate profitable trading outcomes.

 

Key areas of focus include:

 

The accuracy of trend identification using the 8 and 21 EMAs on the 1-hour chart.

The performance of the 8, 13, and 21 EMAs on the 5-minute chart for refining entry points.

The effectiveness of the entry criterion based on the pullback to the 8 EMA on the 5-minute chart.

Evaluating the risk-reward ratio and its impact on the overall strategy's profitability.

The robustness of the trailing stop-loss mechanism in locking in gains while allowing for potential upside movement.

Through back testing, this study aims to provide insights into the strategy's historical performance, including its win rate, average profit, average loss, and drawdowns. Additionally, any potential pitfalls or shortcomings of the strategy will be highlighted, including scenarios where the strategy may struggle to adapt to changing market conditions or fail to generate consistent returns. By addressing these aspects, traders can gain a better understanding of the strategy's potential and limitations, enabling them to make informed decisions when incorporating it into their trading approach

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

 

OBSERVATIONS




DATA ANALYSIS AND COLLECTION

 


Among the currency pairs listed, USD/JPY has the highest number of both total trades and total deals, suggesting that this pair is particularly conducive to the strategy's setup. GBP/USD and USD/CHF also exhibit a considerable number of trades and deals, indicating that the strategy's parameters may have been effective in these pairs as well. EUR/USD, AUD/USD, USD/CAD, and NZD/USD have relatively lower numbers of trades and deals, suggesting that the strategy might be less suitable for these pairs or may require further optimization.

The strategy's success across different currency pairs can vary due to their unique characteristics and volatility levels. Currency pairs with higher trading volumes and liquidity, such as USD/JPY, might present more opportunities for scalping due to tighter bid-ask spreads and reduced slippage.


The percentage of profit trades is higher than loss trades for most currency pairs, indicating that the strategy has a generally positive win rate across the board. GBP/USD has the highest percentage of profit trades at 59.20%, suggesting that the strategy may have been particularly successful in capturing profitable opportunities in this pair. USD/CHF has the lowest percentage of profit trades at 36.25%, implying that the strategy might face challenges in generating consistent profits in this pair.

The higher percentage of profit trades across most pairs suggests that the strategy has the potential to identify and capture profitable opportunities. The varying percentages of profit trades between pairs indicate that the strategy's effectiveness may be influenced by each pair's unique price behavior and volatility.


GBP/USD has the highest largest profit trade value at 782.80, indicating a substantial profitable trade within this pair according to the strategy. USD/JPY also shows a significant largest profit trade value at 238.65, suggesting that the strategy was able to capture a notable price movement in this pair. The largest profit trade values for AUD/USD, USD/CAD, and NZD/USD are also considerable, showcasing the strategy's potential in these pairs. The largest profit trade values are generally much higher than the largest loss trade values across all pairs.

The larger profit values indicate that the strategy has the ability to capture significant price movements during favorable market conditions. The lower largest loss trade values suggest that the strategy's risk management measures, such as stop loss orders, have been effective in limiting potential losses.

USD/JPY has the highest recorded max consecutive wins at 16, indicating that the strategy experienced a notable streak of successful trades in this pair. GBP/USD and EUR/USD also display significant max consecutive wins, suggesting the strategy's potential to achieve consistent profitable runs in these pairs. USD/CHF stands out with a high number of max consecutive losses at 33, indicating that the strategy faced challenges in maintaining consistency in this pair. AUD/USD, USD/CAD, and NZD/USD have relatively lower max consecutive wins and losses, which might suggest more mixed performance or sensitivity to market conditions.

The data on max consecutive wins provides insights into the strategy's ability to capture a streak of profitable trades without significant interruptions. The information on max consecutive losses highlights the strategy's vulnerability to sustained losing streaks and its potential impact on capital preservation.


USD/JPY has the highest gross profit value at $2,147.22, indicating that the strategy was able to capture significant monetary gains in this pair. USD/CHF and GBP/USD also display notable gross profit figures, suggesting that the strategy performed well in generating positive returns in these pairs. USD/CAD and USD/JPY have relatively high gross loss figures, which could be attributed to unfavorable market conditions or potential challenges with the strategy's implementation.


Among the pairs listed, USD/CHF exhibits the highest absolute balance and equity drawdown values, indicating that this pair experienced the most significant decline from its peak balance and equity. USD/JPY, USD/CAD, and NZD/USD also display considerable drawdown figures, suggesting that these pairs may have encountered periods of substantial losses. GBP/USD and AUD/USD have relatively lower drawdown values, implying potentially more stable performance during the testing period.

Drawdown values are crucial for understanding the potential risk exposure of the strategy and its ability to withstand adverse market conditions. Comparing the absolute balance drawdown and absolute equity drawdown provides insights into the impact of both trading performance and equity fluctuations on account resilience.


GBP/USD shows the highest total net profit at $650.12, indicating that the strategy was able to generate a substantial profit in this pair. AUD/USD also displays a notable total net profit at $600.09, suggesting that the strategy performed well in capturing profitable opportunities in this pair. USD/JPY, USD/CAD, and NZD/USD exhibit negative total net profit figures, indicating losses incurred during the testing period. USD/CHF and USD/CAD display significant negative total net profit figures, implying that the strategy faced challenges in generating positive returns in these pairs.

The strategy's profitability varies between currency pairs, highlighting the importance of selecting suitable pairs based on the strategy's characteristics.




Profit Factor: The "Profit Factor" metric provides insight into the ratio of gross profit to gross loss generated by the scalping strategy across different currency pairs. Among the pairs, GBP/USD stands out with the highest profit factor of 2.39, suggesting that the strategy managed to yield approximately 2.39 units of profit for each unit of loss. This indicates a favorable balance between profitable and losing trades in GBP/USD.

Recovery Factor: The "Recovery Factor" offers an understanding of the strategy's resilience in recovering from drawdowns. GBP/USD and AUD/USD display positive recovery factors, indicating that they experienced relatively strong recoveries after encountering periods of drawdown. This suggests that the strategy was able to bounce back and regain profitability in these pairs.

Expected Payoff: The "Expected Payoff" metric evaluates the average gain or loss per trade and sheds light on the strategy's trade dynamics. GBP/USD and AUD/USD exhibit notably high expected payoff values, implying that the strategy tended to generate larger gains per winning trade compared to the losses incurred per losing trade. This suggests a potentially favorable risk-reward profile in these pairs.

 

Sharpe Ratio: The "Sharpe Ratio" measures the risk-adjusted return of the strategy, indicating how efficiently the strategy generates returns relative to its risk exposure. AUD/USD displays the highest Sharpe Ratio at 0.29, indicating a relatively favorable risk-adjusted performance in this pair. This suggests that the strategy managed to achieve proportionally higher returns for the level of risk taken.

 

Z Score: The "Z Score" quantifies how much the strategy's returns deviate from the average return, expressed in standard deviations. The negative Z Scores observed across all pairs suggest that the strategy's returns significantly deviated from the average during the testing period. This indicates that the strategy experienced periods of underperformance and volatility.

 

Margin Level: The "Margin Level" showcases the account equity's health in relation to the used margin, presented as a percentage. The high margin levels recorded for all pairs suggest that the strategy was well-capitalized and maintained a healthy cushion relative to the used margin. This implies that the strategy was not at risk of a margin call and was adequately funded.

 

In conclusion, the provided performance metrics offer a comprehensive assessment of the scalping strategy's performance across different currency pairs. The metrics highlight varying strengths and weaknesses in each pair, suggesting that certain pairs may align more closely with the strategy's parameters and risk appetite. Traders can use these insights to make informed decisions about pair selection, strategy optimization, and overall trading approach.


Summary

The back testing analysis of the scalping strategy across multiple currency pairs provides a comprehensive understanding of its performance characteristics. The strategy, utilizing a combination of 1-hour and 5-minute charts with specific EMA settings, aims to capture short-term price movements while incorporating risk management measures. Here are the key takeaways from the analysis:

Across the different currency pairs, the strategy demonstrated varying degrees of success. GBP/USD emerged as a standout performer, showcasing high profit factors, positive recovery factors, and impressive expected payoff values. Additionally, AUD/USD exhibited strong performance in terms of risk-adjusted returns, indicating a favorable balance between risk and reward.

Conversely, USD/JPY, USD/CHF, USD/CAD, and NZD/USD faced challenges in generating consistent profitability. These pairs displayed negative total net profits, lower profit factors, and less favorable risk-adjusted returns. USD/CHF, in particular, had the lowest profit factor and exhibited substantial drawdowns, indicating potential difficulties in aligning the strategy with its price behavior.

The strategy's win rate and ability to capitalize on profitable opportunities were evident in the profit percentages across most pairs. Notably, GBP/USD, USD/JPY, and AUD/USD displayed relatively high percentages of profit trades, indicating successful identification of potential trends and entry points.

The analysis of consecutive wins and losses shed light on the strategy's consistency. While certain pairs like USD/JPY and GBP/USD showcased extended winning streaks, others experienced challenges in maintaining consistent profitability. This suggests the importance of closely monitoring market conditions and adapting the strategy accordingly.

The provided data on gross profit, gross loss, drawdowns, and recovery factors highlighted the strategy's risk management. GBP/USD and AUD/USD exhibited positive recovery factors, indicating a capacity to recover from drawdowns effectively. However, pairs like USD/CHF faced larger absolute equity and balance drawdowns, indicating the need for refined risk management techniques. 

Recommendations

In light of these observations, here are the recommendations:

Pair Selection: Focus on currency pairs that have shown consistent profitability and favorable performance metrics. GBP/USD and AUD/USD appear promising based on their high profit factors, positive recovery factors, and robust risk-adjusted returns.

Risk Management: Strengthen risk management measures, particularly for pairs like USD/CHF that exhibited higher drawdowns. Carefully consider position sizing, stop loss placement, and trailing stop mechanisms to safeguard against extended losing streaks.

Strategy Optimization: Consider fine-tuning the strategy's parameters, including EMA settings and entry criteria, to better align with the unique behavior of each currency pair. Conduct further sensitivity analysis to identify optimal parameters for improved performance.

Diversification: While GBP/USD and AUD/USD show promise, diversify the trading approach by including a mix of pairs to mitigate risk and avoid overconcentration in a single pair.

Continuous Monitoring: Stay vigilant in monitoring market conditions, news events, and economic indicators that may impact the selected currency pairs. Adapt the strategy as needed to address changing market dynamics.

Real-world Testing: While back testing provides valuable insights, consider running the strategy in a controlled demo environment before deploying it in a live trading setting. This can help validate its performance in real-world conditions.

In conclusion, the analysis offers a thorough evaluation of the scalping strategy's performance. By leveraging the strengths observed in certain currency pairs, addressing challenges, and continuously refining the strategy, traders can position themselves for a more informed and strategic approach to scalping in the dynamic forex market.









Comments

Popular posts from this blog

102 : FINANCIAL MARKETS

104 : INSURANCE

MOVING AVERAGE EXPERT ADVISOR