Expert Template for MT 4

Download script
Profit factor:
0.00

This automated trading script is designed to manage and execute trades on specific currency pairs (EURUSD, GBPUSD, USDCHF, and USDJPY) by analyzing a variety of technical indicators. It follows a strict set of rules to decide when to enter a trade, how to manage the risk, and how to protect profits.

Core Trading Logic

The script continuously monitors market data and looks for specific "confluence" — which means multiple different indicators must agree before a trade is placed.

For Buy (Long) Positions: To open a buy trade, the script requires several conditions to be met simultaneously:

  • Trend Confirmation: The price must be trading above major moving averages (specifically the 200 and 288 periods), indicating an upward trend.
  • Momentum: The MACD indicator must show positive movement and exceed a specific threshold.
  • Oscillator Strength: The RSI (Relative Strength Index) must be trending upwards and stay above a certain level.
  • Specific Price Action: It checks that the current price is higher than previous averages and follows specific mathematical thresholds.

For Sell (Short) Positions: To open a sell trade, the script looks for the opposite signals:

  • Trend Confirmation: The price must be trading below the major moving averages.
  • Momentum: The MACD must show negative movement and exceed its threshold.
  • Oscillator Strength: The Stochastic Oscillator and RSI must indicate downward momentum.
  • Specific Price Action: The script checks that the current price is significantly lower than recent highs and follows specific mathematical offsets.

Trade Management and Safety Features

Beyond just entering trades, the script includes several "quality of life" and safety features:

  • Time Buffers: The script includes a time-based check to ensure it doesn't enter trades too rapidly. It looks back at the history of closed and open orders to ensure there is a sufficient amount of time passed before executing a new trade on a specific currency.
  • Margin Protection: Before attempting to open a new position, the script checks your "Free Margin." If you do not have enough available funds to cover the required investment (based on your chosen Lot size), it will skip the trade to prevent account over-leveraging.
  • Trailing Stop Loss: This is a dynamic risk management tool. Once a trade is in profit, the script will automatically move the "Stop Loss" price closer to the current market price. This helps lock in profits as the price moves in your favor while still giving the trade room to breathe.
  • Take Profit and Initial Stop Loss: Every trade is opened with a predetermined Take Profit level (to secure gains) and an initial Stop Loss level (to limit losses).

User Controls

The script allows you to customize the following "hard" values:

  • Lots: The size of the position.
  • TakeProfit: How far away your target profit is.
  • TrailingStop: How aggressively the stop loss follows the price.
  • MACD & Check Levels: Sensitivity settings for the momentum indicators used to trigger entries.
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
MACD HistogramParabolic Stop and Reverse systemRelative strength indexStochastic oscillatorMoving average indicator
Miscellaneous
It issuies visual alerts to the screen
16 Views
0 Downloads
0 Favorites
Expert Template for MT 4
//+------------------------------------------------------------------+
//|                                     Expert Template for MT 4.mq4 |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+

extern double TakeProfit = 90;
extern double Lots = 0.2;
extern double TrailingStop = 60;
extern double MACDOpenLevel=3;
extern double check=2;
extern double check2=2;

//-------------------------------------------------------------------+
// Ôóíêöèÿ âîçâðàùàþùàÿ âðåìÿ ïîñëåäíåãî îòêðûòîãî(çàêðûòîãî) îðäåðà |
// åñëè âîçâðàùåíî -1 (îøèáêà âûïîëíåíèÿ), 0-îðäåðà íå îáíàðóæåíî,   |
// ïîëîæèòåëüíîå çíà÷åíèå = èñêîìîìó âðåìåíè îðäåðà                  |
//-------------------------------------------------------------------+
int CheckLastOrderTime (string mSymbol, int select, int mode_price)
  //íà âõîäå òðè çíà÷åíèÿ
  //1. íàèìåíîâàíèå èíñòðóìåíòà
  //2. ñìîòðåòü â èñòîðèè(çàêðûòûå) èëè äåéñòâóþùèå îðäåðà (ñîîòâåòñòâåííî 0 è 1)
  //3. ñìîòðåòü öåíó îòêðûòèÿ èëè çàêðûòèÿ (ñîîòâåòñòâåííî 0 è 1)
  {
//---- 
   int oTotal=0; //õðàíèò çíà÷åíèå êîëè÷åñòâà îðäåðîâ (èñòîðèè èëè äåéñòâóþùèå)
   int co; //õðàíèò çíà÷åíèå íîìåðà òåêóùåãî îðäåðà
   datetime LastTime=0;
   //ïðîâåðêà êîððåêòíîñòè ïåðåäàííûõ ôóíêöèè çíà÷åíèé
   if((select>1 || select<0) || (mode_price<0 || mode_price>1))
   {
      Print("Íåâåðíî ïåðåäàííûå ïàðàìåòðû (ôóíêöèÿ CheckLastOrderTime)");
      return(-1);
   }
   if(select!=1) //åñëè íóæíî ñìîòðåòü â èñòîðèè çàêðûòûõ îðäåðîâ
   {
      oTotal=HistoryTotal();
      for(co=0;co<oTotal;co++) // öèêë ïî îðäåðàì
      {
         if(m_OSelect(co,SELECT_BY_POS,MODE_HISTORY,100)!=-1) //äåëàåì 100 ïîïûòîê îðäåð ñåëåêò
         {
            if(mSymbol==OrderSymbol())
            {
               if(LastTime==0) LastTime=1; //îðäåð â íàëè÷èè
               if(mode_price!=1) //åñëè íóæíî ñìîòðåòü íå âðåìÿ çàêðûòèÿ (îòêðûòèÿ)
               {
                  if(LastTime<OrderOpenTime()) LastTime=OrderOpenTime();
               }
               else //èíà÷å ñìîòðèì âðåìÿ çàêðûòèÿ
               {
                  if(LastTime<OrderCloseTime()) LastTime=OrderCloseTime();
               }
            }
         }
         else
         {
            Alert("Âîçíèêëà îøèáêà , ñì. æóðíàë!");
            return(-1);
         }
      }
   }
   else //èíà÷å ñìîòðèì äåéñòâóþùèå îðäåðà
   {
      oTotal=OrdersTotal();
      for(co=0;co<oTotal;co++) // öèêë ïî îðäåðàì
      {
         if(m_OSelect(co,SELECT_BY_POS,MODE_TRADES,100)!=-1) //äåëàåì 100 ïîïûòîê îðäåð ñåëåêò
         {
            if(mSymbol==OrderSymbol())
            {
               if(LastTime==0) LastTime=1; //îðäåð â íàëè÷èè
               if(mode_price!=1) //åñëè íóæíî ñìîòðåòü íå âðåìÿ çàêðûòèÿ (îòêðûòèÿ)
               {
                  if(LastTime<OrderOpenTime()) LastTime=OrderOpenTime();
               }
               else
               {
                  Alert("Íåâåðíî ïåðåäàííûé ïàðàìåòð! Îðäåð åùå â äåéñòâèè.");
               }
            }
         }
         else
         {
            Alert("Âîçíèêëà îøèáêà , ñì. æóðíàë!");
            return(-1);
         }
      }
   }
//----
   return(LastTime);
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Ôóíêöèÿ äåëàåò Attempt êîëè÷åñòâî ïîïûòîê îðäåð ñåëåêò           |
//+------------------------------------------------------------------+
int m_OSelect(int ct, int sel, int pool, int Attempt)
  {
   int i;
//---- 
//îðäåð ñåëåêò çà Attempt ïîïûòîê
   for(i=0;i<Attempt;i++)
   {
      if( OrderSelect(ct,sel,pool)==1 ) //åñëè îðäåð âûáðàí
      {
         Print( "Ïîïûòêà îðäåð ñåëåêò óäà÷íà "+OrderTicket() );
         return(1);//çàâåðøàåì ôóíêöèþ
      }
   }
   Alert( "Êîä îøèáêè - "+GetLastError() );
   Alert("Íåâîçìîæíî îðäåð ñåëåêò! Ñäåëàíî "+Attempt+" ïîïûòîê.");
//---- 
   return(-1);
  }
//-------------------------------------------------------------------------------------------------


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   double MacdCurrent, MacdPrevious, SignalCurrent,movbuffer,upbuffer,lowbuffer;
   double SignalPrevious, MaCurrent, MaPrevious, PSarCurrent,RSICurrent,RSIPrevious,StocMainCurrent,StocMainPrevious,StocSigCurrent,StocSigPrevious,MovAvCur200,MovAvCur288, MovAvCur13;
   int cnt=0, ticket, total;
   string smb;
   datetime temp1, temp2;

   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return(0);  // check TakeProfit
     }

   MacdCurrent=iMACD(NULL,0,20,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious=iMACD(NULL,0,20,26,9,PRICE_CLOSE,MODE_MAIN,1);
    //---Parabolic SAR
   PSarCurrent= iSAR(NULL,0,0.02,0.2,0);
   //---RSI
   RSICurrent=iRSI(NULL,0,14,PRICE_CLOSE,0);
   RSIPrevious=iRSI(NULL,0,14,PRICE_CLOSE,1);
   //---Stochastic Oscillator
   StocMainCurrent=iStochastic(NULL,0,5,3,3,MODE_EMA,0,MODE_MAIN,0);
   StocMainPrevious=iStochastic(NULL,0,5,3,3,MODE_EMA,0,MODE_MAIN,1);
   StocSigCurrent=iStochastic(NULL,0,5,3,3,MODE_EMA,0,MODE_SIGNAL,0);
   StocSigPrevious=iStochastic(NULL,0,5,3,3,MODE_EMA,0,MODE_SIGNAL,1);
    //---Moving Average
   MovAvCur200=iMA(NULL,0,200,0,MODE_EMA,PRICE_CLOSE,0);
   MovAvCur288=iMA(NULL,0,288,0,MODE_EMA,PRICE_CLOSE,0);
   MovAvCur13=iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0);
   //---Bollinger Bands
   movbuffer=iCustom(NULL,0,"EMA Bands modified",0,0); //middle line value - primer ispolzovanija sobstvennogo
   upbuffer=iCustom(NULL,0,"EMA Bands modified",1,0);  //upper line value .. indikatora v sobstvennom eksperte
   lowbuffer=iCustom(NULL,0,"EMA Bands modified",2,0); //lower line value // EMA Bands modified.mq4
   

   total=OrdersTotal();
   if(total<10) 
     {
      // no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      smb=Symbol();
      // check for long position (BUY) possibility***************************************** //mozhno-li vojti v long
      if(MacdCurrent>15*Point && MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MacdCurrent>MacdPrevious && RSICurrent>RSIPrevious && RSICurrent>500000*Point && Close[0]>MovAvCur288 && Close[0]>MovAvCur200 && MovAvCur288>MovAvCur200)
        {
         //-------EURUSD-------
         if(smb=="EURUSD")
          {
           temp1=CheckLastOrderTime("EURUSD",1,0);
           if(temp1>10)
             {
              if((CurTime()-temp1)>3600)
              ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);
             }
           else
             {
              temp2=CheckLastOrderTime("EURUSD", 0, 0);
              if(temp2>10)
                {
                 if((CurTime()-temp2)>3600)
                 ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);
                }
              else ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);  
             }
          }
         //-------EURUSD-------
         
         //-------GBPUSD-------
         if(smb=="GBPUSD")
          {
           temp1=CheckLastOrderTime("GBPUSD",1,0);
           if(temp1>10)
             {
              if((CurTime()-temp1)>3600)
              ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);
             }
           else
             {
              temp2=CheckLastOrderTime("GBPUSD", 0, 0);
              if(temp2>10)
                {
                 if((CurTime()-temp2)>3600)
                 ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);
                }
              else ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);  
             }
          }
         //-------GBPUSD------- 
         
          //-------USDCHF-------
         if(smb=="USDCHF")
          {
           temp1=CheckLastOrderTime("USDCHF",1,0);
           if(temp1>10)
             {
              if((CurTime()-temp1)>3600)
              ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);
             }
           else
             {
              temp2=CheckLastOrderTime("USDCHF", 0, 0);
              if(temp2>10)
                {
                 if((CurTime()-temp2)>3600)
                 ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);
                }
              else ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);  
             }
          }
         //-------USDCHF------- 
         
         //-------USDJPY-------
         if(smb=="USDJPY")
          {
           temp1=CheckLastOrderTime("USDJPY",1,0);
           if(temp1>10)
             {
              if((CurTime()-temp1)>3600)
              ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);
             }
           else
             {
              temp2=CheckLastOrderTime("USDJPY", 0, 0);
              if(temp2>10)
                {
                 if((CurTime()-temp2)>3600)
                 ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);
                }
              else ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-95*Point,Ask+TakeProfit*Point,"macd sample",16384,0,Green);  
             }
          }
         //-------USDJPY------- 
               
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
           }
         else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
      // check for short position (SELL) possibility***************************************** 
      if(MacdCurrent<0 && MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MacdCurrent<MacdPrevious && PSarCurrent>Close[0] && RSICurrent<RSIPrevious && RSICurrent<500000*Point && StocMainCurrent<StocMainPrevious && StocMainCurrent<StocSigCurrent && StocSigCurrent<StocSigPrevious && StocMainCurrent>300000*Point && StocSigCurrent>300000*Point && Close[0]<MovAvCur288&& Close[0]<MovAvCur200 && MovAvCur288<MovAvCur200 && (Close[0]-Low[0])>=2*Point && (MovAvCur13-Close[0])>1*Point) 
        {
         //-------EURUSD-------
         if(smb=="EURUSD")
          {
           temp1=CheckLastOrderTime("EURUSD",1,0);
           if(temp1>10)
             {
              if((CurTime()-temp1)>3600)
              ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
             }
           else
             {
              temp2=CheckLastOrderTime("EURUSD", 0, 0);
              if(temp2>10)
                {
                 if((CurTime()-temp2)>3600)
                 ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
                }
              else ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
             }
          }
         //-------EURUSD-------
         
         //-------GBPUSD-------
         if(smb=="GBPUSD")
          {
           temp1=CheckLastOrderTime("GBPUSD",1,0);
           if(temp1>10)
             {
              if((CurTime()-temp1)>3600)
              ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
             }
           else
             {
              temp2=CheckLastOrderTime("GBPUSD", 0, 0);
              if(temp2>10)
                {
                 if((CurTime()-temp2)>3600)
                 ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
                }
              else ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
             }
          }
         //-------GBPUSD-------
         
         //-------USDCHF-------
         if(smb=="USDCHF")
          {
           temp1=CheckLastOrderTime("USDCHF",1,0);
           if(temp1>10)
             {
              if((CurTime()-temp1)>3600)
              ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
             }
           else
             {
              temp2=CheckLastOrderTime("GBPUSD", 0, 0);
              if(temp2>10)
                {
                 if((CurTime()-temp2)>3600)
                 ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
                }
              else ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+95*Point,Bid-TakeProfit*Point,"macd sample",16384,0,Red);
             }
          }
         //-------USDCHF-------
         
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
           }
         else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
      return(0);
     }
   // it is important to enter the market correctly, 
   // but it is more important to exit it correctly...   
   for(cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   // check for opened position 
         OrderSymbol()==Symbol())  // check for symbol
        {
         if(OrderType()==OP_BUY)   // long position is opened
           {
          
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
           }
         else // go to short position
           {
            
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
           }
        }
     }
   return(0);
  }
// the end.

Comments