FT_TrendFollower

Author: FORTRADER.RU
Profit factor:
1.24

This script is designed to automate trading in the Forex market by following trends. Here?s a breakdown of its logic:

1. Setting the Stage (Initialization & Input Parameters):

  • The script starts by defining various settings (parameters) that the user can adjust. These settings control how the script identifies trends, enters trades, and exits trades.
  • GMMA (Guppy Multiple Moving Average): The script uses a set of moving averages to identify the trend. The user sets the starting and ending periods for these moving averages (e.g., from 50 to 200) and how many lines to use in the calculation (CountLine=5).
  • EMA (Exponential Moving Average): It uses two EMAs with different periods (4 and 8) as a signal.
  • Trade Bar: Determine which bar to work with.
  • Stop Loss: The script defines how to protect against losses. It lets the user choose between two different stop-loss strategies (either a fixed number of pips from the current price or based on the low of the previous bar). Only one can be activated.
  • Exit Strategy: The script defines when to close a trade to take profits. It offers three ways to exit a trade. Only one can be activated. These strategies involve Pivot Points, Hull Moving Average (HMA) or volatility channels.
  • The script includes a function to check if the parameters are set correctly. For example, it verifies that the starting period for GMMA isn't larger than the ending period.

2. Identifying the Trend (Main Calculation):

  • GMMA Calculation: The script calculates a series of moving averages, as defined by the user's GMMA settings. These moving averages help determine the overall trend direction. It compares the current value of each moving average with its previous value to understand whether each line is moving up or down.
  • Trend Confirmation: It assesses whether the faster moving averages (green lines) are above or below the slower moving averages (red lines). This helps establish the primary trend direction (uptrend or downtrend).
  • Laguerre Filter: The script uses a "Laguerre" filter (a custom indicator) to further confirm the trend. It checks if the filter's value is within specific ranges depending on whether it's looking for a buy (uptrend) or sell (downtrend) opportunity.
  • EMA Confirmation: The script checks the relationship between the 4-period and 8-period EMAs. If the shorter EMA is above the longer EMA, it suggests an uptrend, and vice versa.
  • MACD Confirmation: The script uses MACD to confirm direction and strength of a trend.
  • Direction Check: It validates the direction of all moving averages, ensuring the majority are pointing in the expected direction (up for a buy, down for a sell).

3. Entering a Trade (Buy/Sell Logic):

  • The script waits for all the trend confirmation signals to align before considering a trade. Specifically, it checks:
    • The overall trend direction (from GMMA).
    • The Laguerre filter's value.
    • The relationship between the EMAs.
    • MACD Value
    • The direction of moving averages.
  • If all conditions are met, the script enters a trade in the direction of the trend:
    • Buy (Long): If the trend is up, the script sends a "buy" order to the broker.
    • Sell (Short): If the trend is down, the script sends a "sell" order.
  • Stop Loss Placement: When entering a trade, the script places a stop-loss order to limit potential losses. The stop-loss level is determined based on the user's chosen stop-loss strategy (either a fixed number of pips or based on the low/high of the previous bar).

4. Exiting a Trade (Take Profit/Stop Loss):

  • The script monitors open trades and looks for opportunities to exit them profitably or to cut losses. It uses a combination of three strategies, however the script user can only activate one of those.
  • Pivot Point Exit: The script partially closes or completely closes when the price reaches defined resistance or support levels.
  • HMA Exit: The script uses the value of a Hull Moving Average (HMA) to determine when to exit a trade.
  • Volatility Channel Exit: The script closes a trade if the price movement doesn't align with the established volatility channel.

5. Error Handling:

  • The script includes a function to check for common setup errors, such as incorrect parameter settings. If errors are found, the script will print an error message and stop, preventing it from making potentially bad trades.

In essence, this script automates a trend-following strategy by combining multiple indicators and rules to identify and trade trends in the Forex market. The user can customize various parameters to adjust the script's sensitivity and risk management.

Price Data Components
Series array that contains the highest prices of each barSeries array that contains the lowest prices of each barSeries array that contains close prices for each bar
Orders Execution
It automatically opens orders when conditions are reachedChecks for the total of open ordersIt Closes Orders by itself
Indicators Used
MACD HistogramMoving average indicator
5 Views
1 Downloads
0 Favorites
FT_TrendFollower
//+------------------------------------------------------------------+
//|                                             FT_TrendFollower.mq4 |
//|                                                     FORTRADER.RU |
//|                                              http://FORTRADER.RU |
//| http://www.forexsystems.ru/showthread.php?p=6794                 |
//+------------------------------------------------------------------+
#property copyright "FORTRADER.RU"
#property link      "http://FORTRADER.RU Ñèñòåìà ïî TrendFollower"

extern string GMMA0="Íàñòðîéêà GMMA:";
extern int SrartGMMAPer=50; 
extern int EndGMMAPer=200; 
extern int CountLine=5; 

extern string EMA48="Íàñòðîéêà EMASIG4-8:";
extern int EMA4=4;
extern int EMA8=8;

extern string TradeBar="Íà êàêîì áàðå ðàáîòàåì:";
extern int TradeShift=1;


extern string SL="Íàñòðîéêè ÑòîïËîññà:";
extern int Stoploss1=1;
extern int Stoploss1Pips=5;
extern int Stoploss2=0;
extern int Stoploss2Pips=25;

extern string Q="Íàñòðîéêè Âûõîäà:";
extern int Quit=1;//çàêðûòèå ïîëîâèíû íà îïîðíîé òî÷êå ïîëîâèíû ïðè ñìåíå ëèíèè íà êðàñíóþ
extern int HMAPer=80;
extern int Quit1=0;
extern int Quit2=0;
extern int ChPer=34;



int nummodb,nummodbS;

double ggma[1000];
double ggmalast[1000];
int indexline,trend,EmaSigOk,CloseOk,LaguerreOk,EmaSigOkS,CloseOkS,LaguerreOkS;double ema4,ema8,Laguerre,dMacdMain;

int init(){return(0);}
int deinit(){return(0);}

int start()
{int controlgreen,controlvverh,controlvverhS;double sl;int i;
if(errorchek()!=""){Print(errorchek());return(0);}
    
    exit();
    GMMA();

if(Close[1]<ggma[indexline-1]){CloseOk=1;}
if(Close[1]>ggma[indexline-1]){CloseOkS=1;}


if(CloseOk==1 && Close[1]>ggma[0]){LaguerreOk=0;EmaSigOk=0;CloseOk=0;}
if(CloseOkS==1 && Close[1]<ggma[0]){LaguerreOkS=0;EmaSigOkS=0;CloseOkS=0;}
  
    //ñìîòðèì âñå ëè çåëåíûå âûøå êðàñíûõ 
    trend=2;
    if(ggma[indexline-(CountLine+CountLine)]>ggma[indexline-CountLine] )
    {
    trend=1;
    }
    if(ggma[indexline-(CountLine+CountLine)]<ggma[indexline-CountLine] )
    {
    trend=0;
    }
    
    
   Laguerre();
   if(trend==1 && Laguerre<0.15 && Close[1]>ggma[indexline-1]&& Low[1]<ggma[0]){LaguerreOk=1;}
   if(trend==0 && Laguerre>0.75 && Close[1]<ggma[indexline-1]&& High[1]>ggma[0]){LaguerreOkS=1;}
   EMASIG();
   if(trend==1 && ema4<ema8){EmaSigOk=1;}
   if(trend==0 && ema4>ema8){EmaSigOkS=1;}
 
    for( i=CountLine;i>=0;i--)
    {
    //ïîñìîòðèì íàïðàâëåííû âñå êðàñíûå çåëåíûå è æåëòûå ââåðõ
    if(ggma[indexline-(CountLine+i)]>ggmalast[indexline-(CountLine+i)]){controlvverh=controlvverh+1;}
    if(ggma[indexline-(CountLine+CountLine+i-1)]>ggmalast[indexline-(CountLine+CountLine+i-1)]){controlvverh=controlvverh+1;}
    if(ggma[i]>ggmalast[i]){controlvverh=controlvverh+1;}
    }
    for( i=CountLine;i>=0;i--)
    {
    //ïîñìîòðèì íàïðàâëåííû âñå êðàñíûå çåëåíûå è æåëòûå ââåðõ
    if(ggma[indexline-(CountLine+i)]<ggmalast[indexline-(CountLine+i)]){controlvverhS=controlvverhS+1;}
    if(ggma[indexline-(CountLine+CountLine+i-1)]<ggmalast[indexline-(CountLine+CountLine+i-1)]){controlvverhS=controlvverhS+1;}
    if(ggma[i]<ggmalast[i]){controlvverhS=controlvverhS+1;}
    }
    
    
    
    MACD();
    
    if(trend==1 && Laguerre>0.15 && LaguerreOk==1 && ema4>ema8 && EmaSigOk==1 && dMacdMain>0 && controlvverh>(indexline/2)  )
    {LaguerreOk=0;EmaSigOk=0;CloseOk=0;
    if(Stoploss1==1){sl=Low[1]-(Stoploss1Pips+MarketInfo(Symbol(),MODE_SPREAD))*Point; if(MathAbs(Ask-sl)<15*Point){sl=Ask-15*Point;}}
    if(Stoploss2==1){sl=Ask-Stoploss2Pips*Point;}
    OrderSend(Symbol(),OP_BUY,0.1,Ask,3,NormalizeDouble(sl,4),0,"FORTRADER.RU",1337,0,Green);
    nummodb=0;
    }
    
    if(trend==0 && Laguerre<0.75 && LaguerreOkS==1 && ema4<ema8 && EmaSigOkS==1 && dMacdMain<0 && controlvverhS>(indexline/2)  )
    {LaguerreOkS=0;EmaSigOkS=0;CloseOkS=0;
    if(Stoploss1==1){sl=High[1]+(Stoploss1Pips+MarketInfo(Symbol(),MODE_SPREAD))*Point; if(MathAbs(Bid-sl)<15*Point){sl=Bid+15*Point;}}
    if(Stoploss2==1){sl=Bid+Stoploss2Pips*Point;}
    OrderSend(Symbol(),OP_SELL,0.1,Bid,3,NormalizeDouble(sl,4),0,"FORTRADER.RU",1337,0,Green);
    nummodbS=0;
    }
  
return(0);
}

int MACD()
{
 dMacdMain = iMACD(Symbol(),NULL,5,35,5,PRICE_CLOSE,MODE_MAIN,1);
}

int EMASIG()
{
ema4=iMA(NULL,0,EMA4,0,MODE_EMA,PRICE_CLOSE,TradeShift);
ema8=iMA(NULL,0,EMA8,0,MODE_EMA,PRICE_CLOSE,TradeShift);
}

int Laguerre()
{
Laguerre=iCustom(Symbol(),NULL,"Laguerre",0,TradeShift);
}

int GMMA()
{indexline=0;
//âû÷èñëèì îáùåå êîëè÷åñòâî ëèíèé
int cline=5*CountLine;
//âû÷èñëèì øàã ëèíèé
int shagline=(EndGMMAPer-SrartGMMAPer)/cline;

//ïîëó÷èì çíà÷åíèÿ ëèíèé ëèíèè

for(int per=SrartGMMAPer;per<=EndGMMAPer;per=per+shagline)
{
ggma[indexline]=iMA(NULL,0,per,0,MODE_EMA,PRICE_CLOSE,TradeShift);
ggmalast[indexline]=iMA(NULL,0,per,0,MODE_EMA,PRICE_CLOSE,TradeShift+1);
indexline=indexline+1;
}

}

string errorchek()
{
if(SrartGMMAPer>EndGMMAPer){return("Îøèáêà! SrartGMMAPer íå ìîæåò áûòü áîëüøå EndGMMAPer");}
if(SrartGMMAPer==EndGMMAPer){return("Îøèáêà! SrartGMMAPer íå ìîæåò áûòü ðàâíî EndGMMAPer");}
if(CountLine==0){return("Îøèáêà! CountLine íå ìîæåò áûòü 0");}
if(CountLine>10){return("Îøèáêà! CountLine íå ìîæåò áûòü áîëüøå 10");}
if(CountLine>SrartGMMAPer){return("Îøèáêà! CountLine íå ìîæåò áûòü áîëüøå SrartGMMAPer");}
if(CountLine>EndGMMAPer){return("Îøèáêà! CountLine íå ìîæåò áûòü áîëüøå EndGMMAPer");}
if(EMA4>EMA8){return("Îøèáêà! EMA4 íå ìîæåò áûòü áîëüøå EMA8");}
if(Stoploss1==1 && Stoploss2==1){return("Îøèáêà! StopLoss íå ìîæåò áûòü âëþ÷åíî äâà âàðèàíòà îäíîâðåìåííî");}
if(TradeShift>1 || Stoploss1>1 || Stoploss2>1 || Quit>1 || Quit1>1 || Quit2>1){return("Îøèáêà! çíà÷åíèÿ TradeShift>1 || Stoploss1>1 || Stoploss2>1 || Quit>1 Quit1>1 || Quit2>1 íå ìîãóò áûòü áîëüøå 1");}
if(Quit>0 && Quit1>0 || Quit2>0){return("Îøèáêà! Âàðèàíò ñòîï ëîññà ìîæåò áûòü òîëüêî îäèí");}
if(Quit1>0 && Quit>0 || Quit2>0){return("Îøèáêà! Âàðèàíò ñòîï ëîññà ìîæåò áûòü òîëüêî îäèí");}
if(Quit2>0 && Quit>0 || Quit1>0){return("Îøèáêà! Âàðèàíò ñòîï ëîññà ìîæåò áûòü òîëüêî îäèí");}

return("");
}

int exit()
{
double Pivot= (iHigh(Symbol(),1440,1) + iLow(Symbol(),1440,1) +  iClose(Symbol(),1440,1))/3;
double support1 = (2 * Pivot) - iHigh(Symbol(),1440,1);
double resist1 = (2 * Pivot) - iLow(Symbol(),1440,1);
double support2 = Pivot - (iHigh(Symbol(),1440,1) - iLow(Symbol(),1440,1));
double resist2 = Pivot + (iHigh(Symbol(),1440,1) - iLow(Symbol(),1440,1));

double hma=iCustom(Symbol(),0,"HMA",HMAPer,0,TradeShift);
double hma1=iCustom(Symbol(),0,"HMA",HMAPer,1,TradeShift);
double hma2=iCustom(Symbol(),0,"HMA",HMAPer,2,TradeShift);

double vltUP=iMA(NULL,0,ChPer,0,MODE_SMA,PRICE_HIGH,TradeShift);
double vltDW=iMA(NULL,0,ChPer,0,MODE_SMA,PRICE_LOW,TradeShift);

Comment("hma " ,hma, " hma1 " ,hma1," hma2 " ,hma2);


for( int i=1; i<=OrdersTotal(); i++)          
     {
     /*çàêðûòèå ïî ïèâîòó è ñóïåð ëèíèè-------------------------------------------------------------------------------*/
      if (OrderSelect(i-1,SELECT_BY_POS)==true) 
        {                                       
         if(OrderType()==OP_BUY && Bid>resist1 && OrderProfit()>0  && nummodb==0 && OrderSymbol()==Symbol() && Quit==1)
         {  
          OrderClose(OrderTicket(),NormalizeDouble(OrderLots()/2,2),Bid,3,Violet); 
          nummodb++;
         }
        }
        
       if (OrderSelect(i-1,SELECT_BY_POS)==true) // Åñëè åñòü ñëåäóþùèé
        {                                       // À
         if(OrderType()==OP_BUY && hma1!=EMPTY_VALUE && OrderProfit()>0 && OrderSymbol()==Symbol() && nummodb==1 && Quit==1)
         {  
         OrderClose(OrderTicket(),NormalizeDouble(OrderLots(),2),Bid,3,Violet); 
         nummodb++;
         }
        }
        /*çàêðûòèå ïî ïèâîòó -------------------------------------------------------------------------------*/
              if (OrderSelect(i-1,SELECT_BY_POS)==true) 
        {                                       
         if(OrderType()==OP_BUY && Bid>resist1 && OrderProfit()>0  && nummodb==0 && OrderSymbol()==Symbol() && Quit1==1)
         {  
          OrderClose(OrderTicket(),NormalizeDouble(OrderLots()/2,2),Bid,3,Violet); 
          nummodb++;
         }
        }
        
       if (OrderSelect(i-1,SELECT_BY_POS)==true) // Åñëè åñòü ñëåäóþùèé
        {                                       // À
         if(OrderType()==OP_BUY && Bid>resist2 && OrderProfit()>0 && OrderSymbol()==Symbol() && nummodb==1 && Quit1==1)
         {  
         OrderClose(OrderTicket(),NormalizeDouble(OrderLots(),2),Bid,3,Violet); 
         nummodb++;
         }
        }
        /*çàêðûòèå ïî ïèâîòó è êàíàëó âîëàòèëüíîñòè-------------------------------------------------------------------------------*/ 
                     if (OrderSelect(i-1,SELECT_BY_POS)==true) 
        {                                       
         if(OrderType()==OP_BUY && Bid>resist1 && OrderProfit()>0  && nummodb==0 && OrderSymbol()==Symbol() && Quit2==1)
         {  
          OrderClose(OrderTicket(),NormalizeDouble(OrderLots()/2,2),Bid,3,Violet); 
          nummodb++;
         }
        }
        
       if (OrderSelect(i-1,SELECT_BY_POS)==true) // Åñëè åñòü ñëåäóþùèé
        {                                       // À
         if(OrderType()==OP_BUY && Open[1]<vltDW && OrderProfit()>0 && OrderSymbol()==Symbol() && nummodb==1 && Quit2==1)
         {  
         OrderClose(OrderTicket(),NormalizeDouble(OrderLots(),2),Bid,3,Violet); 
         nummodb++;
         }
        }
        
        ///////////////////////////ÏÐÎÄÀÆÈ/////////////////////////////////////////////////////////////////////////////////////////////////////
        if (OrderSelect(i-1,SELECT_BY_POS)==true) 
        {                                       
         if(OrderType()==OP_SELL && Ask<support1 && OrderProfit()>0  && nummodbS==0 && OrderSymbol()==Symbol() && Quit==1)
         {  
          OrderClose(OrderTicket(),NormalizeDouble(OrderLots()/2,2),Ask,3,Violet); 
          nummodbS++;
         }
        }
        
       if (OrderSelect(i-1,SELECT_BY_POS)==true) // Åñëè åñòü ñëåäóþùèé
        {                                       // À
         if(OrderType()==OP_SELL && hma!=EMPTY_VALUE && OrderProfit()>0 && OrderSymbol()==Symbol() && nummodbS==1 && Quit==1)
         {  
         OrderClose(OrderTicket(),NormalizeDouble(OrderLots(),2),Ask,3,Violet); 
         nummodbS++;
         }
        }
        /*çàêðûòèå ïî ïèâîòó -------------------------------------------------------------------------------*/
       if (OrderSelect(i-1,SELECT_BY_POS)==true) 
        {                                       
         if(OrderType()==OP_BUY && Ask<support1 && OrderProfit()>0  && nummodbS==0 && OrderSymbol()==Symbol() && Quit1==1)
         {  
          OrderClose(OrderTicket(),NormalizeDouble(OrderLots()/2,2),Ask,3,Violet); 
          nummodbS++;
         }
        }
        
       if (OrderSelect(i-1,SELECT_BY_POS)==true) // Åñëè åñòü ñëåäóþùèé
        {                                       // À
         if(OrderType()==OP_BUY && Ask<support2 && OrderProfit()>0 && OrderSymbol()==Symbol() && nummodbS==1 && Quit1==1)
         {  
         OrderClose(OrderTicket(),NormalizeDouble(OrderLots(),2),Ask,3,Violet); 
         nummodbS++;
         }
        }
        /*çàêðûòèå ïî ïèâîòó è êàíàëó âîëàòèëüíîñòè-------------------------------------------------------------------------------*/ 
        if (OrderSelect(i-1,SELECT_BY_POS)==true) 
        {                                       
         if(OrderType()==OP_BUY && Ask<support1 && OrderProfit()>0  && nummodbS==0 && OrderSymbol()==Symbol() && Quit2==1)
         {  
          OrderClose(OrderTicket(),NormalizeDouble(OrderLots()/2,2),Ask,3,Violet); 
          nummodbS++;
         }
        }
        
       if (OrderSelect(i-1,SELECT_BY_POS)==true) // Åñëè åñòü ñëåäóþùèé
        {                                       // À
         if(OrderType()==OP_BUY && Open[1]>vltUP && OrderProfit()>0 && OrderSymbol()==Symbol() && nummodbS==1 && Quit2==1)
         {  
         OrderClose(OrderTicket(),NormalizeDouble(OrderLots(),2),Ask,3,Violet); 
         nummodbS++;
         }
        }
      }

return(0);
}

Profitability Reports

USD/CAD Oct 2024 - Jan 2025
3.05
Total Trades 27
Won Trades 22
Lost trades 5
Win Rate 81.48 %
Expected payoff 3.20
Gross Profit 128.58
Gross Loss -42.21
Total Net Profit 86.37
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
0.15
Total Trades 42
Won Trades 18
Lost trades 24
Win Rate 42.86 %
Expected payoff -4.80
Gross Profit 35.10
Gross Loss -236.80
Total Net Profit -201.70
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
0.53
Total Trades 39
Won Trades 20
Lost trades 19
Win Rate 51.28 %
Expected payoff -3.99
Gross Profit 172.50
Gross Loss -328.10
Total Net Profit -155.60
-100%
-50%
0%
50%
100%

Comments