Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

rite an expert advisor for metatrader 5 using a standard bollinger bands breakout…

  1. User

    rite an expert advisor for metatrader 5 using a standard bollinger bands breakout srategy ith confirmation using TRIX and MACD. Include comprehensive risk management

  2. Assistant

    Certainly! Below is an Expert Advisor (EA) for MetaTrader 5 that implements a Bollinger Bands breakout strategy with confirmation using TRIX and MACD indicators. It includes comprehensive risk management features such as position sizing based on risk percentage, stop loss, take profit, and an optional trailing stop.

    //+------------------------------------------------------------------+
    //|                                                      BB_Trix_Macd |
    //|                                        Developed for MetaTrader 5 |
    //+------------------------------------------------------------------+
    #property copyright ""
    #property version   "1.00"
    #property strict
    
    //--- Input parameters
    input double   RiskPercent       = 2.0;       // Risk per trade (% of account balance)
    input int      Slippage          = 3;         // Maximum slippage in points
    input int      StopLossPips      = 50;        // Stop Loss in pips
    input int      TakeProfitPips    = 100;       // Take Profit in pips
    input bool     UseTrailingStop   = true;      // Enable Trailing Stop
    input int      TrailingStopPips  = 30;        // Trailing Stop distance in pips
    input ulong    MagicNumber       = 123456;    // Magic Number for EA identification
    
    //--- Bollinger Bands parameters
    input int      BB_Period         = 20;        // Bollinger Bands period
    input double   BB_Deviation      = 2.0;       // Bollinger Bands deviation
    
    //--- TRIX parameters
    input int      TRIX_Period       = 14;        // TRIX period
    
    //--- MACD parameters
    input int      MACD_FastEMA      = 12;        // MACD fast EMA period
    input int      MACD_SlowEMA      = 26;        // MACD slow EMA period
    input int      MACD_SignalSMA    = 9;         // MACD signal SMA period
    
    //--- Global variables
    double         BollingerUpper, BollingerLower;
    double         TRIX_Current, TRIX_Previous;
    double         MACD_Main, MACD_Signal;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
      {
       //--- Initialization code can be added here
       return(INIT_SUCCEEDED);
      }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
      {
       //--- Check for a new bar
       static datetime lastBarTime = 0;
       datetime currentBarTime = iTime(_Symbol, _Period, 0);
       if (currentBarTime == lastBarTime)
          return;
       lastBarTime = currentBarTime;
    
       //--- Retrieve indicator values
       GetIndicators();
    
       //--- Check and manage open positions
       ManagePositions();
    
       //--- Check for new trading signals
       if(PositionsTotalByMagic(MagicNumber) == 0)
         {
          CheckForSignals();
         }
      }
    
    //+------------------------------------------------------------------+
    //| Retrieve indicator values                                        |
    //+------------------------------------------------------------------+
    void GetIndicators()
      {
       //--- Bollinger Bands
       BollingerUpper = iBands(_Symbol, _Period, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_UPPER, 1);
       BollingerLower = iBands(_Symbol, _Period, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_LOWER, 1);
    
       //--- TRIX
       TRIX_Current  = iTrix(_Symbol, _Period, TRIX_Period, PRICE_CLOSE, 1);
       TRIX_Previous = iTrix(_Symbol, _Period, TRIX_Period, PRICE_CLOSE, 2);
    
       //--- MACD
       MACD_Main   = iMACD(_Symbol, _Period, MACD_FastEMA, MACD_SlowEMA, MACD_SignalSMA, PRICE_CLOSE, MODE_MAIN, 1);
       MACD_Signal = iMACD(_Symbol, _Period, MACD_FastEMA, MACD_SlowEMA, MACD_SignalSMA, PRICE_CLOSE, MODE_SIGNAL, 1);
      }
    
    //+------------------------------------------------------------------+
    //| Check and manage open positions                                  |
    //+------------------------------------------------------------------+
    void ManagePositions()
      {
       //--- Apply trailing stop if enabled
       if(UseTrailingStop)
         {
          for(int i = PositionsTotal() - 1; i >= 0; i--)
            {
             ulong positionTicket = PositionGetTicket(i);
             if(PositionGetInteger(POSITION_MAGIC) != MagicNumber)
                continue;
    
             double positionPrice = PositionGetDouble(POSITION_PRICE_OPEN);
             ENUM_POSITION_TYPE positionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
             double currentPrice = (positionType == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
             double newSL;
    
             if(positionType == POSITION_TYPE_BUY)
               {
                newSL = currentPrice - TrailingStopPips * _Point;
                if(newSL > PositionGetDouble(POSITION_SL))
                  {
                   ModifyPosition(positionTicket, newSL, PositionGetDouble(POSITION_TP));
                  }
               }
             else if(positionType == POSITION_TYPE_SELL)
               {
                newSL = currentPrice + TrailingStopPips * _Point;
                if(newSL < PositionGetDouble(POSITION_SL))
                  {
                   ModifyPosition(positionTicket, newSL, PositionGetDouble(POSITION_TP));
                  }
               }
            }
         }
      }
    
    //+------------------------------------------------------------------+
    //| Check for buy/sell signals                                       |
    //+------------------------------------------------------------------+
    void CheckForSignals()
      {
       //--- Get the latest closed bar index
       int barIndex = 1;
    
       //--- Buy Signal
       if(Close[barIndex] > BollingerUpper)
         {
          if(TRIX_CrossedAboveZero() && MACD_CrossedAboveSignal())
            {
             double lotSize = CalculateLotSize();
             OpenPosition(ORDER_TYPE_BUY, lotSize);
            }
         }
       //--- Sell Signal
       else if(Close[barIndex] < BollingerLower)
         {
          if(TRIX_CrossedBelowZero() && MACD_CrossedBelowSignal())
            {
             double lotSize = CalculateLotSize();
             OpenPosition(ORDER_TYPE_SELL, lotSize);
            }
         }
      }
    
    //+------------------------------------------------------------------+
    //| Check if TRIX crossed above zero                                 |
    //+------------------------------------------------------------------+
    bool TRIX_CrossedAboveZero()
      {
       return (TRIX_Previous < 0 && TRIX_Current > 0);
      }
    
    //+------------------------------------------------------------------+
    //| Check if TRIX crossed below zero                                 |
    //+------------------------------------------------------------------+
    bool TRIX_CrossedBelowZero()
      {
       return (TRIX_Previous > 0 && TRIX_Current < 0);
      }
    
    //+------------------------------------------------------------------+
    //| Check if MACD main crossed above signal                          |
    //+------------------------------------------------------------------+
    bool MACD_CrossedAboveSignal()
      {
       double macdMainPrev   = iMACD(_Symbol, _Period, MACD_FastEMA, MACD_SlowEMA, MACD_SignalSMA, PRICE_CLOSE, MODE_MAIN, 2);
       double macdSignalPrev = iMACD(_Symbol, _Period, MACD_FastEMA, MACD_SlowEMA, MACD_SignalSMA, PRICE_CLOSE, MODE_SIGNAL, 2);
       return (macdMainPrev < macdSignalPrev && MACD_Main > MACD_Signal);
      }
    
    //+------------------------------------------------------------------+
    //| Check if MACD main crossed below signal                          |
    //+------------------------------------------------------------------+
    bool MACD_CrossedBelowSignal()
      {
       double macdMainPrev   = iMACD(_Symbol, _Period, MACD_FastEMA, MACD_SlowEMA, MACD_SignalSMA, PRICE_CLOSE, MODE_MAIN, 2);
       double macdSignalPrev = iMACD(_Symbol, _Period, MACD_FastEMA, MACD_SlowEMA, MACD_SignalSMA, PRICE_CLOSE, MODE_SIGNAL, 2);
       return (macdMainPrev > macdSignalPrev && MACD_Main < MACD_Signal);
      }
    
    //+------------------------------------------------------------------+
    //| Open a new position                                              |
    //+------------------------------------------------------------------+
    void OpenPosition(ENUM_ORDER_TYPE orderType, double lotSize)
      {
       MqlTradeRequest request;
       MqlTradeResult  result;
       ZeroMemory(request);
       ZeroMemory(result);
    
       request.action   = TRADE_ACTION_DEAL;
       request.magic    = MagicNumber;
       request.symbol   = _Symbol;
       request.volume   = lotSize;
       request.deviation= Slippage;
       request.type     = orderType;
       request.type_filling = ORDER_FILLING_FOK;
       request.comment  = "BB_Trix_Macd EA";
    
       double price, stopLoss, takeProfit;
    
       if(orderType == ORDER_TYPE_BUY)
         {
          price      = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
          stopLoss   = price - StopLossPips * _Point;
          takeProfit = price + TakeProfitPips * _Point;
         }
       else
         {
          price      = SymbolInfoDouble(_Symbol, SYMBOL_BID);
          stopLoss   = price + StopLossPips * _Point;
          takeProfit = price - TakeProfitPips * _Point;
         }
    
       request.price = price;
       request.sl    = NormalizeDouble(stopLoss, _Digits);
       request.tp    = NormalizeDouble(takeProfit, _Digits);
    
       if(!OrderSend(request, result))
         {
          PrintFormat("OrderSend failed with error %d", GetLastError());
         }
       else
         {
          PrintFormat("Order opened successfully. Ticket: %d", result.order);
         }
      }
    
    //+------------------------------------------------------------------+
    //| Modify an existing position                                      |
    //+------------------------------------------------------------------+
    void ModifyPosition(ulong ticket, double newSL, double newTP)
      {
       MqlTradeRequest request;
       MqlTradeResult  result;
       ZeroMemory(request);
       ZeroMemory(result);
    
       request.action   = TRADE_ACTION_SLTP;
       request.position = ticket;
       request.sl       = NormalizeDouble(newSL, _Digits);
       request.tp       = NormalizeDouble(newTP, _Digits);
       request.magic    = MagicNumber;
       request.comment  = "BB_Trix_Macd EA";
    
       if(!OrderSend(request, result))
         {
          PrintFormat("Order modification failed with error %d", GetLastError());
         }
       else
         {
          PrintFormat("Stop Loss modified for position %d", ticket);
         }
      }
    
    //+------------------------------------------------------------------+
    //| Calculate position size based on risk                            |
    //+------------------------------------------------------------------+
    double CalculateLotSize()
      {
       double balance       = AccountInfoDouble(ACCOUNT_BALANCE);
       double riskAmount    = balance * RiskPercent / 100.0;
       double tickValue     = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
       double tickSize      = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
       double contractSize  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
       double stopLossPrice = StopLossPips * _Point;
    
       double lotSize = (riskAmount / (stopLossPrice * (tickValue / tickSize))) * (tickSize / contractSize);
       lotSize = NormalizeDouble(lotSize, 2);
    
       //--- Ensure lot size is within allowed range
       double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
       double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
       double lotStep= SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
    
       if(lotSize < minLot)
          lotSize = minLot;
       if(lotSize > maxLot)
          lotSize = maxLot;
       lotSize = MathFloor(lotSize / lotStep) * lotStep;
    
       return lotSize;
      }
    
    //+------------------------------------------------------------------+
    //| Count total positions with specified Magic Number                |
    //+------------------------------------------------------------------+
    int PositionsTotalByMagic(ulong magic)
      {
       int count = 0;
       for(int i = PositionsTotal()-1; i >= 0; i--)
         {
          if(PositionGetInteger(POSITION_MAGIC, i) == (long)magic)
             count++;
         }
       return count;
      }
    

    Explanation:

    Inputs:

    • RiskPercent: The percentage of your account balance you wish to risk on each trade.
    • Slippage: The maximum price slippage allowed when sending orders.
    • StopLossPips & TakeProfitPips: Stop Loss and Take Profit levels defined in pips.
    • UseTrailingStop & TrailingStopPips: Trailing stop parameters to protect profits.
    • MagicNumber: A unique identifier for the EA's trades, ensuring it manages only its own positions.

    Indicator Parameters:

    • Bollinger Bands:

      • BB_Period and BB_Deviation dictate the calculation of the Bollinger Bands.
      • Upper Band Breakout indicates a potential buy signal.
      • Lower Band Breakout indicates a potential sell signal.
    • TRIX:

      • TRIX_Period defines the period for the TRIX indicator.
      • Zero Line Cross: The signal for TRIX is when it crosses the zero line, confirming momentum in the direction of the breakout.
    • MACD:

      • MACD_FastEMA, MACD_SlowEMA, and MACD_SignalSMA set the parameters for the MACD indicator.
      • Signal Line Cross: A buy signal is generated when the MACD main line crosses above the signal line; a sell signal when it crosses below.

    Functions:

    • OnTick(): The main function that runs on every tick. It checks for a new bar and then proceeds to retrieve indicator values, manage open positions, and check for new trading signals.

    • GetIndicators(): Retrieves and updates the values of the Bollinger Bands, TRIX, and MACD indicators.

    • ManagePositions(): Manages any open positions, applying the trailing stop if it's enabled.

    • CheckForSignals(): Determines if there are any buy or sell signals based on the strategy's criteria.

    • OpenPosition(): Executes a market order based on the calculated lot size and specifies the stop loss and take profit levels.

    • ModifyPosition(): Adjusts the stop loss and take profit levels of an open position, primarily used for updating the trailing stop.

    • CalculateLotSize(): Calculates the lot size for the trade based on the risk percentage, account balance, and the distance to the stop loss.

    • PositionsTotalByMagic(): Counts all open positions that have the EA's magic number, ensuring it only manages its own trades.

    Risk Management:

    • Position Sizing: The EA calculates the lot size based on the specified risk percentage and the monetary value of the stop loss distance.

    • Stop Loss and Take Profit: Set for every trade to define clear exit points.

    • Trailing Stop: An optional feature that moves the stop loss in favor of the trade as the market moves, locking in profits.


    Usage Instructions:

    1. Compile the EA: Copy the code into the MetaEditor, save it with a .mq5 extension, and compile it to ensure there are no errors.

    2. Attach to Chart: In MetaTrader 5, attach the EA to the chart of the desired symbol and timeframe.

    3. Configure Inputs: Adjust the input parameters to suit your trading preferences and risk management rules.

    4. Enable Auto Trading: Ensure that automated trading is enabled in your terminal for the EA to function.

    5. Testing: It's highly recommended to test the EA in the Strategy Tester with historical data to evaluate its performance before using it on a live account.


    Important Notes:

    • Risk Management: Always ensure that your risk settings align with your overall trading plan and risk tolerance.

    • Broker Considerations: Be aware of your broker's trading conditions, such as minimum lot sizes, contract specifications, and allowed trading strategies.

    • Market Conditions: The effectiveness of this strategy may vary under different market conditions. Regularly monitor and adjust the EA's parameters as necessary.

    • Continuous Monitoring: While EAs automate trading, it's important to monitor their performance and make adjustments as needed.


    By integrating the Bollinger Bands breakout strategy with TRIX and MACD confirmations, along with robust risk management, this EA aims to provide a comprehensive tool for automated trading in MetaTrader 5.