Author: Copyright � 2005, MetaQuotes Software Corp.
Profit factor:
564.32

This automated trading script is designed to manage and execute trades based on moving average trends and volatility boundaries. It utilizes a combination of technical indicators to identify entry points, manage risk dynamically, and adjust trade parameters in real-time.

Core Trading Strategy

The logic revolves around three primary components:

  • Moving Average (MA): Used as the baseline to determine the current trend direction.
  • Envelopes: These act as dynamic "boundaries" above and below the moving average. They help the script identify price extremes and specific zones for placing orders.
  • Price Positioning: The script monitors where the current market price sits in relation to these boundaries and the moving average to decide whether to initiate "Buy Stop" or "Sell Stop" orders.

Order Execution and Management

The script is capable of managing up to eight distinct positions (four for buying and four for selling) simultaneously.

  • Entry Logic: It places pending orders at specific price points calculated from the moving average. For example, it looks for opportunities where the price is currently below a certain level but potentially trending upward into a "Buy" zone, or vice versa for selling.
  • Tiered Take Profits: For the first three positions in any direction, the script assigns different profit targets. This allows the system to "scale out" of a position—taking partial profits at multiple levels rather than closing everything at once. The fourth position in each direction is designed without a fixed take-profit, allowing it to run for longer potential gains.
  • Dynamic Stop Loss (Trailing): Once a trade is active, the script actively monitors the price. It automatically moves the stop loss as the price moves in your favor. It uses the moving average and envelope boundaries to "trail" these stops, aiming to protect profits while giving the trade room to breathe.

Risk Management Features

A significant portion of the logic is dedicated to protecting the account balance:

  • Automated Lot Sizing: The script calculates the appropriate trade size based on a fixed percentage of your available account margin. This ensures that every trade is proportional to your current capital.
  • Loss Recovery Adjustment: The system includes an "intelligent" reduction mechanism. If the script detects a streak of losing trades in its history, it automatically scales down the lot sizes for subsequent trades. This "Decrease Factor" helps prevent heavy losses during periods of poor market conditions or high volatility.
  • Market Synchronization: The logic accounts for the "spread" (the difference between the buy and sell price) to ensure that orders are placed at realistic, executable prices.
Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategy
Indicators Used
Moving average indicatorEnvelopes indicator
17 Views
0 Downloads
0 Favorites
e.2.21
/*-----------------------------+
|			       |
| Shared by www.Aptrafx.com    |
|			       |
+------------------------------*/

//+------------------------------------------------------------------+
//|                                                 e.2.21 5 min.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, tageiger aka fxid10t@yahoo.com"
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link      "fxid10t@yahoo.com"
#property link      "http://finance.groups.yahoo.com/group/MetaTrader_Experts_and_Indicators/join"

//---- input parameters
extern int        EnvelopePeriod    =144;//ma bars
extern int        EnvTimeFrame      =1; //envelope time frame: 0=chart,60=1hr,240=4hr, etc.
extern int        EnvMaMethod       =1; //0=sma,1=ema,2=smma,3=lwma.
extern double     EnvelopeDeviation =0.1;//%shift above & below ma 
//extern int        TimeOpen          =0;//time order placement can begin
//extern int        TimeClose         =23;//open order deletion time
extern double     FirstTP           =8.0;
extern double     SecondTP          =13.0;
extern double     ThirdTP           =21.0;
extern double     Lots              =0.1;//initial lot size
extern double     MaximumRisk       =0.02;//percentage of account to risk each order
extern double     DecreaseFactor    =3;//lot size reducer during losing streak

int               b1,b2,b3,b4,s1,s2,s3,s4;
double            TSL               =0;

double LotsOptimized()  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
   if(DecreaseFactor>0) {
      for(int i=orders-1;i>=0;i--)  {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
         }
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
      }
   if(lot<0.1) lot=0.1;//  <<<---IBFX MINI MODIFICATION
   return(lot);
   }

int init()  {   return(0);  }

int deinit()  {   return(0);  }

int start() {
   int      p=0;     p=EnvelopePeriod;
   int      etf=0;   etf=EnvTimeFrame;
   int      mam=0;   mam=EnvMaMethod;
   double   d=0;     d=EnvelopeDeviation;
   double   btp1,btp2,btp3,stp1,stp2,stp3,bsl,ssl,buy,sell;
   double   bline=0,sline=0,ma=0,spread,eup,edown;
   int      cnt, ticket, total;
   double   digit; digit=MarketInfo(Symbol(),MODE_DIGITS);

   ma=iMA(NULL,etf,p,0,mam,PRICE_CLOSE,0);
   bline=iEnvelopes(NULL,etf,p,mam,0,PRICE_CLOSE,d,MODE_UPPER,0);
   sline=iEnvelopes(NULL,etf,p,mam,0,PRICE_CLOSE,d,MODE_LOWER,0);
   spread=Ask-Bid;
   
   buy=NormalizeDouble(ma,digit)+spread;
   bsl=NormalizeDouble(sline,digit);
   sell=NormalizeDouble(ma,digit);   
   ssl=NormalizeDouble(bline,digit)+spread;

      
   total=OrdersTotal();
   if(OrdersTotal()==0) {  b1=0;b2=0;b3=0;b4=0;s1=0;s2=0;s3=0;s4=0;   }
   if(OrdersTotal()>0)  {
      for(cnt=0;cnt<total;cnt++) {
         OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
         if(OrderMagicNumber()==2)  {  b1=OrderTicket(); }
         if(OrderMagicNumber()==4)  {  b2=OrderTicket(); }
         if(OrderMagicNumber()==6)  {  b3=OrderTicket(); }
         if(OrderMagicNumber()==8)  {  b4=OrderTicket(); }
         if(OrderMagicNumber()==1)  {  s1=OrderTicket(); }
         if(OrderMagicNumber()==3)  {  s2=OrderTicket(); }
         if(OrderMagicNumber()==5)  {  s3=OrderTicket(); }
         if(OrderMagicNumber()==7)  {  s4=OrderTicket(); }
         }
      }

   if(b1==0)   {  
      //if(Hour()>TimeOpen && Hour()<TimeClose)   {
         if(Bid<buy && Bid>sline)   {
            btp1=buy+(FirstTP*Point);
            ticket=OrderSend(Symbol(),
                              OP_BUYSTOP,
                              LotsOptimized(),
                              buy,
                              0,
                              bsl,
                              btp1,
                              "e.2.21 b1",
                              2,
                              0,
                              Aqua);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  b1=ticket;  Print(ticket); }
                                 else Print("Error Opening BuyStop Order: ",GetLastError());
                                 return(0);
                                 }
            }
         //}
      }         

   if(b2==0)   {
      //if(Hour()>TimeOpen && Hour()<TimeClose)   {
         if(Bid<buy && Bid>sline)   {      
            btp2=buy+(SecondTP*Point);
            ticket=OrderSend(Symbol(),
                              OP_BUYSTOP,
                              LotsOptimized(),
                              buy,
                              0,
                              bsl,
                              btp2,
                              "e.2.21 b2",
                              4,
                              0,
                              Aqua);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))  
                                    {  b2=ticket;  Print(ticket); }
                                 else Print("Error Opening BuyStop Order: ",GetLastError());
                                 return(0);
                                 }
            }
         //}
      }                              

   if(b3==0)   {
      //if(Hour()>TimeOpen && Hour()<TimeClose)   {
         if(Bid<buy && Bid>sline)   {      
            btp3=buy+(ThirdTP*Point);
            ticket=OrderSend(Symbol(),
                              OP_BUYSTOP,
                              LotsOptimized(),
                              buy,
                              0,
                              bsl,
                              btp3,
                              "e.2.21 b3",
                              6,
                              0,
                              Aqua);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  b3=ticket;  Print(ticket); }
                                 else Print("Error Opening BuyStop Order: ",GetLastError());
                                 return(0);
                                 }
            }
         //}
      }                     

   if(b4==0)   {
      //if(Hour()>TimeOpen && Hour()<TimeClose)   {
         if(Bid<buy && Bid>sline)   {      
            ticket=OrderSend(Symbol(),
                              OP_BUYSTOP,
                              LotsOptimized(),
                              buy,
                              0,
                              bsl,
                              0,
                              "e.2.21 b4",
                              8,
                              0,
                              Aqua);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  b4=ticket;  Print(ticket); }
                                 else Print("Error Opening BuyStop Order: ",GetLastError());
                                 return(0);
                                 }
            }
        //}
      }
   
   if(s1==0)   {
      //if(Hour()>TimeOpen && Hour()<TimeClose)   {
         if(Bid>ma && Bid<ssl)   {      
            stp1=sell-(FirstTP*Point);
            ticket=OrderSend(Symbol(),
                              OP_SELLSTOP,
                              LotsOptimized(),
                              sell,
                              0,
                              ssl,
                              stp1,
                              "e.2.21 s1",
                              1,
                              0,
                              HotPink);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  s1=ticket;  Print(ticket); }
                                 else Print("Error Opening SellStop Order: ",GetLastError());
                                 return(0);
                                 }
            }
        // }
      }

   if(s2==0)   {
      //if(Hour()>TimeOpen && Hour()<TimeClose)   {
         if(Bid>ma && Bid<ssl)   {      
            stp2=sell-(SecondTP*Point);
            ticket=OrderSend(Symbol(),
                              OP_SELLSTOP,
                              LotsOptimized(),
                              sell,
                              0,
                              ssl,
                              stp2,
                              "e.2.21 s2",
                              3,
                              0,
                              HotPink);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  s2=ticket;  Print(ticket); }
                                 else Print("Error Opening SellStop Order: ",GetLastError());
                                 return(0);
                                 }
            }
         //}
      }                     
   
   if(s3==0)   {
      //if(Hour()>TimeOpen && Hour()<TimeClose)   {
         if(Bid>ma && Bid<ssl)   {      
            stp3=sell-(ThirdTP*Point);
            ticket=OrderSend(Symbol(),
                              OP_SELLSTOP,
                              LotsOptimized(),
                              sell,
                              0,
                              ssl,
                              stp3,
                              "e.2.21 s3",
                              5,
                              0,
                              HotPink);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  s3=ticket;  Print(ticket); }
                                 else Print("Error Opening SellStop Order: ",GetLastError());
                                 return(0);
                                 }
            }
        // }
      }

   if(s4==0)   {
      //if(Hour()>TimeOpen && Hour()<TimeClose)   {
         if(Bid>ma && Bid<ssl)   {      
            ticket=OrderSend(Symbol(),
                              OP_SELLSTOP,
                              LotsOptimized(),
                              sell,
                              0,
                              ssl,
                              0,
                              "e.2.21 s4",
                              7,
                              0,
                              HotPink);
                              if(ticket>0)   {
                                 if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                                    {  s4=ticket;  Print(ticket); }
                                 else Print("Error Opening SellStop Order: ",GetLastError());
                                 return(0);
                                 }
            }
        // }
      }
   
   for(cnt=0;cnt<total;cnt++) {

      ma=iMA(NULL,etf,p,0,mam,PRICE_CLOSE,0);
      bline=iEnvelopes(NULL,etf,p,mam,0,PRICE_CLOSE,d,MODE_UPPER,0);
      sline=iEnvelopes(NULL,etf,p,mam,0,PRICE_CLOSE,d,MODE_LOWER,0);
      spread=Ask-Bid;

      buy=NormalizeDouble(ma,digit)+spread;
      bsl=NormalizeDouble(sline,digit);
      sell=NormalizeDouble(ma,digit);   
      ssl=NormalizeDouble(bline,digit)+spread;

      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);            
      if(OrderType()==OP_BUY) {
         if(Bid>OrderOpenPrice())   {
            TSL=NormalizeDouble(sline,digit);
            if(TSL>OrderStopLoss()) {
               bsl=TSL;
               OrderModify(OrderTicket(),
                           OrderOpenPrice(),
                           bsl,
                           OrderTakeProfit(),
                           0,//Order expiration server date/time
                           Green);
                           return;  }  }
         if(Bid>bline)  {
            TSL=NormalizeDouble(ma,digit);
            if(TSL>OrderStopLoss()) {
               bsl=TSL;
               OrderModify(OrderTicket(),
                           OrderOpenPrice(),
                           bsl,
                           OrderTakeProfit(),
                           0,//Order expiration server date/time
                           Green);
                           return;  }  } 
         }

      if(OrderType()==OP_SELL)   {
         if(Ask<OrderOpenPrice())   {
            TSL=NormalizeDouble(bline,digit)+spread;
            if(TSL<OrderStopLoss()) {
               ssl=TSL;
               OrderModify(OrderTicket(),
                           OrderOpenPrice(),
                           ssl,
                           OrderTakeProfit(),
                           0,//Order expiration server date/time
                           Red);
                           return;  }  }
         if(Bid<sline)  {
            TSL=NormalizeDouble(ma,digit)+spread;
            if(TSL<OrderStopLoss()) {
               ssl=TSL;
               OrderModify(OrderTicket(),
                           OrderOpenPrice(),
                           ssl,
                           OrderTakeProfit(),
                           0,//Order expiration server date/time
                           Red);
                           return;  }  }
         }

      if(OrderType()==OP_BUYSTOP)  {
         if(OrderOpenPrice()!=MathAbs(buy) &&
            (OrderOpenPrice()-Ask)>=spread)  {
            if(OrderTicket()==b1)   {
               btp1=buy+(FirstTP*Point);
               OrderModify(OrderTicket(),
                           buy,
                           bsl,
                           btp1,
                           0,
                           LimeGreen);
                           }
            if(OrderTicket()==b2)   {
               btp2=buy+(SecondTP*Point);
               OrderModify(OrderTicket(),
                           buy,
                           bsl,
                           btp2,
                           0,
                           LimeGreen);
                           }
            if(OrderTicket()==b3)   {
               btp3=buy+(ThirdTP*Point);
               OrderModify(OrderTicket(),
                           buy,
                           bsl,
                           btp3,
                           0,
                           LimeGreen);
                           }
            if(OrderTicket()==b4)   {
               OrderModify(OrderTicket(),
                           buy,
                           bsl,
                           0,
                           0,
                           LimeGreen);
                           }
            }
         }
      if(OrderType()==OP_SELLSTOP) {
         if(OrderOpenPrice()!=MathAbs(sell) &&
            (Bid-OrderOpenPrice())>=spread)  {                  
            if(OrderTicket()==s1)   {
               stp1=sell-(FirstTP*Point);
               OrderModify(OrderTicket(),
                           sell,
                           ssl,
                           stp1,
                           0,
                           HotPink);
                           }
            if(OrderTicket()==s2)   {
               stp2=(NormalizeDouble(ma,digit))-(SecondTP*Point);
               OrderModify(OrderTicket(),
                           sell,
                           ssl,
                           stp2,
                           0,
                           HotPink);
                           }
            if(OrderTicket()==s3)   {
               stp3=sell-(ThirdTP*Point);
               OrderModify(OrderTicket(),
                           sell,
                           ssl,
                           stp3,
                           0,
                           HotPink);
                           }
            if(OrderTicket()==s4)   {
               OrderModify(OrderTicket(),
                           sell,
                           ssl,
                           0,
                           0,
                           HotPink);
                           }
         }
      }
/*      
      if(Hour()==TimeClose && OrderType()==OP_BUYSTOP)  {
         OrderDelete(OrderTicket());
         if(OrderTicket()==b1) {b1=0; return;}
         if(OrderTicket()==b2) {b2=0; return;}
         if(OrderTicket()==b3) {b3=0; return;}
         if(OrderTicket()==b4) {b4=0; return;}                   
         }
      if(Hour()==TimeClose && OrderType()==OP_SELLSTOP)  {
         OrderDelete(OrderTicket());
         if(OrderTicket()==s1) {s1=0; return;}
         if(OrderTicket()==s2) {s2=0; return;}
         if(OrderTicket()==s3) {s3=0; return;}
         if(OrderTicket()==s4) {s4=0; return;}
         }*/
      OrderSelect(b1,SELECT_BY_TICKET);
      if(OrderCloseTime()>0) {b1=0;}
      OrderSelect(b2,SELECT_BY_TICKET);
      if(OrderCloseTime()>0) {b2=0;}
      OrderSelect(b3,SELECT_BY_TICKET);
      if(OrderCloseTime()>0) {b3=0;}
      OrderSelect(b4,SELECT_BY_TICKET);
      if(OrderCloseTime()>0) {b4=0;}
      OrderSelect(s1,SELECT_BY_TICKET);
      if(OrderCloseTime()>0) {s1=0;}
      OrderSelect(s2,SELECT_BY_TICKET);
      if(OrderCloseTime()>0) {s2=0;}     
      OrderSelect(s3,SELECT_BY_TICKET);
      if(OrderCloseTime()>0) {s3=0;}
      OrderSelect(s4,SELECT_BY_TICKET);
      if(OrderCloseTime()>0) {s4=0;}
      }
   return(0);
   }

  

Profitability Reports

EUR/USD Jul 2025 - Sep 2025
8459.69
Total Trades 871
Won Trades 694
Lost trades 177
Win Rate 79.68 %
Expected payoff 34132.89
Gross Profit 29733258.80
Gross Loss -3514.70
Total Net Profit 29729744.10
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
0.64
Total Trades 482
Won Trades 391
Lost trades 91
Win Rate 81.12 %
Expected payoff -1.45
Gross Profit 1263.80
Gross Loss -1961.10
Total Net Profit -697.30
-100%
-50%
0%
50%
100%
AUD/USD Oct 2025 - Feb 2026
0.58
Total Trades 1049
Won Trades 674
Lost trades 375
Win Rate 64.25 %
Expected payoff -1.48
Gross Profit 2193.10
Gross Loss -3748.90
Total Net Profit -1555.80
-100%
-50%
0%
50%
100%
USD/JPY Jul 2025 - Sep 2025
0.57
Total Trades 566
Won Trades 440
Lost trades 126
Win Rate 77.74 %
Expected payoff -1.56
Gross Profit 1174.77
Gross Loss -2055.17
Total Net Profit -880.40
-100%
-50%
0%
50%
100%
GBP/USD Jul 2025 - Sep 2025
0.52
Total Trades 495
Won Trades 377
Lost trades 118
Win Rate 76.16 %
Expected payoff -2.78
Gross Profit 1514.80
Gross Loss -2888.50
Total Net Profit -1373.70
-100%
-50%
0%
50%
100%
NZD/USD Jul 2025 - Sep 2025
0.44
Total Trades 853
Won Trades 517
Lost trades 336
Win Rate 60.61 %
Expected payoff -2.08
Gross Profit 1420.30
Gross Loss -3194.20
Total Net Profit -1773.90
-100%
-50%
0%
50%
100%
USD/CHF Jul 2025 - Sep 2025
0.42
Total Trades 317
Won Trades 182
Lost trades 135
Win Rate 57.41 %
Expected payoff -3.36
Gross Profit 776.88
Gross Loss -1842.48
Total Net Profit -1065.60
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.41
Total Trades 613
Won Trades 375
Lost trades 238
Win Rate 61.17 %
Expected payoff -2.08
Gross Profit 888.60
Gross Loss -2164.60
Total Net Profit -1276.00
-100%
-50%
0%
50%
100%
GBP/AUD Oct 2025 - Feb 2026
0.40
Total Trades 2075
Won Trades 1531
Lost trades 544
Win Rate 73.78 %
Expected payoff -2.98
Gross Profit 4097.19
Gross Loss -10280.95
Total Net Profit -6183.76
-100%
-50%
0%
50%
100%
AUD/USD Oct 2024 - Jan 2025
0.38
Total Trades 266
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -3.15
Gross Profit 504.30
Gross Loss -1343.50
Total Net Profit -839.20
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
0.29
Total Trades 242
Won Trades 114
Lost trades 128
Win Rate 47.11 %
Expected payoff -5.24
Gross Profit 507.00
Gross Loss -1773.90
Total Net Profit -1266.90
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.27
Total Trades 3239
Won Trades 2413
Lost trades 826
Win Rate 74.50 %
Expected payoff -3.04
Gross Profit 3705.39
Gross Loss -13556.51
Total Net Profit -9851.12
-100%
-50%
0%
50%
100%
GBP/CAD Oct 2025 - Feb 2026
0.16
Total Trades 822
Won Trades 495
Lost trades 327
Win Rate 60.22 %
Expected payoff -6.00
Gross Profit 941.86
Gross Loss -5873.42
Total Net Profit -4931.56
-100%
-50%
0%
50%
100%
GBP/CAD Jul 2025 - Sep 2025
0.08
Total Trades 410
Won Trades 202
Lost trades 208
Win Rate 49.27 %
Expected payoff -11.36
Gross Profit 384.95
Gross Loss -5042.87
Total Net Profit -4657.92
-100%
-50%
0%
50%
100%
USD/CAD Oct 2024 - Jan 2025
0.00
Total Trades 0
Won Trades 0
Lost trades 0
Win Rate 0.0 %
Expected payoff 0.00
Gross Profit 0.00
Gross Loss 0.00
Total Net Profit 0.00
-100%
-50%
0%
50%
100%

Comments