//+------------------------------------------------------------------+
//|                                                     Multi_EA.mq4 |
//|                                                         hellkkas |
//|                                    mailto:helderkastro@gmail.com |
//+------------------------------------------------------------------+

// Version 0.0.1
// Last Modified Date: Apr. 29th, 2007

#property copyright "hellkkas"
#property link      "mailto:hellkkas@gmail.com"
#define MAGICMA  162429
//---- input parameters
extern int    UsePct=0;
extern int    MaxLots=100;
extern int    Slippage=2;
extern double Lots=1;
extern double MaximumRisk=0.05;
extern double DecreaseFactor=6;
extern double MinLot=0.1;
extern double TrailingStop=30;
double        StartBalance,StartEquity;
extern bool   UseHourTrade = false;
extern int    FromHourTrade = 6;
extern int    ToHourTrade = 18;
//---- global variables
int bsi=0;
int dir=0;
int vTrig=0;
int openorders=0;
int cnt;
string pair;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
   pair = Symbol();
   return(0);
  } 

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

//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int GetCurrentOrders()
  {
  //---- calc open OrderSelect
   openorders=0;
   dir=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      //if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
      if(OrderSymbol()==Symbol())
      {
        openorders+=1;
        if(OrderType()==OP_BUY) dir=1;
        if(OrderType()==OP_SELL) dir=-1;
      }  
   }
}
//+-------------------End Calculate open positions-------------------+
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/500.0,1);
//---- calcuulate number of losses orders without a break
   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>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//---- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+-------------------End Calculate optimal lot size-----------------+
//+------------------------------------------------------------------+
//| Close Open Position                                              |
//+------------------------------------------------------------------+
int CloseTrade()
  { 
  for(int i=0;i<OrdersTotal();i++)
    {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)        break;
      //if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      if(OrderSymbol()==Symbol())
      {
        if(OrderType()==OP_BUY) OrderClose(OrderTicket(),OrderLots(),Bid,3,Yellow);
        if(OrderType()==OP_SELL) OrderClose(OrderTicket(),OrderLots(),Ask,3,Yellow);
      }  
   }
}
//+----------------------End Close Open Position---------------------+
//+------------------------------------------------------------------+
//| Open Trade Position                                              |
//+------------------------------------------------------------------+
int OpenTrade()
  {
   int vLots=LotsOptimized();
   if (bsi>0) OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,Slippage,0,0,NULL,MAGICMA,0,Green);
   
   if (bsi<0) OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,Slippage,0,0,NULL,MAGICMA,0,Red);
}
//+----------------------End Open Trade Position---------------------+
//+------------------------------------------------------------------+
//| Buy/Sell Indicator                                               |
//+------------------------------------------------------------------+
int CalcBSI()
  {
  //---- calc current indicators
  int GU_Trig=1,EU_Trig=1,UC_Trig=1,UJ_Trig=1;
  if (iCustom("GBPUSD",0,"JRSX",3,0,0)<50)GU_Trig=-1;
  if (iCustom("EURUSD",0,"JRSX",3,0,0)<50)EU_Trig=-1;
  if (iCustom("USDCHF",0,"JRSX",3,0,0)<50)UC_Trig=-1;
  vTrig=GU_Trig+EU_Trig-UC_Trig;

  bsi=0;
  if (vTrig>2) bsi=1;
  if (vTrig<-2) bsi=-1;
  if (pair>"USD") bsi=bsi*(-1);

}
//+-----------------------End Buy/Sell Indicator---------------------+
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
 {
  for(cnt=0;cnt<OrdersTotal();cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   // check for opened position 
         OrderSymbol()==Symbol())  // check for 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);
                    }
                 }
              }
           }
        }
     }
//+--------------------End TrailingStop & BreakEven------------------+
if (UseHourTrade)
   {
   if (!((Hour() >= FromHourTrade) && (Hour() <= ToHourTrade)))
      {
      Comment("Non-Trading Hours!");
      return(0);
      }
   }

  GetCurrentOrders();
  CalcBSI();
  Comment("\nStart Balance= ",StartBalance,",","Start Equity= ",StartEquity,
		   "\nBalance: ",AccountBalance(),","," Equity: ",AccountEquity(),","," TotalProfit: ",AccountProfit(),
         "\nDir: ",dir,"\nBSI: ",bsi,"\nTrig: ",vTrig);
   
  //---- exit trades
  if (openorders!=0) {
     if ((bsi>0) && (dir<0)) CloseTrade();
     if ((bsi<0) && (dir>0)) CloseTrade();
  }   
  //---- open trades
  else {
   if (bsi!=0) OpenTrade();
  }   
}
//+---------------------End Expert Start Function--------------------+