Author: Copyright � 2007, Hartono Setiono
Profit factor:
0.86

This script is designed to manage trades using a "hedging" logic, where the system simultaneously opens both a Buy and a Sell position on a specific currency pair. The goal is to create a balanced exposure where the profits from one side of the trade are intended to offset the losses of the other, with specific rules governing when to close these positions.

Core Trading Behavior

At the start of each new trading day (specifically at 00:00 server time), the system automatically opens two opposite positions: a Buy order and a Sell order. Both use the same volume (Lot Size). This means that, initially, the net market exposure is neutral.

Management Modes

The script offers three distinct behaviors for how it handles these open positions based on your settings:

  • Mode 0 (End of Day Target): The system holds the positions until the end of the day. It will only close the trades if the total combined profit of all open positions is positive. This is a "wait and see" approach where the goal is to finish the day in the green.
  • Mode 1 (Real-Time Take Profit): The system constantly monitors the total profit of the open positions. As soon as the cumulative profit reaches your defined target amount, it closes all active trades for that session.
  • Mode 2 (Sequential Profit Taking): This is a more dynamic approach. It looks at the performance of individual positions. If one side becomes significantly profitable (exceeding a minimum profit threshold), the script will close that winning position and partially close the opposite losing position to lock in some gains.

Technical Safeguards

  • Smart Identification: The script uses "Magic Numbers" (unique identifiers) combined with the current date. This ensures that the script only manages trades it opened itself and won't accidentally interfere with your other manual trades or different automated systems.
  • Error Handling: When opening orders, the script includes a retry mechanism. If the broker is temporarily busy or the connection flickers, the script will pause briefly and try again several times rather than simply giving up.
  • Weekend Protection: The system is programmed to ignore weekend trading days, focusing its primary logic on standard weekdays.

Summary for the User

Essentially, this script is a "set-and-forget" hedging tool. It enters the market in both directions at once and then follows your chosen strategy—either waiting for a positive total at the end of the day, closing as soon as a profit target is hit, or intelligently trimming positions as they move in your favor.

Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategy
13 Views
0 Downloads
0 Favorites
TrueHedge1
//+------------------------------------------------------------------+
//|                                                    TrueHedge.mq4 |
//|                                               by Hartono Setiono |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007,  Hartono Setiono"
#property link      "http://www.mitrakom.com"
#include <stdlib.mqh>
#include <stderror.mqh>
extern double LotSize=2;
extern int    Slippage=3;
extern double StopLoss=0;
extern double TakeProfit=100;
extern int    GMTShift=0;
extern int    OpenPosHandler=0; 
extern int    MinInitialOrderProfit=500;

/* 
OpenPosHandler:
0:never close till positif at the end of the day
1:check everytime for takeProfit Level
2:wait till next end of the day and close
*/
int           ticket;
int           OpenBuyOrders = 0;
int           OpenSellOrders = 0;
int           LastMN=0; //Last Magic Number
int           TodayMN=0; //Today Magic Number;
int           maxloop=25; // maximum number of attempts to handle errors
int           MNFactor=100000;
int           MagicNumber=123;
string        EAName="TrueHedge 0.1";


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
  switch (OpenPosHandler)
  {
    case 0:
    case 1:
    case 2: break;
    default:OpenPosHandler=0;
  }
  return(0);
}


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

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
  TodayMN = MagicNumber*MNFactor+ (Year() % 100)*10000 + Month()*100 + Day();
  if(DayOfWeek()==0 || DayOfWeek()==6) return(0);
  if(Hour()+GMTShift==23 && Minute()==00) 
  {
    if (OpenPosHandler==0) HandleOpenPositions(3);
    if (OpenPosHandler==2) HandleOpenPositions(4);
    HandleOpenPositions(2);
  }
  
  LastMN=GetLastMN();
    
  if(Hour()+GMTShift==0 && Minute()==0 && LastMN==0) 
  {
    OpenOrder(OP_BUY,LotSize,Ask,Slippage,0,0,EAName,TodayMN,0,Blue);
    OpenOrder(OP_SELL,LotSize,Bid,Slippage,0,0,EAName,TodayMN,0,Red);
    LastMN=TodayMN;
  }
  if (OpenPosHandler==1) HandleOpenPositions(1);
  return(0);
}
//+------------------------------------------------------------------+

int HandleOpenPositions(int id)
{
   int cnt, OrderMN;
   double lotsi;
   
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES);
      lotsi=OrderLots();
      OrderMN=OrderMagicNumber();

      if ( OrderSymbol() != Symbol()) continue;
      if ( OrderMN/MNFactor != MagicNumber)  continue;
      
      if (id==1)
      if (OrderMN != LastMN)
      {
        if (MNProfit(OrderMN)>TakeProfit)
        {
          CloseLongs(OrderMN);
          CloseShorts(OrderMN);
        }
      }

      if (id==2)
      {
        if (OrderMN==LastMN)
        {
          if (OrderType() == OP_BUY && OrderProfit()>MinInitialOrderProfit)
          {
            OrderClose(OrderTicket(),lotsi,Bid,Slippage,Blue);
            CloseShorts(OrderMN, lotsi/2);
          }
      
          if (OrderType() == OP_SELL && OrderProfit()>MinInitialOrderProfit)
          {
            OrderClose(OrderTicket(),lotsi,Ask,Slippage,Red);
            CloseLongs(OrderMN, lotsi/2);
          }
        }
      }

      if (id==3)
      if (OrderMN != LastMN)
      {
        if (MNProfit(OrderMN)>TakeProfit)
        {
          CloseLongs(OrderMN);
          CloseShorts(OrderMN);
        }
      }
      if (id==4)
      if (OrderMN != LastMN)
      {
        CloseLongs(OrderMN);
        CloseShorts(OrderMN);
      }
   }
   return(0);
}

double MNProfit(int MagicNumber)
{
   int cnt;
   double profit=0;
   
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol() != Symbol()) continue;
      if ( OrderMagicNumber() != MagicNumber)  continue;
      profit=profit+OrderProfit();
   }
   return(profit);
}

double MNDirection(int MagicNumber)
{
   int cnt;
   double lotsi=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 ) lotsi=lotsi+OrderLots();
      if ( OrderType()==OP_SELL ) lotsi=lotsi-OrderLots();
   }
   return(lotsi);
}

int GetLastMN()
{
   int cnt, OrderMN, LastMN=0;
   double lotsi;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES);
      OrderMN=OrderMagicNumber();
      if ( OrderSymbol() != Symbol()) continue;
      if (OrderMN/MNFactor != MagicNumber)  continue;

      lotsi=MNDirection(OrderMN);
      if (lotsi==0) { LastMN=OrderMN; break;}
   }
   return(LastMN);
}

int OpenOrder(int pType,double pLots,double pLevel,int sp, int sl, int tp,string pComment,int pMagic,datetime pExpiration,color pColor)
{
  int ticket=0;
  int err=0;
  int c = 0;
  int NumberOfTries = 10;
  switch (pType)
  {
      case OP_BUY:
         for(c = 0 ; c < NumberOfTries ; c++)
         {  
            RefreshRates();
            ticket=OrderSend(Symbol(),OP_BUY,pLots,Ask,sp,StopLong(Bid,sl),TakeLong(Bid,tp),pComment,pMagic,pExpiration,pColor);
            if (ticket > 0) break;
            err=GetLastError();
            if(err==0)
            { 
               break;
            }
            else
            {
               if(err==4 || err==137 ||err==146 || err==136) //Busy errors
               {
                  Sleep(5000);
                  continue;
               }
               else //normal error
               {
                  Print("Error Code= ", err);
                  break;
               }  
            }
         } 
         break;
      case OP_SELL:
         for(c = 0 ; c < NumberOfTries ; c++)
         {
            RefreshRates();
            ticket=OrderSend(Symbol(),OP_SELL,pLots,Bid,sp,StopShort(Ask,sl),TakeShort(Ask,tp),pComment,pMagic,pExpiration,pColor);
            if (ticket > 0) break;
            err=GetLastError();
            if(err==0)
            { 
               break;
            }
            else
            {
               if(err==4 || err==137 ||err==146 || err==136) //Busy errors
               {
                  Sleep(5000);
                  continue;
               }
               else //normal error
               {
                  Print("Error Code= ", err);
                  break;
               }  
            }
         } 
         break;
  } 
  
  return(ticket);
}  



void CloseLongs(int MagicNumber, double clots=0)
{
 int trade;
 double olots;
 
 for(trade=OrdersTotal()-1;trade>=0;trade--)
 {
  if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES)==false) continue;
  if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber) continue;
  if(OrderType()!=OP_BUY) continue;
   
  olots=OrderLots();
  if (clots==0) clots=olots;
  OrderClose(OrderTicket(),clots,Bid,Slippage,Blue);

  if(olots!=clots && StopLoss !=0)
  ModifyStopLoss(OrderTicket(),StopLong(Bid,StopLoss));
 }//for
}

void CloseShorts(int MagicNumber, double clots=0)
{
 int trade;
 double olots;
 for(trade=OrdersTotal()-1;trade>=0;trade--)
 {
  if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES)==false) continue;
  if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber) continue;
  if(OrderType()!=OP_SELL) continue;
  
  olots=OrderLots();
  if (clots==0) clots=olots; 
  OrderClose(OrderTicket(),clots,Ask,Slippage,Red);

  if(olots!=clots && StopLoss !=0)
  ModifyStopLoss(OrderTicket(),StopShort(Ask,StopLoss));
 }//for
}

double StopLong(double price,int stop)
{
 if(stop==0)
  return(0);
 else
  return(price-(stop*Point));
}

double StopShort(double price,int stop)
{
 if(stop==0)
  return(0);
 else
  return(price+(stop*Point));
}

double TakeLong(double price,int take)
{
 if(take==0)
  return(0);
 else
  return(price+(take*Point));
}

double TakeShort(double price,int take)
{
 if(take==0)
  return(0);
 else
  return(price-(take*Point));
}


int HandleTrailingStop(int type, int ticket, double open_price, double cur_sl, int TrailingStopType, int TrailingStop)
{
	double pt, TS = 0, myAsk, myBid;


	if (type == OP_BUY)
	{
		myBid = MarketInfo(Symbol(),MODE_BID);
		switch (TrailingStopType)
		{
			case 1: 
				pt = Point * StopLoss;
				if (myBid - cur_sl > pt) 
					ModifyStopLoss(ticket, myBid - pt);
				break;
				
			case 2: 
				pt = Point * TrailingStop;
				if (myBid - open_price > pt && (cur_sl < myBid - pt || cur_sl == 0))
					ModifyStopLoss(ticket, myBid - pt);
				break;

		}
		return(0);
	}


	else if (type ==  OP_SELL)
	{
		myAsk = MarketInfo(Symbol(),MODE_ASK);
		switch (TrailingStopType)
		{
			case 1: 
				pt = Point * StopLoss;
				if (cur_sl - myAsk > pt) 
					ModifyStopLoss(ticket, myAsk+pt);
				break;
				
			case 2: 
				pt = Point * TrailingStop;
				if (open_price - myAsk > pt && (cur_sl > myAsk + pt || cur_sl == 0))
					ModifyStopLoss(ticket, myAsk+pt);
				break;
				
		 }
	 }
	 return(0);
}

int ModifyStopLoss(int ticket, double stoploss)
{
    int Cnt, digits, err;
    string symbol;
    double myStopLoss;
    
    OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
    symbol = OrderSymbol();
    digits = MarketInfo(symbol,MODE_DIGITS);
    if (digits > 0)
    {
			 myStopLoss = NormalizeDouble(stoploss,digits);
    }
    Cnt=0;
    while (Cnt < 3)
    {
       if (OrderModify(ticket,OrderOpenPrice(),myStopLoss,OrderTakeProfit(),0,Aqua))
       {
         Cnt = 3;
       }
       else
       {
          err=GetLastError();
          Print(Cnt," Error modifying order : (", err , ") " + ErrorDescription(err));
         if (err>0) Cnt++;
       }
    }
}

Profitability Reports

PERFORMANCE BY SYMBOL

Expected payoff

Average expected payoff across the available backtests for each symbol.

Positive Negative
15 reports
GBP/USD Oct 2024 - Jan 2025
1.00
Total Trades 24
Won Trades 12
Lost trades 12
Win Rate 50.00 %
Expected payoff -28.00
Gross Profit 152400.00
Gross Loss -153072.00
Total Net Profit -672.00
-100%
-50%
0%
50%
100%
USD/CAD Oct 2024 - Jan 2025
1.00
Total Trades 36
Won Trades 18
Lost trades 18
Win Rate 50.00 %
Expected payoff -23.10
Gross Profit 172238.60
Gross Loss -173070.16
Total Net Profit -831.56
-100%
-50%
0%
50%
100%
GBP/AUD Oct 2025 - Feb 2026
0.99
Total Trades 22
Won Trades 11
Lost trades 11
Win Rate 50.00 %
Expected payoff -61.19
Gross Profit 210644.53
Gross Loss -211990.69
Total Net Profit -1346.16
-100%
-50%
0%
50%
100%
GBP/USD Jul 2025 - Sep 2025
0.98
Total Trades 12
Won Trades 6
Lost trades 6
Win Rate 50.00 %
Expected payoff -26.00
Gross Profit 17298.00
Gross Loss -17610.00
Total Net Profit -312.00
-100%
-50%
0%
50%
100%
USD/CAD Jul 2025 - Sep 2025
0.98
Total Trades 36
Won Trades 18
Lost trades 18
Win Rate 50.00 %
Expected payoff -24.47
Gross Profit 51588.85
Gross Loss -52469.60
Total Net Profit -880.75
-100%
-50%
0%
50%
100%
USD/JPY Jul 2025 - Sep 2025
0.98
Total Trades 34
Won Trades 17
Lost trades 17
Win Rate 50.00 %
Expected payoff -40.01
Gross Profit 87850.70
Gross Loss -89211.04
Total Net Profit -1360.34
-100%
-50%
0%
50%
100%
GBP/CAD Oct 2025 - Feb 2026
0.98
Total Trades 22
Won Trades 11
Lost trades 11
Win Rate 50.00 %
Expected payoff -51.72
Gross Profit 55971.95
Gross Loss -57109.78
Total Net Profit -1137.83
-100%
-50%
0%
50%
100%
AUD/USD Oct 2024 - Jan 2025
0.96
Total Trades 48
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -34.00
Gross Profit 44864.00
Gross Loss -46496.00
Total Net Profit -1632.00
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
0.94
Total Trades 48
Won Trades 23
Lost trades 25
Win Rate 47.92 %
Expected payoff -34.00
Gross Profit 23700.00
Gross Loss -25332.00
Total Net Profit -1632.00
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.93
Total Trades 10
Won Trades 5
Lost trades 5
Win Rate 50.00 %
Expected payoff -167.20
Gross Profit 22761.18
Gross Loss -24433.18
Total Net Profit -1672.00
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.92
Total Trades 44
Won Trades 22
Lost trades 22
Win Rate 50.00 %
Expected payoff -26.00
Gross Profit 13470.00
Gross Loss -14614.00
Total Net Profit -1144.00
-100%
-50%
0%
50%
100%
EUR/USD Oct 2025 - Feb 2026
0.81
Total Trades 24
Won Trades 12
Lost trades 12
Win Rate 50.00 %
Expected payoff -86.00
Gross Profit 8876.00
Gross Loss -10940.00
Total Net Profit -2064.00
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
0.76
Total Trades 28
Won Trades 11
Lost trades 17
Win Rate 39.29 %
Expected payoff -28.00
Gross Profit 2456.00
Gross Loss -3240.00
Total Net Profit -784.00
-100%
-50%
0%
50%
100%
AUD/USD Oct 2025 - Feb 2026
0.66
Total Trades 36
Won Trades 17
Lost trades 19
Win Rate 47.22 %
Expected payoff -78.00
Gross Profit 5540.00
Gross Loss -8348.00
Total Net Profit -2808.00
-100%
-50%
0%
50%
100%
GBP/CAD Jul 2025 - Sep 2025
0.00
Total Trades 17
Won Trades 0
Lost trades 17
Win Rate 0.00 %
Expected payoff -198.70
Gross Profit 0.00
Gross Loss -3377.98
Total Net Profit -3377.98
-100%
-50%
0%
50%
100%

Comments