//+------------------------------------------------------------------+
//|                                       BB_Cross_EA.mq4           |
//|                        Created by OpenAI - Assistant            |
//|                                                                  |
//+------------------------------------------------------------------+
#property strict

extern double LotSize = 0.1;
extern double Slippage = 3;
extern double StopLossMultiplier = 1; // Multiplier for initial stop loss
extern double TakeProfitMultiplier = 1.5; // Multiplier for take profit
extern double TrailingStop = 20; // Distance in points for trailing stop
extern int Period_BB = 30;
extern double Deviations = 0.8;

// Declare the global variables
bool isBuySignal = false;
bool isSellSignal = false;

//+------------------------------------------------------------------+
//| Expert initialization function                                     |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Initialize the EA
   return (INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                   |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   // Cleanup code can go here.
  }

//+------------------------------------------------------------------+
//| Expert tick function                                              |
//+------------------------------------------------------------------+
void OnTick()
{
    // Update the buy/sell signals based on the Bollinger Bands indicator
    UpdateSignals();
    
    // Execute buy orders if the buy signal is set
    if (isBuySignal)
    {
        double sl = iBands(Symbol(), 0, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_LOWER, 0) - StopLossMultiplier * Point; // set Stop Loss below the lower band
        double tp = Ask + TakeProfitMultiplier * (Ask - sl); // Calculate Take Profit based on the Stop Loss

        // Check if there's already an open buy order
        if (OrderSelect(0, SELECT_BY_POS, MODE_TRADES) == false)
        {
            int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, Slippage, sl, tp, "BB_Cross Buy", 0, 0, clrGreen);
            if (ticket < 0)
                Print("Buy Order Error: ", GetLastError());
        }
    }
    
    // Execute sell orders if the sell signal is set
    if (isSellSignal)
    {
        double sl = iBands(Symbol(), 0, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_UPPER, 0) + StopLossMultiplier * Point; // set Stop Loss above the upper band
        double tp = Bid - TakeProfitMultiplier * (sl - Bid); // Calculate Take Profit based on the Stop Loss

        // Check if there's already an open sell order
        if (OrderSelect(0, SELECT_BY_POS, MODE_TRADES) == false)
        {
            int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, Slippage, sl, tp, "BB_Cross Sell", 0, 0, clrRed);
            if (ticket < 0)
                Print("Sell Order Error: ", GetLastError());
        }
    }

    // Manage existing orders
    ManageOpenOrders();
}

//+------------------------------------------------------------------+
//| Function to manage open orders with trailing stop                 |
//+------------------------------------------------------------------+
void ManageOpenOrders()
  {
   double trailingStopPrice;
   // Loop through all open orders
   for (int i = OrdersTotal() - 1; i >= 0; i--)
     {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && (OrderSymbol() == Symbol()))
        {
         // For Buy orders
         if (OrderType() == OP_BUY)
           {
            trailingStopPrice = OrderOpenPrice() + TrailingStop * Point;

            // If current price exceeds the trailing stop price, we can update the stop loss
            if (Bid > trailingStopPrice)
              {
               double newStopLoss = Bid - StopLossMultiplier * Point;
               if (newStopLoss > OrderStopLoss()) // Only update if the new stop loss is higher
                 {
                  if (OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrGreen) == false)
                     Print("Error in modifying Buy order: ", GetLastError());
                 }
              }
           }
         
         // For Sell orders
         if (OrderType() == OP_SELL)
           {
            trailingStopPrice = OrderOpenPrice() - TrailingStop * Point;

            // If current price falls below the trailing stop price, we can update the stop loss
            if (Ask < trailingStopPrice)
              {
               double newStopLoss = Ask + StopLossMultiplier * Point;
               if (newStopLoss < OrderStopLoss()) // Only update if the new stop loss is lower
                 {
                  if (OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrRed) == false)
                     Print("Error in modifying Sell order: ", GetLastError());
                 }
              }
           }
        }
     }
  }

//+------------------------------------------------------------------+
//| Function to update buy/sell signals                               |
//+------------------------------------------------------------------+
void UpdateSignals()
{
    double upperBand = iBands(Symbol(), 0, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_UPPER, 1); // shift set to 1 for last closed candle
    double lowerBand = iBands(Symbol(), 0, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_LOWER, 1); // shift set to 1 for last closed candle

    double closePrice = Close[1]; // Current close price (previous candle)
    double closePricePrev = Close[2]; // Previous close price (before that)

    // Check for Buy signal
    if (closePrice > upperBand && closePricePrev < upperBand)
    {
        isBuySignal = true;
        isSellSignal = false; // Reset sell signal
    }
    else
        isBuySignal = false;

    // Check for Sell signal
    if (closePrice < lowerBand && closePricePrev > lowerBand)
    {
        isSellSignal = true;
        isBuySignal = false; // Reset buy signal
    }
    else
        isSellSignal = false;
}
//+------------------------------------------------------------------+

make tailing stop loss value as upper or lower band