OverHedge_mini

Download script
Author: Copyright � 2005
Profit factor:
0.59

This automated trading script is designed to manage a "hedged" trading strategy. In simple terms, it opens multiple positions in opposite directions (buying and selling) simultaneously to manage market volatility while seeking specific profit targets.

Here is a breakdown of the logic used by the script:

Market Analysis & Direction

The script begins by analyzing the current market trend using mathematical averages (Moving Averages). It looks at two different timeframes—a "Short Period" and a "Long Period"—to determine the momentum.

  • If the short-term average is higher than the long-term average, it identifies an Upward trend.
  • If it is lower, it identifies a Downward trend.

Trade Entry Logic

Once a trend is established, the script determines where to place its first set of trades based on a "Tunnel" system:

  • In an Upward Trend: It prepares to Buy at current prices but sets a "buffer zone" (the Tunnel) for Sell orders.
  • In a Downward Trend: It prepares to Sell at current prices and sets a buffer zone for Buy orders.

The Hedging & Scaling Mechanism

The script does not just open one trade; it builds a grid of positions:

  • Position Counting: The script constantly monitors how many trades are currently open.
  • Dynamic Lot Sizing: As the number of open positions increases, the script automatically increases the volume (lots) of the next trade based on a multiplier. This is intended to balance the weight of the open positions as the grid grows.
  • Alternating Trades: The script systematically alternates between Buy and Sell orders to maintain a hedge, ensuring that as it adds more positions, it is balanced between both sides of the market.

Profit Management and Exit Strategy

The script handles closing trades in two distinct ways:

  1. Targeted Profit: If the total profit from all open positions reaches a specific pre-set goal (the Pip Target), the script will automatically close every single position to "reset" the cycle.
  2. Individual Trade Handling:
    • Losing Trades: The script identifies losing positions and closes them first.
    • Winning Trades: It identifies winning positions and closes them only after a brief "sleep" or pause period, allowing for a moment of price stabilization before finalizing the exit.

Safety Features

  • Magic Number: It uses a unique identification number to ensure it only manages the trades it opened, avoiding interference with other manual trades or different robots on the same account.
  • Shutdown Mode: There is a specific command that allows the user to instantly close all open positions and stop the script's activity immediately.
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It automatically opens orders when conditions are reached
Indicators Used
Moving average indicator
16 Views
0 Downloads
0 Favorites
OverHedge_mini
/*-----------------------------+
|			       |
| Shared by www.Aptrafx.com    |
|			       |
+------------------------------*/

//+------------------------------------------------------------------+
//|                                                  OverHedgeV2.mq4 |
//|                                               Copyright © 2006,  |
//|                                                                  |
//| Written by MrPip (Robert Hill) for kmrunner                      |
//| 3/7/06  Added check of direction for first trade Buy or Sell     |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005"
#property link      "http://www.strategtbuilderfx.com"
#include <stdlib.mqh>


extern int    MagicNumber = 11111;
extern double Lots = 0.01;
extern double HedgeBase = 2.0; 
extern int Slippage = 5;
extern bool shutdownGrid = false;
extern int TunnelWidth=20;

extern double profitTarget = 100;     // if > 0, will close out all positions once the pip target has been met
extern bool UseLSMA = true;
extern int MAShortPeriod=8;   // original was 7, change based on new optimization Mar06
extern int MALongPeriod=21;   // original was 16, change based on new optimization Mar06
extern int    PauseSeconds  =     6; // Number of seconds to "sleep" before closing the next winning trade
extern int    MillisPerSec  =  1000; // DO NOT CHANGE - Standard multiplier to convert seconds to milliseconds

double TunnelSize;
string setup;
double startBuyRate, startSellRate;
int currentOpen;
int NumBuyTrades, NumSellTrades;   // Number of buy and sell trades in this symbol
bool myWantLongs;
double lotMM;
double Profit;
bool OK2Buy,OK2Sell, FirstDirSell;

//+------------------------------------------------------------------------+
//| LSMA - Least Squares Moving Average function calculation               |
//| LSMA_In_Color Indicator plots the end of the linear regression line    |
//+------------------------------------------------------------------------+

double LSMA(int Rperiod, int shift)
{
   int i;
   double sum;
   int length;
   double lengthvar;
   double tmp;
   double wt;

   length = Rperiod;
 
   sum = 0;
   for(i = length; i >= 1  ; i--)
   {
     lengthvar = length + 1;
     lengthvar /= 3;
     tmp = 0;
     tmp = ( i - lengthvar)*Close[length-i+shift];
     sum+=tmp;
    }
    wt = sum*6/(length*(length+1));
    
    return(wt);
}


//+------------------------------------------------------------------+
//| CheckDirection                                                   |
//| Check direction for trade                                        |
//| return 1 for up, -1 for down, 0 for flat                         |
//+------------------------------------------------------------------+
int CheckDirection()
{
   double SlowMA, FastMA;
   double Dif;
   
   if (UseLSMA)
   {
     FastMA = LSMA(MAShortPeriod,1);
     SlowMA = LSMA(MALongPeriod,1);
   }
   else
   {
     FastMA = iMA(NULL,0,MAShortPeriod,0,MODE_EMA,PRICE_CLOSE,1);
     SlowMA = iMA(NULL,0,MALongPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   }
 
   Dif = FastMA-SlowMA;
   
   if(Dif > 0 ) return(1);
   if(Dif < 0 ) return(-1);
   return(0);
   

}

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---- 
   setup = StringConcatenate( "OverHedgeEMA-", Symbol(),"-",MagicNumber );
   return(0);
  }

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
   return(0);
  }

//+------------------------------------------------------------------+
//| Close Open Positions                                             |
//| Close all open positions                                         |
//+------------------------------------------------------------------+
void CloseOpenPositions()
{
   int cnt, err;
   
// First close losing trades
   
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS,MODE_TRADES);
      if ( OrderSymbol() != Symbol()) continue;
      if ( OrderMagicNumber() != MagicNumber)  continue;
      
        if(OrderType() == OP_BUY && OrderProfit() < 0)
        {
          if (OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Violet))
          {
            Print("Buy Order closed for " + Symbol() + " at " + Bid + ".");
          }
          else
          {
            err=GetLastError();
            Print("Error closing order : (", err , ") " + ErrorDescription(err));
          }
        }
        if(OrderType() == OP_SELL && OrderProfit() < 0)
        {
          if (OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Violet))
          {
            Print("Sell Order closed for " + Symbol() + " at " + Ask + ".");
          }
          else
          {
            err=GetLastError();
            Print("Error closing order : (", err , ") " + ErrorDescription(err));
          }
        }
   }
   
// Then close winning trades
   
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS,MODE_TRADES);
      if ( OrderSymbol() != Symbol()) continue;
      if ( OrderMagicNumber() != MagicNumber)  continue;
      
        if(OrderType() == OP_BUY && OrderProfit() > 0)
        {
          Sleep(PauseSeconds*MillisPerSec);
          if (OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Gold))
          {
            Print("Buy Order closed for " + Symbol() + " at " + Bid + ".");
          }
          else
          {
            err=GetLastError();
            Print("Error closing order : (", err , ") " + ErrorDescription(err));
          }
        }
        if(OrderType() == OP_SELL && OrderProfit() > 0)
        {
          Sleep(PauseSeconds*MillisPerSec);
          if (OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Gold))
          {
            Print("Sell Order closed for " + Symbol() + " at " + Ask + ".");
          }
          else
          {
            err=GetLastError();
            Print(" Error closing order : (", err , ") " + ErrorDescription(err));
          }
        }
   }

}

//+------------------------------------------------------------------------+
//| counts the number of open positions                                    |
//| type BUY returns number of long positions                              |
//| type SELL returns number of short positions                            |
//| type BOTH returns number of long and short positions                   |
//+------------------------------------------------------------------------+

int CheckOpenPositions(string type)
{
   int cnt, NumPositions;
   int NumBuyTrades, NumSellTrades;   // Number of buy and sell trades in this symbol
   
   NumBuyTrades = 0;
   NumSellTrades = 0;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol() != Symbol()) continue;
      if ( OrderMagicNumber() != MagicNumber)  continue;
      if(OrderType() == OP_BUY )
      {
        NumBuyTrades++;
      }
      else if(OrderType() == OP_SELL)
      {
        NumSellTrades++;
      }
             
   }
   NumPositions = NumBuyTrades + NumSellTrades;
   if (type == "BUY") return (NumBuyTrades);
   if (type == "SELL") return (NumSellTrades);
   return (NumPositions);
}

//+------------------------------------------------------------------+
//| GetProfit                                                        |
//| Return Open Profit from all open positions                       |
//+------------------------------------------------------------------+
double GetProfit( )
{
   int i;
   double   openProfit = 0;

   openProfit = 0;

   for(i=OrdersTotal()-1;i>=0;i--)
   {
      OrderSelect(i, SELECT_BY_POS );
      if ( OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber )
      {
          openProfit = openProfit + MathRound(OrderProfit()/MarketInfo(Symbol(),MODE_TICKVALUE)*10);
      }
   }
   return (openProfit);
}

//+------------------------------------------------------------------+
//| OpenBuyOrder                                                     |
//+------------------------------------------------------------------+
void OpenBuyOrder()
{
   int err;
   int ticket;

   ticket = OrderSend(Symbol(),OP_BUY,lotMM,Ask,Slippage,0,0,setup,MagicNumber,0,Blue);
   if(ticket<=0)
   {
      err = GetLastError();
      Print("Error opening BUY order [" + setup + "]: (" + err + ") " + ErrorDescription(err)); 
   }
}

//+------------------------------------------------------------------+
//| OpenSellOrder                                                    |
//+------------------------------------------------------------------+
void OpenSellOrder()
{
   int err;
   int ticket;
   
   ticket = OrderSend(Symbol(),OP_SELL,lotMM,Bid,Slippage,0,0,setup,MagicNumber,0,Red);
   if(ticket<=0)
   {
      err = GetLastError();
      Print("Error opening Sell order [" + setup + "]: (" + err + ") " + ErrorDescription(err)); 
   }
}

//+------------------------------------------------------------------+
//| Check  Profit                                                    |
//| Output comment showing progit, longs, shorts, etc                |
//| If profit target is reached close all open positions             |
//+------------------------------------------------------------------+
void CheckProfit()
{
   double Profit;
   int openLongs,openShorts;
   
   Profit = GetProfit();
   if ( Profit >= profitTarget ) 
   {
       CloseOpenPositions();
   }
//   else
//   {
//       openLongs = CheckOpenPositions("BUY");
//       openShorts = CheckOpenPositions("SELL");
//       Comment(" Server time is ",TimeToStr(CurTime()),
//               "\n",
//               "\n","                  Open p&l  = ",Profit,
//               "\n","                  Long      = ",openLongs, 
//               "\n","                  Short     = ",openShorts, 
//               "\n",
//               "\n","                  Balance   = ",AccountBalance(),
//               "\n","                  Equity    = ",AccountEquity(),
//               "\n","                  Margin    = ",AccountMargin(),
//               "\n","                  Free mrg  = ",AccountFreeMargin());
//    }
}

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
//---- 


//---- test if we want to shutdown

   if (shutdownGrid )         // close all orders. then exit.. there is nothing more to do
   {
      CloseOpenPositions();
      return(0);
   }
   
   TunnelSize = ((2*(Ask-Bid)/Point)+TunnelWidth);
   
// Check for new trade cycle
// First check if profit target is reached
// If yes then there will be no open positions
// So a new trade cycle will begin
    
   CheckProfit();
   currentOpen = CheckOpenPositions("BOTH");
   if (currentOpen == 0)
   {
// Start trades based on confirmation direction, was daily

      if (CheckDirection() == 0) return(0);
      if (CheckDirection() == 1)
      {
         OK2Buy = true;
         OK2Sell = false;
         FirstDirSell = false;
      }
      if (CheckDirection() == -1)
      {
         OK2Buy = false;
         OK2Sell = true;
         FirstDirSell = true;
      }
      if (OK2Buy)
      {
         startBuyRate = Ask ;
         startSellRate = Bid - TunnelSize*Point;
      }
      if (OK2Sell)
      {
         startSellRate = Bid ;
         startBuyRate = Bid + TunnelSize*Point;
      }
      
   }
   else
   {
     OK2Buy = true;
     OK2Sell = true;
   }
   
// Determine how many lots for next trade based on current number of open positions

   lotMM = Lots * MathPow(HedgeBase,currentOpen);
   if (lotMM == 0) return (0);
   
// Determine if next trade should be long or short based on current number of open positions

  myWantLongs = true;
  if (MathMod(currentOpen,2) > 0.1) myWantLongs = false;
   
   if (FirstDirSell) myWantLongs = !myWantLongs;   // added to match starting trade direction
	if (myWantLongs)
	{
	   if (Ask >=startBuyRate )
	   {

        OpenBuyOrder();
	   }
	}
	else
	{
	   if (Bid <= startSellRate)
	   {
        OpenSellOrder();
	   }
	}
	
   return(0);
}

//+------------------------------------------------------------------+

Profitability Reports

PERFORMANCE BY SYMBOL

Expected payoff

Average expected payoff across the available backtests for each symbol.

Positive Negative
14 reports
USD/JPY Jul 2025 - Sep 2025
1.09
Total Trades 910
Won Trades 499
Lost trades 411
Win Rate 54.84 %
Expected payoff 1.25
Gross Profit 13095.01
Gross Loss -11960.38
Total Net Profit 1134.63
-100%
-50%
0%
50%
100%
GBP/CAD Oct 2025 - Feb 2026
1.03
Total Trades 463
Won Trades 255
Lost trades 208
Win Rate 55.08 %
Expected payoff 1.33
Gross Profit 22046.15
Gross Loss -21428.40
Total Net Profit 617.75
-100%
-50%
0%
50%
100%
GBP/AUD Oct 2025 - Feb 2026
0.75
Total Trades 222
Won Trades 122
Lost trades 100
Win Rate 54.95 %
Expected payoff -25.11
Gross Profit 16523.75
Gross Loss -22097.57
Total Net Profit -5573.82
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.69
Total Trades 289
Won Trades 162
Lost trades 127
Win Rate 56.06 %
Expected payoff -16.89
Gross Profit 10943.01
Gross Loss -15825.28
Total Net Profit -4882.27
-100%
-50%
0%
50%
100%
USD/CAD Oct 2024 - Jan 2025
0.63
Total Trades 156
Won Trades 85
Lost trades 71
Win Rate 54.49 %
Expected payoff -20.38
Gross Profit 5515.13
Gross Loss -8693.74
Total Net Profit -3178.61
-100%
-50%
0%
50%
100%
NZD/USD Jul 2025 - Sep 2025
0.63
Total Trades 223
Won Trades 119
Lost trades 104
Win Rate 53.36 %
Expected payoff -23.42
Gross Profit 8845.90
Gross Loss -14069.15
Total Net Profit -5223.25
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
0.58
Total Trades 86
Won Trades 43
Lost trades 43
Win Rate 50.00 %
Expected payoff -56.79
Gross Profit 6643.93
Gross Loss -11528.02
Total Net Profit -4884.09
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
0.57
Total Trades 109
Won Trades 59
Lost trades 50
Win Rate 54.13 %
Expected payoff -47.98
Gross Profit 7016.77
Gross Loss -12246.62
Total Net Profit -5229.85
-100%
-50%
0%
50%
100%
AUD/USD Oct 2024 - Jan 2025
0.49
Total Trades 102
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -51.27
Gross Profit 5054.21
Gross Loss -10283.42
Total Net Profit -5229.21
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.49
Total Trades 85
Won Trades 46
Lost trades 39
Win Rate 54.12 %
Expected payoff -53.46
Gross Profit 4366.84
Gross Loss -8910.55
Total Net Profit -4543.71
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
0.42
Total Trades 82
Won Trades 44
Lost trades 38
Win Rate 53.66 %
Expected payoff -384.29
Gross Profit 22612.52
Gross Loss -54124.07
Total Net Profit -31511.55
-100%
-50%
0%
50%
100%
USD/CAD Jul 2025 - Sep 2025
0.38
Total Trades 46
Won Trades 25
Lost trades 21
Win Rate 54.35 %
Expected payoff -69.05
Gross Profit 1952.02
Gross Loss -5128.24
Total Net Profit -3176.22
-100%
-50%
0%
50%
100%
EUR/USD Oct 2025 - Feb 2026
0.32
Total Trades 37
Won Trades 13
Lost trades 24
Win Rate 35.14 %
Expected payoff -30.65
Gross Profit 535.32
Gross Loss -1669.55
Total Net Profit -1134.23
-100%
-50%
0%
50%
100%
AUD/USD Oct 2025 - Feb 2026
0.14
Total Trades 12
Won Trades 6
Lost trades 6
Win Rate 50.00 %
Expected payoff -378.79
Gross Profit 723.45
Gross Loss -5268.90
Total Net Profit -4545.45
-100%
-50%
0%
50%
100%

Comments