//+---------------------------------------------------------------------+
//|                                                 E-Bay_Clone_1v1.mq4 |
//| Copyright © 2007, MetaTrader_Experts_and_Indicators@yahoogroups.com |
//|                   MetaTrader_Experts_and_Indicators@yahoogroups.com |
//+---------------------------------------------------------------------+

#property copyright "Copyright © 2007, MetaTrader_Experts_and_Indicators@yahoogroups.com"
#property link      "MetaTrader_Experts_and_Indicators@yahoogroups.com"

// This Expert created by => Copy Over Paste Yippee Code Assembly Technician <= ,  aka "C.O.P.Y.C.A.T."
// For Demo Testing Only , MetaTrader_Experts_and_Indicators@yahoogroups.com will not accept responsibility for any loses incurred
// If you're not sure what incurred means , go here http://dictionary.reference.com/browse/incurred

#include <stderror.mqh>
#include <stdlib.mqh>

extern bool SuspendAfterClose = False;

extern double StartLots = 0.01;
extern bool UseMM = False;

extern int PipsBetweenTrades = 20;
extern double TakeProfitPips =  2;

extern bool ReverseTrading = True;

int SendRequest;

bool FirstRun = True;

string Accfreemargin;
string MaxLots;
string usedmargin;
string openbuys;
string opensells;

extern bool ShowComments = True;

int Magic;
int cnt;

double lotsi;
double mylotsi;

int OpenOrders;
double Profit;
double lotstote;
double LastLots;

int buytote;
double buylots;
double LastBuyPrice;
double LastBuyLots;
double BuyPips;

int selltote;
double selllots;
double LastSellPrice;
double LastSellLots;
double SellPips;

extern bool CloseM = False;

double goober;

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   
   if (!IsDemo())return(0);
   
   lotsi = StartLots;
   
   if (UseMM)
    {
      lotsi=MathFloor(AccountBalance()/2000)*StartLots;
    }
   
   if (lotsi < StartLots) lotsi = StartLots;
   
   SendRequest = -1;
   
   if (FirstRun)
    {
      if (Symbol()=="EURUSD"){Magic=110+ReverseTrading;}
      if (Symbol()=="GBPUSD"){Magic=220+ReverseTrading;}
      if (Symbol()=="USDJPY"){Magic=330+ReverseTrading;}
      if (Symbol()=="USDCHF"){Magic=440+ReverseTrading;}// copy this line , paste below it
      
      // after you paste , change "USDCHF" to whatever symbol you are running and change Magic= "xxx" +ReverseTrading;.
      
      if (Magic < 2){Magic=5+ReverseTrading;}
      
      Accfreemargin = AccountNumber()+"_Accfreemargin";
      MaxLots = AccountNumber()+"_"+Symbol()+"_"+Magic+"_MaxLots";
      usedmargin = AccountNumber()+"_"+Symbol()+"_"+Magic+"_usedmargin";
      openbuys = AccountNumber()+"_"+Symbol()+"_"+Magic+"_openbuys";
      opensells = AccountNumber()+"_"+Symbol()+"_"+Magic+"_opensells";
      
      if (!GlobalVariableCheck(Accfreemargin)) { GlobalVariableSet(Accfreemargin,200000000); }
      if (!GlobalVariableCheck(MaxLots)) { GlobalVariableSet(MaxLots,lotstote); }
      if (!GlobalVariableCheck(usedmargin)) { GlobalVariableSet(usedmargin,0); }
      if (!GlobalVariableCheck(openbuys)) { GlobalVariableSet(openbuys,buytote); }
      if (!GlobalVariableCheck(opensells)) { GlobalVariableSet(opensells,selltote); }
      FirstRun=False;
    }
   
   OpenOrders = 0;
   Profit = 0;
   lotstote = 0;
   LastLots = 0;
   buytote = 0;
   buylots = 0;
   LastBuyPrice = 0;
   LastBuyLots = 0;
   BuyPips = 0;
   selltote = 0;
   selllots = 0;
   LastSellPrice = 0;
   LastSellLots = 0;
   SellPips = 0;
   mylotsi = 0;
   
   if (OrdersTotal() > 0)
    {
     for (cnt = 0; cnt < OrdersTotal(); cnt++)
      {
        OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
       if ((OrderSymbol()==Symbol()) && (OrderMagicNumber() == Magic))
        {
          OpenOrders++;
          Profit+=OrderProfit();
          lotstote+=OrderLots();
          LastLots = OrderLots();
         if ((OrderSymbol()==Symbol()) && (OrderType()==OP_BUY) && (OrderMagicNumber() == Magic))
          {
            buytote++;
            buylots+=OrderLots();
            LastBuyPrice = OrderOpenPrice();
            LastBuyLots = OrderLots();
            BuyPips += (OrderClosePrice()-OrderOpenPrice());
          }
         if ((OrderSymbol()==Symbol()) && (OrderType()==OP_SELL) && (OrderMagicNumber() == Magic))
          {
            selltote++;
            selllots-=OrderLots();
            LastSellPrice = OrderOpenPrice();
            LastSellLots = OrderLots();
            SellPips += (OrderOpenPrice()-OrderClosePrice());
          }
        }
      }
    }
   
   if ((CloseM) && (OpenOrders <= 0)) { CloseM = False; return(0); }
   if ((CloseM) && (OpenOrders > 0)) CloseAll();
   
   if (!CloseM)
    {
     
     if ((BuyPips+SellPips) >= TakeProfitPips*Point)
      {
        CloseM = True;
        CloseAll();
      }
     
     if ((!SuspendAfterClose) && (OpenOrders <= 0)) 
      {
       if ((SuspendAfterClose) && (OpenOrders <= 0)) { return(0); }
       //if (
	     LastSellPrice = 0;
	     LastBuyPrice = 0;
	     RequestBuy();
	   }
     
     if ((OpenOrders == 1) && (selltote == 0))
      {
        RequestSell();
      }
     
     if ( (!ReverseTrading) && (OpenOrders >= 2) )
      {
       if (NormalizeDouble(Bid,Digits) <= (LastSellPrice-(PipsBetweenTrades*Point)) )
	     {
		    RequestAdditionalSell();
	     }
	    else
	    if (NormalizeDouble(Ask,Digits) >= (LastBuyPrice+(PipsBetweenTrades*Point)) )
	     {
		    RequestAdditionalBuy();
	     }
      }
     
     if ( (ReverseTrading) && (OpenOrders >= 2) )
      {	
	    if (NormalizeDouble(Ask,Digits) <= (LastBuyPrice-(PipsBetweenTrades*Point)) )
	     {
	       RequestAdditionalBuy();
	     }
	    else
	    if (NormalizeDouble(Bid,Digits) >= (LastSellPrice+(PipsBetweenTrades*Point)) )
	     {
		    RequestAdditionalSell();
	     }
      }
    }
   
   if (AccountFreeMargin() < GlobalVariableGet(Accfreemargin)) GlobalVariableSet(Accfreemargin,AccountFreeMargin());
   if (lotstote > GlobalVariableGet(MaxLots)) GlobalVariableSet(MaxLots,lotstote);
   if (buytote > GlobalVariableGet(openbuys)) GlobalVariableSet(openbuys,buytote);
   if (selltote > GlobalVariableGet(opensells)) GlobalVariableSet(opensells,selltote);
   if ((MarketInfo(Symbol(),MODE_MARGINREQUIRED)*lotstote) != GlobalVariableGet(usedmargin)) { GlobalVariableSet(usedmargin,(MarketInfo(Symbol(),MODE_MARGINREQUIRED)*lotstote)); }
   
   if (ShowComments)
    {
      Comment("\n    LastBuyPrice = ",DoubleToStr(LastBuyPrice,Digits)," , LastSellPrice = ",DoubleToStr(LastSellPrice,Digits),
              "\n    Account Lowest Free Margin = $ ",DoubleToStr(GlobalVariableGet(Accfreemargin),2)," , Max Open Lots = ",DoubleToStr(GlobalVariableGet(MaxLots),2),
              "\n    Open Buys = ",buytote," , Open Sells = ",selltote," , Margin In Use = $ ",DoubleToStr(GlobalVariableGet(usedmargin),2),
              "\n    Pips Between Trades = ",DoubleToStr(PipsBetweenTrades*Point,Digits)," , Start Lots = ",StartLots," , UseMM = ",UseMM," , Start Lots = ",lotsi,
              "\n    Open Buy Lots = ",DoubleToStr(buylots,2)," , Open Sell Lots = ",DoubleToStr(selllots,2)," , Total Lots Bias = ",DoubleToStr(buylots+selllots,2),
              "\n    BuyPips = ",DoubleToStr(BuyPips,Digits)," , SellPips = ",DoubleToStr(SellPips,Digits)," , BuyPips+SellPips = ",DoubleToStr(BuyPips+SellPips,Digits),
              "\n    SuspendAfterClose = ",SuspendAfterClose," , Magic = ",Magic," , Margin Required For 1 Lot = $ ",DoubleToStr(MarketInfo(Symbol(),MODE_MARGINREQUIRED),2));
    }
   if ((!ShowComments) && (goober != Time[0])) { Comment(""); goober = Time[0]; }
   
//----
   return(0);
  }
//+------------------------------------------------------------------+

void CloseAll()
 {
   int crumbs = OrdersTotal();
  for (cnt = 0; cnt < crumbs; cnt++)
   {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);	
    if ((Symbol() == Symbol()) && (OrderMagicNumber() == Magic))
     {
       OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),0,White);
       CloseM = True;
     }
   }
 }

void RequestAdditionalBuy()
 {
   SendRequest = -1;
   mylotsi = LastLots * 2;
  if (mylotsi>100) { mylotsi=100; }
    SendRequest = OrderSend(Symbol(),OP_BUY,mylotsi,Ask,3,0,0,""+Symbol()+" E-Bay_Clone_1v1 "+Magic+"",Magic,0,Blue);
  if (SendRequest < 0)
   { Print("Error - OrderSend Buy @ ",Ask);
     ReportError();
   }
 }

void RequestAdditionalSell()
 {
   SendRequest = -1;
   mylotsi = LastLots * 2;
  if (mylotsi>100) { mylotsi=100; }
	 SendRequest = OrderSend(Symbol(),OP_SELL,mylotsi,Bid,3,0,0,""+Symbol()+" E-Bay_Clone_1v1 "+Magic+"",Magic,0,Red);
  if (SendRequest < 0)
   { Print("Error - OrderSend Sell @ ",Bid);
     ReportError();
   }
 }

void RequestBuy()
 {
  if ((!SuspendAfterClose) && (buytote == 0) && (!CloseM))
   {
     SendRequest = -1;
	  SendRequest = OrderSend(Symbol(),OP_BUY,lotsi,Ask,3,0,0,""+Symbol()+" E-Bay_Clone_1v1 "+Magic+"",Magic,0,Blue);
	 if (SendRequest < 0)
	  { Print("Error - OrderSend Buy @ ",Ask);
	    ReportError();
	  }
   }
 }

void RequestSell()
 {
  if ((!SuspendAfterClose) && (selltote == 0) && (!CloseM)) 
	{
	  SendRequest = -1;
	  SendRequest = OrderSend(Symbol(),OP_SELL,lotsi,Bid,3,0,0,""+Symbol()+" E-Bay_Clone_1v1 "+Magic+"",Magic,0,Red);
	 if (SendRequest < 0)
	  { Print("Error - OrderSend Sell @ ",Bid);
	    ReportError();
     }
   }
 }

void ReportError() 
{
   int err = GetLastError();
   Print("Error(",err,"): ", ErrorDescription(err));
}