gpfTCPivotStop

Author: Copyright � 2006, George-on-Don
Profit factor:
5.70

This script is designed to automatically trade on the Forex market using a pivot point strategy. Here's a breakdown of how it works:

1. Calculating Pivot Points:

  • The script first calculates "Pivot Points" ? which are key levels used to predict potential support and resistance areas in the market. Support levels are price levels where the price tends to stop falling, while resistance levels are price levels where the price tends to stop rising.
  • These points are calculated based on the high, low, and closing price of the previous day (specifically, using the first hour of the current day to look back at the previous 24 hours of that day) and remain constant through the timeframe the chart its loaded on (1hour). It calculates a central "Pivot" point, and then calculates three levels of Resistance (price levels where the price might stop rising) and three levels of Support (price levels where the price might stop falling) based on the Pivot point.
  • This calculation only happens once per day; after the first tick of the hour the script determines all pivot points and support/resistance levels.

2. Determining Trade Size:

  • The script can either use a fixed lot size (the amount of currency you trade) or calculate it automatically based on your account balance and risk tolerance.
  • If set to calculate automatically, it determines the lot size by considering how much money you're willing to risk on each trade. It also tries to reduce the lot size if you've had a series of losing trades, in an attempt to protect your capital.

3. Opening Trades:

  • The script constantly monitors the price and compares it to the calculated Pivot Point.
  • If the price crosses below the Pivot Point, it considers opening a "Sell" trade (betting that the price will continue to fall).
  • If the price crosses above the Pivot Point, it considers opening a "Buy" trade (betting that the price will continue to rise).
  • When opening a trade, it sets a "Stop Loss" (an order to automatically close the trade if the price moves against you to limit losses) and a "Take Profit" (an order to automatically close the trade when the price reaches a certain level to secure profits). The placement of these stop-loss and take-profit orders are based upon the calculated Support and Resistance levels.
  • It attempts the open the trade and in case that it fails, a second order attempt will be placed with different parameters.
  • An email can be sent whenever a trade is opened.

4. Managing Open Trades:

  • The script checks all open trades on its chart.
  • The script can implement a "trailing stop," which automatically adjusts the stop-loss order as the price moves in your favor, locking in profits.
  • It also has the functionality to close trades automatically at the end of the day. This ensures that the script doesn't hold trades overnight.
  • An email can be sent whenever a trade is closed.

5. Email Notifications:

  • The script can send email alerts to notify you when it opens or closes trades.

In Summary:

This script is an automated trading system that uses Pivot Points to identify potential trading opportunities. It calculates trade sizes based on risk settings, automatically opens and manages trades with stop-loss and take-profit levels, and can send email notifications to keep you informed.

Price Data Components
Series array that contains close prices for each bar
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 strategyIt Closes Orders by itself
Miscellaneous
It sends emails
7 Views
0 Downloads
0 Favorites
gpfTCPivotStop
//+------------------------------------------------------------------+
//|                                               gpfTCPivotStop.mq4 |
//|                                  Copyright © 2006, George-on-Don |
//|                                       http://www.forex.aaanet.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2006, George-on-Don"
#property link      "http://www.forex.aaanet.ru"

#include <stdlib.mqh>
#include <stderror.mqh>

#define MAGICMA  20050610

extern double    Lots=0.1;             // lot size
extern bool      SndMl=true;           // is send e-mail message?
extern bool      isFloatLots = true;   // is cals lot size 
extern double    DcF = 3;              // optimization factor 
extern double    MaxR = 0.02;          // max risk
extern int       TgtProfit = 1;        // if take profit = Support1 or Resist1 = TgtProfit= 1
                                       // if take profit = Support2 or Resist2 = TgtProfit =2 
                                       // if take profit = Support3 or Resist3 = TgtProfit =3 
extern bool isTradeDay = False;        // is trade intraday or extraday?
extern bool      isTrace = False;      // is tracer on?


double Pivot;
double Resist1;
double Resist2;
double Support1;
double Support2;
double Support3;
double Resist3;

double StpBuy;
double StpSell;
double PrftBuy;
double PrftSell;


double pPoint;
double r1 , s1 ,s2, r2, r3, s3 ;
int err;
bool isCals=false;
//+------------------------------------------------------------------+
//| CalculateCurrentOrders function                                   |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0;
   int sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) 
         break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  
            buys++;
         if(OrderType()==OP_SELL) 
           sells++;
        }
     }
//---- return orders volume
      if(buys>0) 
         return(buys);
      else
        return(-sells);
  }

//+------------------------------------------------------------------+
//| LotsOptimized function                                           |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   if (isFloatLots == true) 
    {  
 	int    orders=HistoryTotal();     // history orders total
	int    losses=0;                  // number of losses orders without a break
	//---- select lot size
	   lot=NormalizeDouble(AccountFreeMargin()*MaxR/1000.0,1);
	//---- calcuulate number of losses orders without a break
	   if(DcF>0)
     	{
      	for(int i=orders-1;i>=0;i--)
        		{
	         	if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Îøèáêà â èñòîðèè!"); break; }
         		if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         	//----
	         	if(OrderProfit()>0) break;
         		if(OrderProfit()<0) losses++;
        		}
      	if(losses>1) lot=NormalizeDouble(lot-lot*losses/DcF,1);
     	}
   }
//---- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
}
//+------------------------------------------------------------------+
//| initialization of Calspivot function                                              |
//+------------------------------------------------------------------+
bool isCalsPivot()
{
   int tHour;
   double hLine;
   double lLine;
   int i,k;
   if(Volume[0]>1) return(false);
   if (TimeHour(Time[1])== 0 )
   //if (TimeHour(Time[1])<=24 || TimeHour(Time[0])>=0) 
   {
   tHour  = TimeHour(Time[2]);
 	k= tHour+1;
 	if (isTrace == true)
   {
    Print("tHour",tHour);
    Print("K",k);
   }
 	
   hLine   = High[tHour];
	lLine   = Low[tHour];
  
 	for (i = tHour+1; i > 0; i--)
 	{
 	   
   if (Low[i+1]  < lLine) lLine = Low[i+1];
	if (High[i+1] > hLine) hLine = High[i+1];
    if (isTrace == true)
      {
      Print("i# ",i," lLine# ", lLine, " Low# ", Low[i+1], " hLine #", hLine, " High #", High[i+1], " time #" , TimeHour(Time[i+1]), " day #", TimeDay(Time[i+1]));
      }
   }
   
   pPoint = (lLine + hLine + Close[2]) / 3;
	r1 = 2 * pPoint - lLine;
	s1 = 2 * pPoint - hLine;
	r2 = pPoint + (r1 - s1);
	s2 = pPoint - (r1 - s1);
   r3 = hLine + 2 * (pPoint - lLine);
   s3 = lLine - 2 * (hLine - pPoint);
   CalsPivot();
   isCals = true;
   return (true);
   }
   return (false);
}
//+------------------------------------------------------------------+
//| Cals Pivot    function                                           |
//+------------------------------------------------------------------+
void CalsPivot()
{
    
      Pivot    =NormalizeDouble(pPoint,Digits);
      Resist1  =NormalizeDouble(r1,Digits);
      Resist2  =NormalizeDouble(r2,Digits);
      Resist3  =NormalizeDouble(r3,Digits);
      Support1 =NormalizeDouble(s1,Digits);
      Support2 =NormalizeDouble(s2,Digits);
      Support3 =NormalizeDouble(s3,Digits);
      if (isTrace == true)
         {
         Print("Pivot# ",Pivot," Resist1# ",Resist1," Support1# ",Support1);
         }
}
//+------------------------------------------------------------------+
//| CheckForOpen trade function                                      |
//+------------------------------------------------------------------+

void CheckForOpen()
{
   string sHeaderLetter;
   string sBodyLetter;
   int err2;  
   
   // is first tick?
   if(Volume[0]>1) return;
   
   //---- Sell trade
     if ( Close[1]<Pivot && Close[2]>=Pivot)
     {
         if (isTrace == true)
         {
         Print("Close1#", Close[1]);
         Print("Pivot#",Pivot);
         Print("Close2#",Close[2]);
         }
         switch (TgtProfit)
         {
          case 1 : err = OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,Resist1,Support1,"",MAGICMA,0,Red);
               break;
          case 2 : err = OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,Resist1,Support2,"",MAGICMA,0,Red);
               break;
          case 3 : err = OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,Resist2,Support3,"",MAGICMA,0,Red);
               break;
         default : err = OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,Resist1,Support1,"",MAGICMA,0,Red); 
         }
            StpSell = Resist1;
            PrftSell = Support1;
       if (err < 0)
        {
         Print("OrderSend Sell failed err#", GetLastError());
         if (isTrace == true)
               {
               Print("Bid#",Bid);
               Print("Pivot #",Pivot);
               Print("Stop loss#",Resist1);
               Print("Take prof#",Support2);
               }
         if (GetLastError()== 130) err2 =OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,Resist2,Support3,"",MAGICMA,0,Red);
            StpSell = Resist2;
            PrftSell = Support2;
            if ( err2 <0)
            {
            Print("OrderSend Sell failed err2#", GetLastError());
             if (isTrace == True)
             {
               Print("Bid#",Bid);
               Print("Pivot #",Pivot);
               Print("Stop loss#",Resist2);
               Print("Take prof#",Support3);
             }  
            }
         return(0);   
        }else{
          if (SndMl == True ) 
          {
               sHeaderLetter = "Operation SELL by " + Symbol()+"";
               sBodyLetter = "Order Sell by "+ Symbol() + " at " + DoubleToStr(Bid,4)+ ", and set stop/loss at " + DoubleToStr(StpSell,4)+"";
               sndMessage(sHeaderLetter, sBodyLetter);
          }
        }
      //return;
     }
      //---- Buy trade
   if ( Close[1]>Pivot && Close[2]<=Pivot)
     {
      if (isTrace == true)
      {
      Print("Close1#", Close[1]);
      Print("Pivot#",Pivot);
      Print("Close2#",Close[2]);
      }
      switch (TgtProfit)
      {
      case 1:  err=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,Support1,Resist1,"",MAGICMA,0,Blue);
          break;
      case 2:  err=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,Support1,Resist2,"",MAGICMA,0,Blue);
          break;  
      case 3:  err=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,Support2,Resist3,"",MAGICMA,0,Blue);
          break;
      default :  err=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,Support1,Resist1,"",MAGICMA,0,Blue); 
      }
         StpBuy = Support1;
         PrftBuy = Resist1;
      if (err < 0)
        {
         Print("OrderSend Buy failed err#", GetLastError());
         if (isTrace== true)
            {
            Print("Bid#",Bid);
            Print("Pivot #",Pivot);
            Print("Stop loss#",Support2);
            Print("Take prof#",Resist3);
            }
         if (GetLastError() == 130) err2=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,Support2,Resist3,"",MAGICMA,0,Blue);
               StpBuy  = Support2;
               PrftBuy = Resist2;
            if (err2 < 0)
            {
            Print("OrderSend Buy failed err2#", GetLastError());
            if (isTrace== true)
            {
            Print("Bid#",Bid);
            Print("Pivot #",Pivot);
            Print("Stop loss#",Support2);
            Print("Take prof#",Resist3);
            }
         }
         return(0);   
        }else{
            if ( SndMl == True )
            { 
               sHeaderLetter = "Operation BUY at " + Symbol()+"";
               sBodyLetter = "Order Buy at "+ Symbol() + " for " + DoubleToStr(Ask,4)+ ", and set stop/loss at " + DoubleToStr(StpBuy,4)+"";
               sndMessage(sHeaderLetter, sBodyLetter);
            }
        }      
      return;
      }    
}  

//+------------------------------------------------------------------+
//| CheckForClose open trade function                                |
//+------------------------------------------------------------------+
void CheckForClose()
{
   string sHeaderLetter;
   string sBodyLetter;
   bool CloseOrd;
   
//---- 
   if(Volume[0]>1) return;
  
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)        break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //----  
      if(OrderType()==OP_BUY)
        {
        if (isTrace== true)
            {
         Print("in OP_BUY");
            }
            // trailing stop
            if(Bid >= StpSell)
               {
               if(OrderStopLoss()== PrftSell)
                  {
                  err=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(Ask-Bid) ,OrderTakeProfit(),0,Green);
                     if (err < 0)
                     {
                        Print("OrderModify Buy failed err#", GetLastError());
                        if (isTrace== true)
                        {
                        Print("Bid#",Bid);
                        Print("Pivot #",OrderOpenPrice());
                        Print("Stop loss#",PrftSell);
                        Print("First prof#",StpSell);
                        }
                     return(0);
                     }
                  return ;

                  }
                }
            if (isTradeDay == True && TimeHour(Time[0])== 24 ) 
            {
            CloseOrd=OrderClose(OrderTicket(),OrderLots(),Bid,3,Lime);
            }
            if ( SndMl == True && CloseOrd == True)
            {
                 sHeaderLetter = "Operation CLOSE BUY at" + Symbol()+"";
                 sBodyLetter = "Close order Buy at "+ Symbol() + " for " + DoubleToStr(Bid,4)+ ", and finish this Trade";
                 sndMessage(sHeaderLetter, sBodyLetter);
            }
         break;
        }
      if(OrderType()==OP_SELL)
        {
            if (isTrace== true)
            {
            Print("in OP_SELL");
            }
            // trailing stop                           
            if( Ask <= StpBuy)
               {
               if(OrderStopLoss()== PrftBuy) 
                  {
                  err = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,Red);
                  if (err < 0)
                     {
                        Print("OrderModify Sell failed err#", GetLastError());
                        if (isTrace== true)
                        {
                        Print("Bid#",Bid);
                        Print("Pivot #",OrderOpenPrice());
                        Print("Stop loss#",StpBuy);
                        Print("First prof#",PrftBuy);
                        }
                     return(0);
                     }
                  return;
                  }
               }
               
            if (isTradeDay == True && TimeHour(Time[0])== 24 ) 
            {
            CloseOrd=OrderClose(OrderTicket(),OrderLots(),Ask,3,Lime);
            }
         if ( SndMl == True && CloseOrd == True) 
         {
              sHeaderLetter = "Operation CLOSE SELL at" + Symbol()+"";
              sBodyLetter = "Close order Sell at "+ Symbol() + " for " + DoubleToStr(Ask,4)+ ", and finish this Trade";
              sndMessage(sHeaderLetter, sBodyLetter);
         }
         break;
        }
     }
//----
}  
//--------------------------------------------------------------------
// message sending function                                          |
//--------------------------------------------------------------------
void sndMessage(string HeaderLetter, string BodyLetter)
{
   int RetVal;
   SendMail( HeaderLetter, BodyLetter );
   RetVal = GetLastError();
   if (isTrace== true)
   {
   if (RetVal!= ERR_NO_MQLERROR) Print ("Error, message not sending: ", ErrorDescription(RetVal));
   }
}

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//---- 
   if (Period() != PERIOD_H1) 
   {
   Print("Error, Time Frame is not 1 hour!");
   return ; 
   }
   if(Bars<25 || IsTradeAllowed()==false) return;
   
   if (isCalsPivot()==false) return ;
     
   if(CalculateCurrentOrders(Symbol())==0 ) 
   CheckForOpen();
   else
   CheckForClose();
//-
//----
   return(0);
  }
//+------------------------------------------------------------------+

Profitability Reports

GBP/USD Jul 2025 - Sep 2025
1.03
Total Trades 5
Won Trades 3
Lost trades 2
Win Rate 60.00 %
Expected payoff 1.04
Gross Profit 203.00
Gross Loss -197.80
Total Net Profit 5.20
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.20
Total Trades 6
Won Trades 2
Lost trades 4
Win Rate 33.33 %
Expected payoff -34.35
Gross Profit 52.57
Gross Loss -258.69
Total Net Profit -206.12
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.34
Total Trades 8
Won Trades 3
Lost trades 5
Win Rate 37.50 %
Expected payoff -21.02
Gross Profit 88.20
Gross Loss -256.40
Total Net Profit -168.20
-100%
-50%
0%
50%
100%
USD/JPY Jan 2025 - Jul 2025
2.35
Total Trades 11
Won Trades 8
Lost trades 3
Win Rate 72.73 %
Expected payoff 31.32
Gross Profit 599.05
Gross Loss -254.56
Total Net Profit 344.49
-100%
-50%
0%
50%
100%
USD/CHF Jan 2025 - Jul 2025
1.02
Total Trades 18
Won Trades 8
Lost trades 10
Win Rate 44.44 %
Expected payoff 0.73
Gross Profit 620.15
Gross Loss -607.05
Total Net Profit 13.10
-100%
-50%
0%
50%
100%
NZD/USD Jan 2025 - Jul 2025
1.46
Total Trades 7
Won Trades 5
Lost trades 2
Win Rate 71.43 %
Expected payoff 7.20
Gross Profit 159.40
Gross Loss -109.00
Total Net Profit 50.40
-100%
-50%
0%
50%
100%
GBP/USD Jan 2025 - Jul 2025
0.71
Total Trades 8
Won Trades 4
Lost trades 4
Win Rate 50.00 %
Expected payoff -11.33
Gross Profit 221.10
Gross Loss -311.70
Total Net Profit -90.60
-100%
-50%
0%
50%
100%
GBP/CAD Jan 2025 - Jul 2025
2.11
Total Trades 20
Won Trades 15
Lost trades 5
Win Rate 75.00 %
Expected payoff 27.02
Gross Profit 1027.57
Gross Loss -487.10
Total Net Profit 540.47
-100%
-50%
0%
50%
100%
GBP/AUD Jan 2025 - Jul 2025
0.75
Total Trades 14
Won Trades 9
Lost trades 5
Win Rate 64.29 %
Expected payoff -10.25
Gross Profit 434.49
Gross Loss -577.97
Total Net Profit -143.48
-100%
-50%
0%
50%
100%
EUR/USD Jan 2025 - Jul 2025
0.12
Total Trades 8
Won Trades 3
Lost trades 5
Win Rate 37.50 %
Expected payoff -54.85
Gross Profit 60.70
Gross Loss -499.50
Total Net Profit -438.80
-100%
-50%
0%
50%
100%

Comments