Delta Envelope Project (Non-Repaint) MetaTrader 4 Expert Advisor

The Delta Envelope Project (Non-Repaint) is an Expert Advisor that utilizes the Envelopes indicator to automate trading decisions. This EA generates buy and sell signals based on the position of price relative to the Envelopes’ upper and lower bands. By following predefined rules, it executes trades with consistent risk management, ensuring that the process remains systematic and free from emotional biases.

#property strict
#define buy 2
#define sell -2

//+------------------------------------------------------------------+
//| Expert inputs - Define the main settings for the EA               |
//+------------------------------------------------------------------+
extern string __Afx1 = "------open for buy sell trades----------------------------";
input bool   CloseBySignal = True;    // Close trades by signal
input bool   OpenBUY       = True;    // Enable buying
input bool   OpenSELL      = True;    // Enable selling

input string Indicator1 = "==Envelopes Indicator settings==";
extern bool  use_Envolop = true;      // Enable Envelopes indicator usage
input int    I_Period    = 25;        // Envelopes period
input double I_Deviation = 0.35;      // Envelopes deviation

extern string __Afx3 = "-----------trade settings-----------------------";
input double LotSize      = 0.1;      // Lot size
input double StopLoss     = 0;        // Stop loss level (in pips)
input double TakeProfit   = 0;        // Take profit level (in pips)
input double TrailingStop = 0;        // Trailing stop level (in pips)
input int    MagicNumber  = 122354;   // Magic number for order management
input int    Slippage     = 10;       // Maximum allowed slippage
input string comment      = "AFX ENVO";// Order comment

//+------------------------------------------------------------------+
//| Variables declaration                                            |
//+------------------------------------------------------------------+
datetime dt;                          // Stores the last bar time
const double F_away = 0.000001;       // Offset for price comparison
int OrderBuy, OrderSell;              // Number of open buy/sell orders
int ticket;                           // Order ticket
int LotDigits;                        // Number of digits in the lot size
double Trail, iTrailingStop;          // Trailing stop variables

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Initialization logic, if any, goes here
   
   return(INIT_SUCCEEDED);  // Successful initialization
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   // Cleanup code, if any, goes here
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
int start()
  {  
   double stoplevel = MarketInfo(Symbol(), MODE_STOPLEVEL);  // Get the stop level for the symbol
   OrderBuy = 0;
   OrderSell = 0;
   
   // Loop through all open orders
   for (int cnt = 0; cnt < OrdersTotal(); cnt++)
    {
     if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
      {
       if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber && OrderComment() == comment)
        {
         if (OrderType() == OP_BUY) OrderBuy++;   // Count open buy orders
         if (OrderType() == OP_SELL) OrderSell++; // Count open sell orders

         // Trailing stop logic
         if (TrailingStop > 0)
          {
           iTrailingStop = TrailingStop;
           if (TrailingStop < stoplevel) iTrailingStop = stoplevel;
           Trail = iTrailingStop * Point;
           double tsbuy = NormalizeDouble(Bid - Trail, Digits);
           double tssell = NormalizeDouble(Ask + Trail, Digits);

           // Modify orders with new stop loss levels
           if (OrderType() == OP_BUY && Bid - OrderOpenPrice() > Trail && Bid - OrderStopLoss() > Trail)
              ticket = OrderModify(OrderTicket(), OrderOpenPrice(), tsbuy, OrderTakeProfit(), 0, Blue);

           if (OrderType() == OP_SELL && OrderOpenPrice() - Ask > Trail && (OrderStopLoss() - Ask > Trail || OrderStopLoss() == 0))
              ticket = OrderModify(OrderTicket(), OrderOpenPrice(), tssell, OrderTakeProfit(), 0, Blue);
          }
        }
      }
    }

   if (isnewbar())
    {
     // Open position if conditions match
     if (OpenSELL && OrderSell < 1 && signal() == sell) OPSELL();
     if (OpenBUY && OrderBuy < 1 && signal() == buy) OPBUY();

     // Close position by signal
     if (CloseBySignal)
      {
       if (OrderBuy > 0 && signal() == sell) CloseBuy();
       if (OrderSell > 0 && signal() == buy) CloseSell();
      }
    }
    
   return(0);  // Return 0 to indicate successful execution
  }
//+------------------------------------------------------------------+
//| Function to open a Buy order                                     |
//+------------------------------------------------------------------+
void OPBUY()
  {
   double StopLossLevel;
   double TakeProfitLevel;

   // Calculate the stop loss and take profit levels based on input values
   if(StopLoss > 0) StopLossLevel = Bid - StopLoss * Point; else StopLossLevel = 0.0;
   if(TakeProfit > 0) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel = 0.0;

   // Send a buy order with the calculated stop loss and take profit levels
   ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, Slippage, StopLossLevel, TakeProfitLevel, comment, MagicNumber, 0, Blue);
  }
//+------------------------------------------------------------------+
//| Function to open a Sell order                                    |
//+------------------------------------------------------------------+
void OPSELL()
  {
   double StopLossLevel;
   double TakeProfitLevel;

   // Calculate the stop loss and take profit levels based on input values
   if(StopLoss > 0) StopLossLevel = Ask + StopLoss * Point; else StopLossLevel = 0.0;
   if(TakeProfit > 0) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel = 0.0;

   // Send a sell order with the calculated stop loss and take profit levels
   ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, Slippage, StopLossLevel, TakeProfitLevel, comment, MagicNumber, 0, Red);
  }
//+------------------------------------------------------------------+
//| Function to close all Buy orders                                 |
//+------------------------------------------------------------------+
void CloseBuy()
  {
   int total = OrdersTotal();  // Get the total number of orders

   // Iterate over all orders starting from the most recent one
   for(int y = OrdersTotal() - 1; y >= 0; y--)
    { 
     if (OrderSelect(y, SELECT_BY_POS, MODE_TRADES))  // Select an order by its position
      {
       // Check if the order is a BUY order for the specified symbol and magic number
       if (OrderSymbol() == Symbol() && OrderType() == OP_BUY && OrderMagicNumber() == MagicNumber)
        {
         ticket = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, Black);
        }
      }
    }
  }
//+------------------------------------------------------------------+
//| Function to close all Sell orders                                |
//+------------------------------------------------------------------+
void CloseSell()
  {
   int total = OrdersTotal();  // Get the total number of orders

   // Iterate over all orders starting from the most recent one
   for(int y = OrdersTotal() - 1; y >= 0; y--)
    {
     if (OrderSelect(y, SELECT_BY_POS, MODE_TRADES))  // Select an order by its position
      {
       // Check if the order is a SELL order for the specified symbol and magic number
       if (OrderSymbol() == Symbol() && OrderType() == OP_SELL && OrderMagicNumber() == MagicNumber)
        {
         ticket = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, Black);
        }
      }
    }
  }
//+------------------------------------------------------------------+
//| Function to check if a new bar has formed                        |
//+------------------------------------------------------------------+
bool isnewbar()
  {
   if (Time[0] != dt)
    {
     dt = Time[0];
     return(true);  // New bar detected
    }
   return(false);   // No new bar
  }  
//+------------------------------------------------------------------+
//| Function to generate a trading signal based on Envelopes         |
//+------------------------------------------------------------------+
int signal()
  {
   double I_UPBand  = iEnvelopes(NULL, 0, I_Period, MODE_SMA, 0, PRICE_CLOSE, I_Deviation, MODE_UPPER, 1);
   double I_LOBand  = iEnvelopes(NULL, 0, I_Period, MODE_SMA, 0, PRICE_CLOSE, I_Deviation, MODE_LOWER, 1);
   double I_UPBand1 = iEnvelopes(NULL, 0, I_Period, MODE_SMA, 0, PRICE_CLOSE, I_Deviation, MODE_UPPER, 2);
   double I_LOBand1 = iEnvelopes(NULL, 0, I_Period, MODE_SMA, 0, PRICE_CLOSE, I_Deviation, MODE_LOWER, 2);
   
   // Check if the Envelopes indicator is enabled
   if (use_Envolop)
    {
     // Generate buy signal
     if (Open(0) < I_LOBand - F_away && Open(1) > I_LOBand1 + F_away) return(buy);
     
     // Generate sell signal
     if (Open(0) > I_UPBand + F_away && Open(1) < I_UPBand1 - F_away) return(sell);
    } 
   return(0);  // No signal
  }
//+------------------------------------------------------------------+
//| Function to get the opening price of a specific bar              |
//+------------------------------------------------------------------+
double Open(int bar)
  {
   return(Open[bar]);
  }
//+------------------------------------------------------------------+

What is the Envelopes Indicator?

The Envelopes indicator is a trend-following tool that plots two lines above and below a moving average. These lines are typically set at a certain percentage distance from the moving average, which helps identify overbought and oversold conditions in the market.

  • Upper Band: This is the line plotted above the moving average. It suggests a potential overbought condition when the price moves close to or above this band.
  • Lower Band: This line is plotted below the moving average. It indicates a potential oversold condition when the price moves close to or below this band.
See also  Alixa SSL + ATR Band (Non-Repaint) MetaTrader 4 Indicator

The idea behind using the Envelopes indicator is to identify points where the price has deviated significantly from the average, potentially indicating a reversal or continuation of the trend.

How This EA Uses the Envelopes Indicator

The EA is built around the signals generated by the Envelopes indicator. Here’s how it works:

Signal Generation

The EA generates a buy signal when the price opens below the Lower Band and the previous bar’s opening price was above the previous Lower Band. This suggests that the market may have been oversold and could be preparing for an upward movement.

Conversely, a sell signal is generated when the price opens above the Upper Band and the previous bar’s opening price was below the previous Upper Band. This condition implies that the market may have been overbought and could be heading downward.

Trade Execution

Once the EA detects a valid signal based on the conditions above, it proceeds to open a buy or sell position. The trade size, stop loss, take profit, and trailing stop levels are all predefined, ensuring that each trade is executed with consistent risk management.

  • Buy Orders: These are triggered when a buy signal is generated, with stop loss and take profit levels set according to the input parameters.
  • Sell Orders: Similarly, sell orders are triggered when a sell signal is detected, again with predefined stop loss and take profit levels.

Trailing Stop Feature

The EA includes a trailing stop mechanism, which adjusts the stop loss level as the trade becomes more profitable. This feature is crucial for locking in profits and minimizing risk, particularly in volatile markets.

See also  Boom Limit Pro v1.0 (Non-Repaint) MetaTrader 4 Expert Advisor

Key Features and Limitations of the EA

Non-Repaint and Non-Lagging Behavior

This EA is non-repaint and non-lagging, meaning it does not alter past signals, and the signals generated are based on the latest market data without delay. This is important for maintaining the integrity and reliability of the trading signals.

Recalculation Issue

However, it’s essential to note that the EA does recalculate signals as new price data comes in. This means that while the signals are accurate and timely, they can change slightly as the market progresses, which might affect the consistency of trading decisions. To address this, traders could consider implementing a mechanism to lock in signals at the close of each bar, which would prevent recalculation and make the signals more stable.

Risk Management and Trade Settings

The EA provides several adjustable parameters for managing risk and customizing trade settings:

  • Lot Size: Defines the volume of each trade.
  • Stop Loss: Sets the maximum loss threshold, protecting the account from large, unexpected market movements.
  • Take Profit: Determines the target profit level, allowing the EA to close positions automatically once the market reaches a favorable price.
  • Trailing Stop: Adjusts the stop loss as the trade moves in a profitable direction, ensuring profits are secured.

Final Thoughts

This Envelopes-based EA offers a structured and methodical approach to trading, leveraging a widely recognized indicator to make trading decisions. By automating the process, the EA can help remove emotional biases and ensure that trading strategies are executed consistently.

However, it’s important to understand the EA’s strengths and limitations, particularly its recalculation behavior, to use it effectively in your trading strategy. As always, thorough testing and customization are key to ensuring that the EA aligns with your specific trading goals and risk tolerance.

See also  Xenith Stochastic V1.3 (Non-Repaint) MetaTrader 5 Expert Advisor

Leave a Comment