//+------------------------------------------------------------------+
//|                                               Moving Average.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

// *************************** COLLECTIVE2 REGION BEGIN ******************************
#import "C2MT4Connector.dll"
      string C2Init2(string c2InterfaceHost, string email, string password, string systemid, double c2LotMultiplier, string eaVersion, string terminal_data_path, string terminal_commondata_path, string reserve );
      string C2OrderOpen(string email, string password, string systemid, int orderid, string symbol, int cmd, double volume, double price, double stoploss, double takeprofit, string timeStamp, string mt4OrderComment);
      string C2OrderClose(string email, string password, string systemid, int orderid, string symbol, int cmd, double volume, double closePrice, string mt4OrderComment); 
      int C2ReadResponses();
      string C2NextResponse();
#import

extern string C2SystemID = "";
extern string C2Email = ""; 
extern string C2Password = "";
extern double C2LotMultiplier = 10;
extern string C2InterfaceHost = "ts.collective2.com"; 

// -----------------------------------------------------------------
// ReadCollective2Responses
// -----------------------------------------------------------------
int ReadCollective2Responses()
{
    Sleep(4000); // Wait 4 seconds (let Colective2 finish its work before reading responses).
    int numOfResponses = C2ReadResponses();
    if (numOfResponses > 0) 
    {
      for  (int i=1; i<=numOfResponses; i++) {
         string c2Result = C2NextResponse();
         if (c2Result != "") {
            Print(" <- from C2: ",c2Result);
         }
      }
    }
     return (0);
}

// -----------------------------------------------------------------
// RoundDownLots
// -----------------------------------------------------------------
double RoundDownLots(double lots)
{
    // Make sure the amount sent to Collective2 is an integer number.
    lots = lots * C2LotMultiplier;
    if (lots == NormalizeDouble(lots,0))
    {
       return (lots);
    }
    else
    {
       return (MathFloor(lots));
    }    
}

//+------------------------------------------------------------------+
void init()
{
    string c2InitResult = C2Init(C2InterfaceHost, C2Email, C2Password, C2SystemID, C2LotMultiplier, "0.0", TerminalInfoString(TERMINAL_DATA_PATH), TerminalInfoString(TERMINAL_COMMONDATA_PATH), "");
    Print("Collective2 connection initialization: " + c2InitResult);
    return(0);        
}
// *************************** COLLECTIVE2 REGION END ******************************

#define MAGICMA  20050610

extern double Lots               = 0.1;
extern double MaximumRisk        = 0.02;
extern double DecreaseFactor     = 3;
extern double MovingPeriod       = 12;
extern double MovingShift        = 6;
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//---- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| 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/1000.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);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double ma;
   int    res;
   double lots;
//---- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//---- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//---- sell conditions
   if(Open[1]>ma && Close[1]<ma)  
     {
      lots = LotsOptimized();
      res=OrderSend(Symbol(),OP_SELL,lots,Bid,3,0,0,"",MAGICMA,0,Red);
      C2OrderOpen(C2Email, C2Password, C2SystemID, res, Symbol(), OP_SELL, RoundDownLots(lots), Bid, 0.0, 0.0, "", "");
      ReadCollective2Responses();
      return;
     }
//---- buy conditions
   if(Open[1]<ma && Close[1]>ma)  
     {
      lots = LotsOptimized();
      res=OrderSend(Symbol(),OP_BUY,lots,Ask,3,0,0,"",MAGICMA,0,Blue);
      C2OrderOpen(C2Email, C2Password, C2SystemID, res, Symbol(), OP_BUY, RoundDownLots(lots), Ask, 0.0, 0.0, "", "");
      ReadCollective2Responses();
      return;
     }
//----
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double ma;
//---- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//---- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)        break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;

      int ticket = OrderTicket();
      double lots = OrderLots();
      //---- check order type 
      if(OrderType()==OP_BUY)
        {
         if(Open[1]>ma && Close[1]<ma) {
            OrderClose(ticket,lots,Bid,3,White);
            C2OrderClose(C2Email, C2Password, C2SystemID, ticket, Symbol(), OrderType(), RoundDownLots(lots), Bid, ""); 
            ReadCollective2Responses();
         }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(Open[1]<ma && Close[1]>ma) {
            OrderClose(ticket,lots,Ask,3,White);
            C2OrderClose(C2Email, C2Password, C2SystemID, ticket, Symbol(), OrderType(), RoundDownLots(lots), Ask, ""); 
            ReadCollective2Responses();
         }            
         break;
        }
     }
//----
  }
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
  {
//---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//----
  }