ema_crossmod

Author: Coders Guru
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 strategy
Indicators Used
Moving average indicator
0 Views
0 Downloads
0 Favorites

Profitability Reports

AUD/USD Oct 2024 - Jan 2025
7.00 %
Total Trades 20
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -478.25
Gross Profit 695.50
Gross Loss -10260.50
Total Net Profit -9565.00
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
9.00 %
Total Trades 42
Won Trades 40
Lost trades 2
Win Rate 0.95 %
Expected payoff -153.99
Gross Profit 634.50
Gross Loss -7102.00
Total Net Profit -6467.50
-100%
-50%
0%
50%
100%
ema_crossmod
//+------------------------------------------------------------------+
//|                                                  EMA_CROSS_2.mq4 |
//|                                                      Coders Guru |
//|                                         http://www.forex-tsd.com |
//+------------------------------------------------------------------+
// ultima versiune cu micro lots! H1 si D1

#property copyright "Coders Guru"
#property link      "http://www.forex-tsd.com"
#define MAGICMA  20060301

//---- Trades limits
extern double    TakeProfit=160;
extern double    TrailingStop=20;
extern double    StopLoss=70;
extern bool      UseStopLoss = false;

//---- EMAs paris
extern int ShortEma = 10; 
extern int LongEma = 80;

//---- Crossing options
extern bool immediate_trade = true; //Open trades immediately or wait for cross.
extern bool reversal = true; //Use the originally reversal crossing method or not

//---- Money Management
extern double Lots = 1;
extern bool MM = true; //Use Money Management or not
extern bool AccountIsMicro = false; //Use Micro-Account or not
extern int Risk = 10; //10%

extern bool Show_Settings = true;

//---- Global varaibles
static int TimeFrame = 0;


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---- 
   if(Show_Settings) Print_Details();
   else Comment("");
//----
   
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
      TimeFrame=Period(); //Prevent counting the cross while the user changing the timeframe
//----
   return(0);
  }
  
bool isNewSumbol(string current_symbol)
  {
   //loop through all the opened order and compare the symbols
   int total  = OrdersTotal();
   for(int cnt = 0 ; cnt < total ; cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      string selected_symbol = OrderSymbol();
      if (current_symbol == selected_symbol)
      return (False);
    }
    return (True);
}

int Crossed (double line1 , double line2)
   {
      static int last_direction = 0;
      static int current_direction = 0;
      
      if(TimeFrame!=Period())
      {
         TimeFrame=Period();
         return (0);
      }
      
      if(line1>line2)current_direction = 1; //up
      if(line1<line2)current_direction = 2; //down
      
      if(immediate_trade==false)
      {
         if(last_direction == 0) //first use
         {
               last_direction = current_direction;
               return(0);
         }
      }

      if(current_direction != last_direction) //changed 
      {
            last_direction = current_direction;
            return (last_direction);
      }
      else
      {
            return (0); //not changed
      }
   }

//--- Bassed on Alex idea! More ideas are coming
double LotSize()
{
     double lotMM = MathCeil(AccountFreeMargin() *  Risk / 1000) / 100;
	  
	  if(AccountIsMicro==false) //normal account
	  {
	     if (lotMM < 0.1) lotMM = Lots;
	     if ((lotMM > 0.5) && (lotMM < 1)) lotMM=0.5;
	     if (lotMM > 1.0) lotMM = MathCeil(lotMM);
	     if  (lotMM > 100) lotMM = 100;
	  }
	  else //micro account
	  {
	     if (lotMM < 0.01) lotMM = Lots;
	     if (lotMM > 1.0) lotMM = MathCeil(lotMM);
	     if  (lotMM > 100) lotMM = 100;
	  }
	  
	  return (lotMM);
}

string BoolToStr ( bool value)
{
   if(value) return ("True");
   else return ("False");
}
void Print_Details()
{
   string sComment = "";
   string sp = "----------------------------------------\n";
   string NL = "\n";

   sComment = sp;
   sComment = sComment + "TakeProfit=" + DoubleToStr(TakeProfit,0) + " | ";
   sComment = sComment + "TrailingStop=" + DoubleToStr(TrailingStop,0) + " | ";
   sComment = sComment + "StopLoss=" + DoubleToStr(StopLoss,0) + " | "; 
   sComment = sComment + "UseStopLoss=" + BoolToStr(UseStopLoss) + NL;
   sComment = sComment + sp;
   sComment = sComment + "immediate_trade=" + BoolToStr(immediate_trade) + " | ";
   sComment = sComment + "reversal=" + BoolToStr(reversal) + NL;
   sComment = sComment + sp;
   sComment = sComment + "Lots=" + DoubleToStr(Lots,0) + " | ";
   sComment = sComment + "MM=" + BoolToStr(MM) + " | ";
   sComment = sComment + "Risk=" + DoubleToStr(Risk,0) + "%" + NL;
   sComment = sComment + sp;
  
   Comment(sComment);
}

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//---- 

   int cnt, ticket, total;
   double SEma, LEma;
   
   string comment = "";
   if(reversal==true) comment = "EMA_CROSS_Counter-Trend";
   if(reversal==false) comment = "EMA_CROSS_Trend-Following";

   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return(0);  // check TakeProfit
     }
     
   SEma = iMA(NULL,0,ShortEma,0,MODE_EMA,PRICE_CLOSE,0);
   LEma = iMA(NULL,0,LongEma,0,MODE_EMA,PRICE_CLOSE,0);
   
   
   
   static int isCrossed  = 0;
   isCrossed = Crossed (LEma,SEma);
   
   if(reversal==false)
   {
      if(isCrossed==1) isCrossed=2;
      if(isCrossed==2) isCrossed=1;
   }
   
   if(MM==true) Lots = LotSize(); //Adjust the lot size
  
   
   total  = OrdersTotal();

   if(total < 2 || isNewSumbol(Symbol())) //I have modified the if condition too: it was total<1 (orBanAway aka cucurucu)
     {
       if(isCrossed == 1)
         {
            
            if(UseStopLoss)
               ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point,comment,MAGICMA,0,Green);
            else
               ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,comment,MAGICMA,0,Green);
            
            if(ticket>0)
              {
               if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
              }
            else Print("Error opening BUY order : ",GetLastError()); 
//######################################################################   the added code starts here         
            if(UseStopLoss)
               ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point,comment,MAGICMA,0,Red);
            else
               ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,comment,MAGICMA,0,Red);
            
            if(ticket>0)
              {
               if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
              }
            else Print("Error opening SELL order : ",GetLastError());             
//######################################################################   ends here          
            return(0);
         }
         if(isCrossed == 2)
         {
            if(UseStopLoss)
               ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point,comment,MAGICMA,0,Red);
            else
               ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,comment,MAGICMA,0,Red);
            
            if(ticket>0)
              {
               if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
              }
            else Print("Error opening SELL order : ",GetLastError()); 
//###################################################################### the added code starts here  
            if(UseStopLoss)
               ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point,comment,MAGICMA,0,Green);
            else
               ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,comment,MAGICMA,0,Green);
            
            if(ticket>0)
              {
               if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
              }
            else Print("Error opening BUY order : ",GetLastError()); 
//######################################################################  ends here   
            return(0);
         }
         return(0);
     }
     
     
   for(cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

      if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
        {
         if(OrderType()==OP_BUY)   // long position is opened
           {
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
           }
         else // go to short position
           {
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
           }
        }
     }
   return(0);
  }
//+------------------------------------------------------------------+

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 ---