//+------------------------------------------------------------------+
//|                                                    EURO-SELL.mq4 |
//|                                       Copyright © 2008, LEGRUPO. |
//|                                           http://www.legrupo.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, LEGRUPO."
#property link      "http://www.legrupo.com"

//+------------------------------------------------------------------+
//| EX4 imports                                                      |
//+------------------------------------------------------------------+
#include <stderror.mqh>
#include <stdlib.mqh>

extern double LotSize = 5.0;
extern int TakeProfit = 30;
extern int StopLoss = 60;
extern int HedgeDistance = 30;
extern int HourToTrade = 10;
extern int Slippage = 3;

extern bool UseMoneyManagement = false;
extern bool AccountIsMicro = false;
extern int Risk = 50; // risk in percentage % (10% of risk in this case)

int ExpertID = 988988;

int MagicNumber = 0;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   MagicNumber = MakeMagicNumber();
   if(UseMoneyManagement==true) {
      LotSize = DefineLotSize(); //Adjust the lot size     total
      if (LotSize > MarketInfo(Symbol(), MODE_MAXLOT)) {
         LotSize = MarketInfo(Symbol(), MODE_MAXLOT);
      }
   }
   
   if (Hour() == HourToTrade) {
         double price,hedge_price,hedge_tp,hedge_sl,sl,tp = 0.0;
         if (CountShorts(MagicNumber) == 0) {
            price = Bid;
            sl = price+StopLoss*Point;
            tp = price-TakeProfit*Point;
            int ticket_sell = OrderSend(Symbol(),OP_SELL,LotSize,price,Slippage,sl,tp,WindowExpertName(),MagicNumber,0,CLR_NONE);
            
            hedge_price = price+HedgeDistance*Point;
            hedge_tp = hedge_price+TakeProfit*Point;
            hedge_sl = hedge_price-StopLoss*Point;
            int hedge_buy = OrderSend(Symbol(), OP_BUYSTOP, LotSize,hedge_price,Slippage,hedge_sl,hedge_tp,WindowExpertName(),MagicNumber,0,CLR_NONE);
            if (hedge_buy < 0) {
               Alert(Symbol()," ",WindowExpertName()," Open BUYSTOP order error: ", ErrorDescription(GetLastError()));
            }
         }
   }
//----
   return(0);
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Calculate concurrent Long position                               |
//+------------------------------------------------------------------+
int CountLongs(int MagicNumber)
{
 int count=0;
 int trade;
 int trades=OrdersTotal();
 for(trade=0;trade<trades;trade++)
 {
  OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
  
  if( OrderSymbol()!=Symbol() || OrderMagicNumber() != MagicNumber )
   continue;
   
  if(OrderType()==OP_BUY)
   count++;
 }//for
 return(count);
}
//+------------------------------------------------------------------+
//| Calculate concurrent short position                              |
//+------------------------------------------------------------------+
int CountShorts(int MagicNumber)
{
 int count=0;
 int trade;
 int trades=OrdersTotal();
 for(trade=0;trade<trades;trade++)
 {
  OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
  
  if(OrderSymbol()!=Symbol() || OrderMagicNumber() != MagicNumber )
   continue;
   
  if(OrderType()==OP_SELL)
  count++;
 }//for
 return(count);
}
//+------------------------------------------------------------------+
//| Make Magic Number                                                |
//+------------------------------------------------------------------+
int MakeMagicNumber()
{
   int SymbolCode  = 0;
   int PeriodCode  = 0;
   int MagicNumber = 0; 
   
   //---- Symbol Code
        if( Symbol() == "AUDCAD" || Symbol() == "AUDCADm" ) { SymbolCode = 1000; }
   else if( Symbol() == "AUDJPY" || Symbol() == "AUDJPYm" ) { SymbolCode = 2000; }
   else if( Symbol() == "AUDNZD" || Symbol() == "AUDNZDm" ) { SymbolCode = 3000; }
   else if( Symbol() == "AUDUSD" || Symbol() == "AUDUSDm" ) { SymbolCode = 4000; }
   else if( Symbol() == "CHFJPY" || Symbol() == "CHFJPYm" ) { SymbolCode = 5000; }
   else if( Symbol() == "EURAUD" || Symbol() == "EURAUDm" ) { SymbolCode = 6000; }
   else if( Symbol() == "EURCAD" || Symbol() == "EURCADm" ) { SymbolCode = 7000; }
   else if( Symbol() == "EURCHF" || Symbol() == "EURCHFm" ) { SymbolCode = 8000; }
   else if( Symbol() == "EURGBP" || Symbol() == "EURGBPm" ) { SymbolCode = 9000; }
   else if( Symbol() == "EURJPY" || Symbol() == "EURJPYm" ) { SymbolCode = 1000; }
   else if( Symbol() == "EURUSD" || Symbol() == "EURUSDm" ) { SymbolCode = 1100; }
   else if( Symbol() == "GBPCHF" || Symbol() == "GBPCHFm" ) { SymbolCode = 1200; }
   else if( Symbol() == "GBPJPY" || Symbol() == "GBPJPYm" ) { SymbolCode = 1300; }
   else if( Symbol() == "GBPUSD" || Symbol() == "GBPUSDm" ) { SymbolCode = 1400; }
   else if( Symbol() == "NZDJPY" || Symbol() == "NZDJPYm" ) { SymbolCode = 1500; }
   else if( Symbol() == "NZDUSD" || Symbol() == "NZDUSDm" ) { SymbolCode = 1600; }
   else if( Symbol() == "USDCAD" || Symbol() == "USDCADm" ) { SymbolCode = 1700; }
   else if( Symbol() == "USDCHF" || Symbol() == "USDCHFm" ) { SymbolCode = 1800; }
   else if( Symbol() == "USDJPY" || Symbol() == "USDJPYm" ) { SymbolCode = 1900; }
                     
   //---- Calculate MagicNumber
   MagicNumber = ExpertID+SymbolCode;
   return(MagicNumber);
}

double DefineLotSize() {
   double lotMM = MathCeil(AccountFreeMargin() *  Risk / 1000) / 100;
   if(AccountIsMicro==false) { //normal account
      if (lotMM < 0.1) lotMM = LotSize;
      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 = LotSize;
      if (lotMM > 1.0) lotMM = MathCeil(lotMM);
      if  (lotMM > 100) lotMM = 100;
   }
   return (lotMM);
}

bool LastOrderSelect(int pool, int type1, int type2 = -1)
{
  datetime tm = -1;
  int ticket = -1;

  if (pool == MODE_TRADES)
  {
    int cnt = OrdersTotal();
    for (int i=0; i < cnt; i++) 
    {
      if (!OrderSelect(i, SELECT_BY_POS, pool)) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
      int type = OrderType();
      if (type == type1 || type == type2)
      {
        if (OrderOpenTime() > tm)
        {
          tm = OrderOpenTime();
          ticket = OrderTicket();
        }
      }
    }
  
    return (OrderSelect(ticket, SELECT_BY_TICKET));
  }

  if (pool == MODE_HISTORY)
  {
    cnt = OrdersHistoryTotal();
    for (i=0; i < cnt; i++) 
    {
      if (!OrderSelect(i, SELECT_BY_POS, pool)) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
      type = OrderType();
      if (type == type1 || type == type2)
      {
        if (OrderCloseTime() > tm)
        {
          tm = OrderCloseTime();
          ticket = OrderTicket();
        }
      }
    }
  
    return (OrderSelect(ticket, SELECT_BY_TICKET));
  }
    
  return (false);
}