HedgeTrade_BS_04

Author: OnTheRoad
Orders Execution
Checks for the total of closed ordersIt automatically opens orders when conditions are reachedChecks for the total of open ordersIt Closes Orders by itself
Indicators Used
Moving average indicator
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites

Profitability Reports

AUD/USD Oct 2024 - Jan 2025
93.00 %
Total Trades 800
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -0.41
Gross Profit 4504.80
Gross Loss -4833.90
Total Net Profit -329.10
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
63.00 %
Total Trades 798
Won Trades 422
Lost trades 376
Win Rate 0.53 %
Expected payoff -4.05
Gross Profit 5454.80
Gross Loss -8689.30
Total Net Profit -3234.50
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
80.00 %
Total Trades 798
Won Trades 457
Lost trades 341
Win Rate 0.57 %
Expected payoff -1.20
Gross Profit 3809.50
Gross Loss -4765.00
Total Net Profit -955.50
-100%
-50%
0%
50%
100%
HedgeTrade_BS_04
//+------------------------------------------------------------------+
//|                                             HedgeTrade_BS_04.mq4 |
//+------------------------------------------------------------------+

#property copyright "OnTheRoad"

#include <stdlib.mqh>

#define MAGICPROB  11010101122

#define UP          1
#define BUY         1
#define NUTRAL      0
#define SELL        -1
#define DOWN        -1

extern double TP_BUY                = 16;
extern double SL_BUY                = 66;


extern double TP_SELL               = 76;
extern double SL_SELL               = 68;


extern int TALL_TF  = 240;
extern int TALL_PER = 5 ;
extern int TALL_SHIFT = 1 ;


extern int TF_SEL                = 240;
extern int SLIPAGE               = 2;


extern double Lots               = 0.1;
extern double MaximumRisk        = 0.0002;
extern double DecreaseFactor     = 3;
extern double RiskFactor = 1000;
extern int    maxbuyorders = 100;
extern int    maxsellorders = 100;

extern double equity_dd_4x       = 0.8; //0.8;
extern double equity_gu_4x       = 1.2; //1.2;

static double equity_max ;
static int    last_trend ;
static double equity_base;

static datetime lastbar = 0;

int buycount = 1;
int sellcount = 1;

int init()
{

   lastbar = Time[0];//iTime(Symbol(),PERIOD_M5,0); //Time[0];
   
   last_trend = NUTRAL;
   equity_base = AccountEquity();
   equity_max = 0;
   
	return ;
}


bool NewBar()
{
   
   datetime curbar = iTime(Symbol(),TF_SEL,0);//Time[0];//
   if(lastbar!=curbar)
   {
      lastbar=curbar;
      return (true);
   }
   else
   {
      return(false);
   }
} 
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=OrdersHistoryTotal(); //HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
   
   int    dp=1;
   if ( Lots < 0.1 ) dp = 2;
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/RiskFactor,dp);
//---- calcuulate number of losses orders without a break
   if ( orders > 1 )
    if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         //----
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses/orders > 0.3) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,dp);
     }
//---- return lot size
   if(lot<Lots) lot=Lots;
   return(lot);
  }
  
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
  {

   int    res , trend;
   double tpb,slb,tps,sls;
   
   double equitynow = AccountEquity();
   
   if ( equitynow < equity_dd_4x * equity_max )
      {
         CLOSE_ALL( BUY ) ;
         CLOSE_ALL( SELL ) ;
         equity_max = 0;
      }
   else if ( equitynow > equity_gu_4x * equity_base ) 
      {
         CLOSE_ALL( BUY ) ;
         CLOSE_ALL( SELL ) ;
         equity_base = AccountEquity();
      }
   else if ( equitynow > equity_max ) equity_max = equitynow ;
   
   
   if(Bars<100 || IsTradeAllowed()==false) return;
   
    if (NewBar() == true)
      {

         Comment ( " \n lasttrend= " , last_trend , " ,trend = " , trend );
         
         if (( last_trend != trend )&&( trend != NUTRAL ))
            {
            last_trend = trend;
            CLOSE_ALL( BUY ) ;
            CLOSE_ALL( SELL ) ;
            }
      
      double tall = ( iMA(NULL,TALL_TF,TALL_PER,0,MODE_SMA,PRICE_HIGH,TALL_SHIFT) -  iMA(NULL,TALL_TF,TALL_PER,0,MODE_SMA,PRICE_LOW,TALL_SHIFT) ) ;
      tpb = NormalizeDouble(0.01 * TP_BUY * tall / Point , 0 ); if ( tpb < 7 ) tpb = 7;
      slb = NormalizeDouble(0.01 * SL_BUY * tall / Point , 0 ); if ( slb < 7 ) slb = 7;
      tps = NormalizeDouble(0.01 * TP_SELL * tall / Point , 0 ); if ( tps < 7 ) tps = 7 ;
      sls = NormalizeDouble(0.01 * SL_SELL * tall / Point , 0 ); if ( sls < 7 ) sls = 7 ;
      
      if(OrdersTotal() < maxsellorders) { res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,SLIPAGE,Bid+Point*sls,Bid-Point*tps,"",MAGICPROB,0,Red);}
      if(OrdersTotal() < maxbuyorders) { res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,SLIPAGE,Ask-Point*slb,Ask+Point*tpb,"",MAGICPROB,0,Blue);}
      }

      return;
      
  }
  
  
  
/////////////////////////////////////////////////////////////////////

   void CLOSE_ALL( int buysell )
   {
   int    myTyp;

   int i;

   // return;

   for( i=(OrdersTotal()-1); i>=0; i-- )
     {
      OrderSelect(i, SELECT_BY_POS);
      if(OrderMagicNumber()==MAGICPROB)
        {
         switch( OrderType() )
           {
            //Close opened long positions
            case OP_BUY      : if ( buysell == buycount ) CloseBuy("CLOSEEVERYTHING script  BUY");
            break;
   
            //Close opened short positions
            case OP_SELL     : if ( buysell == -sellcount ) CloseSell("CLOSEEVERYTHING script SELL");
            break;
           }
 
        }//magic
        
      Sleep(500);

     } //for
  
  } // closeeverything


void CloseBuy (string myInfo)
  {
   int gle;
   int cnt;
   
   int loopcount=0;
   
   while(true)
     {
      OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),2,White);
      gle=GetLastError();
      if(gle==0)
        {
         Print("CLOSE BUY "+myInfo+" Ticket="+OrderTicket()+" SL="+OrderStopLoss()+" TP="+OrderTakeProfit() );
         break;
        }
       else 
        {
         Print("-----ERROR----- CLOSE BUY PROFIT Bid="+MarketInfo(OrderSymbol(),MODE_BID)+" error="+gle+" "+ErrorDescription(gle));
         Sleep(500);
         RefreshRates();
        }

      loopcount++;
      if(loopcount>25)
        {
         Alert("Order failed to CLOSE - See Journal for errors");
         break;
        }
                     
     }//while
  
  }//closebuy


void CloseSell (string myInfo)
  {
   int gle;
   int cnt;
   
   int loopcount=0;
   
   while(true)
     {
      OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),2,Red);
      gle=GetLastError();
      if(gle==0)
        {
         Print("CLOSE SELL "+myInfo+" Ticket="+OrderTicket()+" SL="+OrderStopLoss()+" TP="+OrderTakeProfit() );
         break;
        }
      else 
        {
         Print("-----ERROR----- CLOSE SELL PROFIT Ask="+MarketInfo(OrderSymbol(),MODE_ASK)+" error="+gle+" "+ErrorDescription(gle));
         Sleep(500);
         RefreshRates();
        }
                    
      loopcount++;
      if(loopcount>25)
        {
         Alert("Order failed to CLOSE - See Journal for errors");
         break;
        }

     }//while                 

  }//closesell
    
//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---