/////////////////////////////////////////////////////////////////////// Recomended time frames
// MrsPacMan is a Hybrid version, by xxDavidxSxx, of                 //     1 hr charts--CCIBLOCKS 250/-250 HEDGE TRUE
// Goblin BiPolar Edition                                            //    
// Special thanks to  bluto @ www.forex-tsd.com                      //     DEMO=DEFAULT SETTINGS
// And Alisso @ www.forex-tsd.com for some optimising and corrections//     
//                                                                   //
///////////////////////////////////////////////////////////////////////
 // THE MAJIC #'S IN HERE ARE DIFFERENT FROM PACMAN AND CAN BE RAN WITH PACMAN ON THE SAME PAIR
 // MrsPacMan is a pacman mod version. There are alot of new features added. You can chose from L_Profit/S_Profit individual equity exit. Or L_Profit+S_Profit together.
 // There is a test feature that will close all open orders on the account regardless of majic #. And you can set it to close all accounts open orders on account equity
 // regardless of ea or majic #. There is a setting to close orders when market momentom shifts.(still needs something)
 // The signals are generated on 3 ma's. With volume filter, and cci blocking over bought and over sold ranges. A very simple but accurate signal.
 //  On 1 hr chart over 2007 gets 75%-82% win rate. (give or take) with 8-12pip equity target. The defaults are set up to run on 5k demo. For real account turn 
 // moneymanagement to true and superpacman2.25 to true. To run on a m15 chart set cciblocks to 350. This helps stop it from placing orders at the peak of a move.
 //  I wanted to get the improvements out there so this isn't fully tested. But its a lightened version of pacman_x I posted a test on in the show us your best ea thread.
 // That one I am able to get over 90% win rate on tests and one time hit 97%. Still keeping good amount of trades. But theres alot I am working on it.
 // There is room for pacmanJr some where too. 
 // You can hedge one of your orders. I like to hedge the initial order. But not on m15.
  
extern string    SystemWideParms = "**  MrsPacMan Systemwide Parameters **";

extern bool      PacManSuperCell=false;               // this setting to true, and PacMan will increase progression "on the go" CuperCell determines when

extern string    SuperCellnumber = "increase progression to 300%";

extern double    SuperCell=3;                         //2nd trade after this # will be supersized 2.50. EX: set to 3 the 5th trade will be 250% of the 4th 

extern string    SuperPacManSettings = "Full Time SuperMrsPacMan 210% or 225%";
                    
extern bool      SuperPacMan2.25=false;               // Set to true=All lot size progression based on 225%
extern bool      SuperPacMan2.1=false;                 // Set to true=All lot size progression based on 210%
extern double    LotSize = 0.1;                      // First order will be for this lot size
extern bool      UseFiboLotSizeProgression=false;
extern bool      UseMoneyMgmt=true;                   // if true, the lots size will increase based on account size
extern string    reverseOrder= " true= close order when momentom reverses ";
extern bool      ReverseOrder=false;                  // Reverses order when markets momentom shifts/reverses      
extern bool      hedge=true;                          // true to hedge one of your trades
extern int       HedgeNumber=3;                       // set to the # of trade you want to hedge
extern double    EquityProtectionLevel=0.0;           // Min. equity to preserve in the event things go bad; all orders for Symbol/Magic will be closed.
double           MaxLossPerOrder=0.0;                 // Max. loss tolerance per order; once reached, order will be closed.

extern string    Nonmajic= " set to 1 to close all account orders profit";
extern string    nonmajic= "set to 0 to close on single pair profit";
extern string    testExit= "set to 1 to close all open orders on account ea or not ";
extern int       NonMagic=0;                           //Set to 1 and will close all accounts orders at desired equity target regardless of majic #
extern int       TestExit=0;                           //Set test to 1 and it will close all open orders on account
extern string    LongShort= " Set LScombined=true to exit on long+short profit, false = individual";
extern bool      LScombined=false;                     // true makes it add long and short profit for the equity target
extern double    TargetEquityToCloseAndReset= 0.15;    // allows you to take less pips and keep more pip step.

extern double    RiskPercent= 1.25;                    // risk to calculate the lots size (only if mm is enabled)

extern int       JMA_Volume=100;                      // Volume filter won't allow trades if market volume is below this #
                    

extern int       CCI_PeroidFast=55;
extern double    L_cciblock=250;                      // blocks over bought range
extern double    S_cciblock=-250;                     // blocks over sold range 

extern string    LongTradeParms = "**  MsPacMan Buy Side Parameters **";

extern double    LongTakeProfit = 30;                 // Profit Goal for the latest order opened
extern double    LongInitialStop = 0;                 // StopLoss
extern double    LongTrailingStop = 0;                // Pips to trail the StopLoss
extern int       LongMaxTrades=5;                     // Maximum number of orders to open
extern int       LongPips=33;                         // Distance in Pips from one order to another
int              LongSecureProfit=1000;              // If profit made is bigger than SecureProfit we close the orders
extern bool      LongAccountProtection=false;         // If one the account protection will be enabled, 0 is disabled
extern int       LongOrderstoProtect=0;               // This number subtracted from LongMaxTrades is the number of open orders to enable the account protection.
                                                     // Example: (LongMaxTrades=10) minus (OrderstoProtect=3)=7 orders need to be open before account protection is enabled.
                                                
extern string    ShortTradeParms = "**  MsPacMan Sell Side Parameters **";

extern double    ShortTakeProfit = 30;                // Profit Goal for the latest order opened
extern double    ShortInitialStop = 0;                // StopLoss
extern double    ShortTrailingStop = 0;               // Pips to trail the StopLoss
extern int       ShortMaxTrades=5;                    // Maximum number of orders to open
extern int       ShortPips=33;                        // Distance in Pips from one order to another
int              ShortSecureProfit=1000;             // If profit made is bigger than SecureProfit we close the orders
extern bool      ShortAccountProtection=false;        // If one the account protection will be enabled, 0 is disabled
extern int       ShortOrderstoProtect=0;              // This number subtracted from LongMaxTrades is the number of open orders to enable the account protection.
                                                      // Example: (LongMaxTrades=10) minus (OrderstoProtect=3)=7 orders need to be open before account protection is enabled. 
                                                 
                                                 
// Global internal parameters used by Long() buy order module:   
                        
extern int       LongMagicNumber = 0;                 // Magic number for the long orders placed                              
int              L_OpenOrders=0;
int              L_Count=0;
int              L_Slippage=5;
double           L_sl=0;
double           L_tp=0;
double           BuyPrice=0;
double           L_OrderLotSize=0;
int              L_Mode=0;
int              L_OrderType=0;
bool             L_ContinueOpening=true;
double           L_LastPrice=0;
int              L_PreviousOpenOrders=0;
double           L_Profit=0;
int              L_LastTicket=0;
int              L_LastType=0;
double           L_LastClosePrice=0;
double           L_LastLots=0;
double           L_PipValue=0;

// Global internal parameters used by Short() sell order module:
   
extern int       ShortMagicNumber = 0;                // Magic number for the short orders placed                            
int              S_OpenOrders=0;
int              S_Count=0;
int              S_Slippage=5;
double           S_sl=0;
double           S_tp=0;
double           SellPrice=0;
double           S_OrderLotSize=0;
int              S_Mode=0;
int              S_OrderType=0;
bool             S_ContinueOpening=true;
double           S_LastPrice=0;
int              S_PreviousOpenOrders=0;
double           S_Profit=0;
int              S_LastTicket=0;
int              S_LastType=0;
double           S_LastClosePrice=0;
double           S_LastLots=0;
double           S_PipValue=0;


// Global internal shared parameters

string           text="", text2="";
string           TrendTxt="analyzing...";
int              trendtype=0;
bool             AllowTrading=true;
double           G_MinLotSize=0;
double           G_MaxLotSize=0;
double           G_LotStep=0;
double           G_Decimals=0;
int              G_AcctLeverage=0;
int              G_CurrencyLotSize=0;
double           G_OrderLotSize=0;
int              G_Count=0;
int              G_Slippage=5;
double           cci1=0;

int init()
  {

// For those of us tired of messing around assigning annoying but essential magic numbers.
   
   if (Symbol()=="AUDCADm" || Symbol()=="AUDCAD") {LongMagicNumber=110001;ShortMagicNumber=210001;}
   if (Symbol()=="AUDJPYm" || Symbol()=="AUDJPY") {LongMagicNumber=110002;ShortMagicNumber=210002;}
   if (Symbol()=="AUDNZDm" || Symbol()=="AUDNZD") {LongMagicNumber=110003;ShortMagicNumber=210003;}
   if (Symbol()=="AUDUSDm" || Symbol()=="AUDUSD") {LongMagicNumber=110004;ShortMagicNumber=210004;}
   if (Symbol()=="CHFJPYm" || Symbol()=="CHFJPY") {LongMagicNumber=110005;ShortMagicNumber=210005;}
   if (Symbol()=="EURAUDm" || Symbol()=="EURAUD") {LongMagicNumber=110006;ShortMagicNumber=210006;}
   if (Symbol()=="EURCADm" || Symbol()=="EURCAD") {LongMagicNumber=110007;ShortMagicNumber=210007;}
   if (Symbol()=="EURCHFm" || Symbol()=="EURCHF") {LongMagicNumber=110008;ShortMagicNumber=210008;}
   if (Symbol()=="EURGBPm" || Symbol()=="EURGBP") {LongMagicNumber=110009;ShortMagicNumber=210009;}
   if (Symbol()=="EURJPYm" || Symbol()=="EURJPY") {LongMagicNumber=110010;ShortMagicNumber=210010;}
   if (Symbol()=="EURUSDm" || Symbol()=="EURUSD") {LongMagicNumber=110011;ShortMagicNumber=210011;}
   if (Symbol()=="GBPCHFm" || Symbol()=="GBPCHF") {LongMagicNumber=110012;ShortMagicNumber=210012;}   
   if (Symbol()=="GBPJPYm" || Symbol()=="GBPJPY") {LongMagicNumber=110013;ShortMagicNumber=210013;}
   if (Symbol()=="GBPUSDm" || Symbol()=="GBPUSD") {LongMagicNumber=110014;ShortMagicNumber=210014;}
   if (Symbol()=="NZDJPYm" || Symbol()=="NZDJPY") {LongMagicNumber=110015;ShortMagicNumber=210015;}
   if (Symbol()=="NZDUSDm" || Symbol()=="NZDUSD") {LongMagicNumber=110016;ShortMagicNumber=210016;}
   if (Symbol()=="USDCHFm" || Symbol()=="USDCHF") {LongMagicNumber=110017;ShortMagicNumber=210017;}
   if (Symbol()=="USDJPYm" || Symbol()=="USDJPY") {LongMagicNumber=110018;ShortMagicNumber=210018;}
   if (Symbol()=="USDCADm" || Symbol()=="USDCAD") {LongMagicNumber=110019;ShortMagicNumber=210019;}
   if (LongMagicNumber==0) {LongMagicNumber = 110999;}   
   if (ShortMagicNumber==0) {ShortMagicNumber = 210999;}   
   return(0);
   
  }


int start()

  {
  
//====================================================== Begin Top Level Command Module ============================================================  
 
// Global equity/risk based lot sizer
cci1=iCCI( NULL, 0, CCI_PeroidFast, PRICE_TYPICAL, 1);
G_AcctLeverage = AccountLeverage();
G_MinLotSize = MarketInfo(Symbol(),MODE_MINLOT);
G_MaxLotSize = MarketInfo(Symbol(),MODE_MAXLOT);
G_LotStep = MarketInfo(Symbol(),MODE_LOTSTEP);
G_CurrencyLotSize = MarketInfo(Symbol(),MODE_LOTSIZE);

if(G_LotStep == 0.01) {G_Decimals = 2;}
if(G_LotStep == 0.1) {G_Decimals = 1;}

if (UseMoneyMgmt == true)
 {
  G_OrderLotSize = AccountEquity() * (RiskPercent * 0.01) / (G_CurrencyLotSize / G_AcctLeverage);
  G_OrderLotSize = StrToDouble(DoubleToStr(G_OrderLotSize,G_Decimals));
 }
  else
 {
  G_OrderLotSize = LotSize;
 }

if (G_OrderLotSize < G_MinLotSize) {G_OrderLotSize = G_MinLotSize;}
if (G_OrderLotSize > G_MaxLotSize) {G_OrderLotSize = G_MaxLotSize;}
 
    
// Added Minimum Equity Level to protect to protect from being wiped out in the event things really get wicked...more elegant risk control stuff.
      
   if(EquityProtectionLevel > 0 && AccountEquity() <= EquityProtectionLevel)
     {
      AllowTrading = false;
      Print("Min. Equity Level Reached - Trading Halted & Orders Closed");
      Alert("Min. Equity Level Reached - Trading Halted & Orders Closed");
      for(G_Count=OrdersTotal();G_Count>=0;G_Count--)
       {
	     OrderSelect(G_Count, SELECT_BY_POS, MODE_TRADES);	  	  
		  OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),G_Slippage,Blue); 
		 }	 
		 return(0);		   
	  }
	     	    
// Equity Target based on single pair profit	  

SymbolProfitLong();
L_Profit=L_Profit;
SymbolProfitShort();  // call Profit functions
S_Profit=S_Profit;

	  Comment ("S_Profit: ",S_Profit," L_Profit: ",L_Profit," TotalProfit: ", S_Profit+L_Profit, " EquityExit: $",(AccountBalance() * ( (TargetEquityToCloseAndReset * 0.01))) );
	  if (LScombined==true)
	  if ( TargetEquityToCloseAndReset > 0 && 
	  ((S_Profit+L_Profit >= (AccountBalance() * ((TargetEquityToCloseAndReset * 0.01) ))) || TestExit==1) )
	  {
	  
      for(G_Count=OrdersTotal();G_Count>=0;G_Count--)
       {
	     OrderSelect(G_Count, SELECT_BY_POS, MODE_TRADES);
	     if (OrderSymbol()==Symbol())
	     {
		  OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),G_Slippage,Peru);
		  } 	  		  
		 }	 
		 return(0);		   
	  }
	  SymbolProfitLong();
L_Profit=L_Profit;
SymbolProfitShort();  // call Profit functions
S_Profit=S_Profit;

	 
	  if (LScombined==false)
	  if ( TargetEquityToCloseAndReset > 0 && 
	  ((L_Profit >= (AccountBalance() * ((TargetEquityToCloseAndReset * 0.01) ))) || TestExit==1) )
	  {
	  
      for(L_Count=OrdersTotal();L_Count>=0;L_Count--)
       {
	     OrderSelect(L_Count, SELECT_BY_POS, MODE_TRADES);
	     if (OrderSymbol()==Symbol())
	     {
		 OrderClose(L_LastTicket,L_LastLots,L_LastClosePrice,L_Slippage,SlateBlue);
		  } 	  		  
		 }	 
		 return(0);		   
	  }
SymbolProfitLong();
L_Profit=L_Profit;
SymbolProfitShort();  // call Profit functions
S_Profit=S_Profit;

	 
	  if (LScombined==false)
	  if ( TargetEquityToCloseAndReset > 0 && 
	  ((S_Profit >= (AccountBalance() * ((TargetEquityToCloseAndReset * 0.01) ))) || TestExit==1) )
	  {
	  
      for(S_Count=OrdersTotal();S_Count>=0;S_Count--)
       {
	     OrderSelect(S_Count, SELECT_BY_POS, MODE_TRADES);
	     if (OrderSymbol()==Symbol())
	     {
		  OrderClose(S_LastTicket,S_LastLots,S_LastClosePrice,S_Slippage,IndianRed);
		  } 	  		  
		 }	 
		 return(0);		   
	  }


           
   if (AllowTrading==true) {LongGoblin();ShortGoblin();}
   
   
   
   

   return(0);
  }  
   
//====================================================== End Of Top Level Command Module ============================================================<<





//====================================================== Begin Buy Order Processing SubRoutine ======================================================<<

void LongGoblin()
  {
  if (ReverseOrder==true) 
    {
     for(L_Count=OrdersTotal();L_Count>=0;L_Count--) 
      {
       RefreshRates();
       OrderSelect(L_Count,SELECT_BY_POS,MODE_TRADES);
       if (OrderSymbol() == Symbol())
        {
         if (OrderType() == OP_BUY && OrderMagicNumber() == LongMagicNumber && cci1 < -50  && L_OpenOrders >= 1 ) { OrderClose(OrderTicket(),OrderLots(),Bid,L_Slippage,White);
         }
         
         if (OrderType() == OP_SELL && OrderMagicNumber() == ShortMagicNumber && cci1 > 50 && S_OpenOrders >= 1) { OrderClose(OrderTicket(),OrderLots(),Ask,S_Slippage,White);
         
         }
        }
      }
    }

  
    
   L_Profit=0;
   L_OpenOrders=0;
   for(L_Count=0;L_Count<OrdersTotal();L_Count++)   
   {
    OrderSelect(L_Count, SELECT_BY_POS, MODE_TRADES);
    if (OrderSymbol()==Symbol() && OrderMagicNumber() == LongMagicNumber) {L_OpenOrders++;L_Profit=L_Profit+OrderProfit();}
   }     
   
   L_PipValue = MarketInfo(Symbol(),MODE_TICKVALUE);
   if (L_PipValue==0) { L_PipValue=5; }
   
   if (L_PreviousOpenOrders>L_OpenOrders) 
   {	
    bool closed = false;
	 for(L_Count=OrdersTotal();L_Count>=0;L_Count--)
	  {     
      OrderSelect(L_Count, SELECT_BY_POS, MODE_TRADES);
	   if (OrderSymbol()==Symbol() && OrderMagicNumber() == LongMagicNumber && OrderType() == OP_BUY) 
	    {
        int m_Ticket = OrderTicket();
	     OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),L_Slippage,Blue);
		  Print("Closing Buy Order ",m_Ticket);
	      }
		 }
	  }
	  if (closed)
	  {
	     return (0);
	  }

   L_PreviousOpenOrders=L_OpenOrders;
   if (L_OpenOrders>=LongMaxTrades) 
    {
	  L_ContinueOpening=False;
    } else {
	  L_ContinueOpening=True;
    }

   if (L_LastPrice==0) 
    {
	  for(L_Count=0;L_Count<OrdersTotal();L_Count++)
	   {	
       OrderSelect(L_Count, SELECT_BY_POS, MODE_TRADES);
	    if (OrderSymbol()==Symbol() && OrderMagicNumber() == LongMagicNumber && OrderType() == OP_BUY) 
		  {
			L_LastPrice=OrderOpenPrice();
		   L_OrderType=2;
		  }
	   }
    }

   if (L_OpenOrders<1) {L_OrderType=OpenOrdersBasedOnTrendRSX();}
 
// Here comes the fun part we all waited for where we update those trailing stops....yippeekyeah!!

   for(L_Count=OrdersTotal();L_Count>=2;L_Count--)
    {
     OrderSelect(L_Count, SELECT_BY_POS, MODE_TRADES);
     if (OrderSymbol() == Symbol() && OrderMagicNumber() == LongMagicNumber && OrderType()== OP_BUY)  
      {	
       if (LongTrailingStop > 0 && (Bid-OrderOpenPrice()>=(LongTrailingStop+LongPips)*Point) &&  (OrderStopLoss()<(Bid-Point*LongTrailingStop)) )
        {				   
	      OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*LongTrailingStop,OrderClosePrice()+LongTakeProfit*Point+LongTrailingStop*Point,800,Yellow);
         return(0);
        } 
	   }
  	 }
   
   L_Profit=0;
   L_LastTicket=0;
   L_LastType=0;
	L_LastClosePrice=0;
	L_LastLots=0;	
	for(L_Count=0;L_Count<OrdersTotal();L_Count++)
	{
    OrderSelect(L_Count, SELECT_BY_POS, MODE_TRADES);
    if (OrderSymbol()==Symbol() && OrderMagicNumber() == LongMagicNumber && OrderType()==OP_BUY) 
	  {			
  	   L_LastTicket=OrderTicket();
		L_LastType=OP_BUY; 
		L_LastClosePrice=OrderClosePrice();
		L_LastLots=OrderLots();
		L_Profit=L_Profit+OrderProfit();	
	  }
   } 
 
      
   if (L_OrderType==2 && L_ContinueOpening && ((L_LastPrice-Ask)>=LongPips*Point || L_OpenOrders<1) ) 
    {  		
     BuyPrice=Ask;
     L_LastPrice=0;
     if (LongTakeProfit==0) { L_tp=0; }
      else { L_tp=BuyPrice+LongTakeProfit*Point; }	
     if (LongInitialStop==0)  { L_sl=0; }
      else { L_sl=NormalizeDouble(BuyPrice-LongInitialStop*Point - (LongMaxTrades-L_OpenOrders)*LongPips*Point, Digits); }
     if (L_OpenOrders!=0) 
       {
        L_OrderLotSize=G_OrderLotSize;			
        for(L_Count=1;L_Count<=L_OpenOrders;L_Count++)
         {
          if (UseFiboLotSizeProgression)
          {
            L_OrderLotSize = MathRound(MathPow(1.6180339,S_Count+1)/MathSqrt(5))* L_OrderLotSize;  // Fibonacci progression by Tross
           }
//================================================SuperMrsPacMan settings for Lot sizing=============================================//
              else                                                        // PacMan can start out with super lot size progression
             {  			                                                  // Or it can start increasing at a set # Called the Super Cell #. This is 
               if (SuperPacMan2.25)                                        // the # of open positions that it will increase progression size to 225%   
                {                                                            // So we can cover the losses on the first trades. USE GREAT CAUTION!! Because
                  L_OrderLotSize=NormalizeDouble(L_OrderLotSize*2.25,2.25);   // they eat margin fast. 
                   }                                                                   
                   else                                                         
                 {  			      
                  if (SuperPacMan2.1)                                                   
                {                                                               
               L_OrderLotSize=NormalizeDouble(L_OrderLotSize*2.1,2.1);
              }	           
	           else 
	         {
	           if (PacManSuperCell && L_OpenOrders > SuperCell)
	            {
	             L_OrderLotSize=NormalizeDouble(L_OrderLotSize*3,3);
	             } 
	              else 
	             {
	               L_OrderLotSize=NormalizeDouble(L_OrderLotSize*2,2);
                   }
                 }
               } 
             }
           } 
       } else { L_OrderLotSize=G_OrderLotSize; } 
	   OrderSend(Symbol(),OP_BUY,L_OrderLotSize,BuyPrice,L_Slippage,L_sl,L_tp,"PacMan Buy",LongMagicNumber,0,Blue);		    
	   return(0);   
    }   

   return(0);
  }


//====================================================== Begin Sell Order Processing SubRoutine =====================================================<<

void ShortGoblin()
  {   
   if (MathAbs(MaxLossPerOrder) > 0)
    {
     for(S_Count=OrdersTotal();S_Count>=0;S_Count--) 
      {
       RefreshRates();
       OrderSelect(S_Count,SELECT_BY_POS,MODE_TRADES);
       if (OrderSymbol() == Symbol())
        {         
         if (OrderType() == OP_SELL && OrderMagicNumber() == ShortMagicNumber && OrderProfit() <= MathAbs(MaxLossPerOrder) * (-1)) { OrderClose(OrderTicket(),OrderLots(),Ask,L_Slippage,White); }
        }
      }
    }
   
   S_Profit=0;  
   S_OpenOrders=0;
   bool closed=false;
   for(S_Count=0;S_Count<OrdersTotal();S_Count++)   
    {
     OrderSelect(S_Count, SELECT_BY_POS, MODE_TRADES);
	  if (OrderSymbol()==Symbol() && OrderMagicNumber() == ShortMagicNumber) {S_OpenOrders++;S_Profit=S_Profit+OrderProfit();}
    }     
      
   S_PipValue = MarketInfo(Symbol(),MODE_TICKVALUE);
   if (S_PipValue==0) { S_PipValue=5; }
   
   if (S_PreviousOpenOrders>S_OpenOrders) 
   {	  
	 for(S_Count=OrdersTotal();S_Count>=0;S_Count--)
	  {	     
      OrderSelect(S_Count, SELECT_BY_POS, MODE_TRADES);
	   if (OrderSymbol()==Symbol() && OrderMagicNumber() == ShortMagicNumber && OrderType() == OP_SELL) 
	    {
        int m_Ticket = OrderTicket();
	     OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),S_Slippage,Red); 
	     Print("Closing Sell Order ",m_Ticket);
	      }
		 }
	  }
	  if (closed)
	  {
	     return (0);
	     }
    
   
  
	  

   S_PreviousOpenOrders=S_OpenOrders;
   if (S_OpenOrders>=ShortMaxTrades) 
    {
	  S_ContinueOpening=False;
    } else {
	  S_ContinueOpening=True;
    }

   if (S_LastPrice==0) 
    {
	  for(S_Count=0;S_Count<OrdersTotal();S_Count++)
      {	
       OrderSelect(S_Count, SELECT_BY_POS, MODE_TRADES);	
	    if (OrderSymbol()==Symbol() && OrderMagicNumber() == ShortMagicNumber && OrderType() == OP_SELL) 
		  {
	      S_LastPrice=OrderOpenPrice();
		   S_OrderType=1;
		  }
	   }
    }


   
   if (S_OpenOrders<1){S_OrderType=OpenOrdersBasedOnTrendRSX();}
      

//  update those trailing stops

   for(S_Count=OrdersTotal();S_Count>=2;S_Count--)
   {
    OrderSelect(S_Count, SELECT_BY_POS, MODE_TRADES);
    if (OrderSymbol() == Symbol() && OrderMagicNumber() == ShortMagicNumber && OrderType()==OP_SELL) 
	  {	
      if (ShortTrailingStop > 0 && (OrderOpenPrice()-Ask>=(ShortTrailingStop+ShortPips)*Point) && (OrderStopLoss()>(Ask+Point*ShortTrailingStop)) ) 
	    {					
	     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*ShortTrailingStop,OrderClosePrice()-ShortTakeProfit*Point-ShortTrailingStop*Point,800,Purple);
	     return(0);	  					
		 }
     }
   }
   
   
   S_Profit=0;
   S_LastTicket=0;
   S_LastType=0;
	S_LastClosePrice=0;
	S_LastLots=0;	
   for(S_Count=0;S_Count<OrdersTotal();S_Count++)
    {
	  OrderSelect(S_Count, SELECT_BY_POS, MODE_TRADES);
	  if (OrderSymbol()==Symbol() && OrderMagicNumber() == ShortMagicNumber && OrderType()==OP_SELL) 
  	   {			
       S_LastTicket=OrderTicket();
	    S_LastType=OP_SELL;
 	    S_LastClosePrice=OrderClosePrice();
	    S_LastLots=OrderLots();
       S_Profit=S_Profit+OrderProfit();			 	   
      }
    }
   
   
   
     // Lets deal with lot sizing: We got fibo lot sizing at 161.8% increase, to SuperPacMan sizing to 250% increase
       
    if (S_OrderType==1 && S_ContinueOpening && ((Bid-S_LastPrice)>=ShortPips*Point || S_OpenOrders<1)) 
     {		
      SellPrice=Bid;				
      S_LastPrice=0;
      if (ShortTakeProfit==0) { S_tp=0; }
       else { S_tp=SellPrice-ShortTakeProfit*Point; }	
      if (ShortInitialStop==0) { S_sl=0; }
       else { S_sl=NormalizeDouble(SellPrice+ShortInitialStop*Point + (ShortMaxTrades-S_OpenOrders)* ShortPips*Point, Digits);  }
      if (S_OpenOrders!=0) 
       {
        S_OrderLotSize=G_OrderLotSize;			
        for(S_Count=1;S_Count<=S_OpenOrders;S_Count++)
         {
          if (UseFiboLotSizeProgression)
           {
            S_OrderLotSize = MathRound(MathPow(1.6180339,S_Count+1)/MathSqrt(5))* S_OrderLotSize;  // Fibonacci progression by Tross
           }
//=============================================SuperMrsPacMan Lot sizing=================================================//
            else                                                          // PacMan can start out with super lot size progression
           {  			                                                     // Or it can start increasing at a set # Called the Super Cell #. This is 
            if (SuperPacMan2.25)                                          // the # of open positions that it will increase progression size to 225%   
             {                                                            // So we can cover the losses on the first trades. USE GREAT CAUTION!! Because
              S_OrderLotSize=NormalizeDouble(S_OrderLotSize*2.25,2.25);   // they eat margin fast. 
                }                                                         //  Now we see where I got the name PacMan      
                 else                                                     //     
                  {  			      
                   if (SuperPacMan2.1)                                                   
                  {                                                               
                 S_OrderLotSize=NormalizeDouble(S_OrderLotSize*2.1,2.1);
               }	           
	          else 
	            {
	             if (PacManSuperCell && S_OpenOrders > SuperCell)
	              {
	               S_OrderLotSize=NormalizeDouble(S_OrderLotSize*3,3); 
	                } 
	                 else 
	                 {
	                 S_OrderLotSize=NormalizeDouble(S_OrderLotSize*2,2);
                   }
                 }
               } 
             }
           }
         
          
       } else { S_OrderLotSize=G_OrderLotSize; }   
	    OrderSend(Symbol(),OP_SELL,S_OrderLotSize,SellPrice,S_Slippage,S_sl,S_tp,"PacMan Sell",ShortMagicNumber,0,Red);		    		    
	    return(0);    
     }
       
    return(0);
  }  
  
int deinit()
  {
   return(0);
  }  
  
  //==================================================== Equity Profit Functions  ============================================<<


double SymbolProfitLong()
{
   L_Profit=0;

	for(int i=0;i<OrdersTotal();i++)
	{
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    if (NonMagic==0)
      {
       if (OrderSymbol()==Symbol() && OrderMagicNumber() == LongMagicNumber && OrderType()==OP_BUY) 
         {			
		    L_Profit=L_Profit+OrderProfit();	
	      }
	   }
	 if (NonMagic==1)
      {    
      if (OrderSymbol()==Symbol() && OrderType()==OP_BUY) 
	     {			
		   L_Profit=L_Profit+OrderProfit();	
	     }
	   }
	 }   
}

double SymbolProfitShort()
{
   S_Profit=0;
	
	for(int i=0;i<OrdersTotal();i++)
    {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    if (NonMagic==0)
      {
       if (OrderSymbol()==Symbol() && OrderMagicNumber() == ShortMagicNumber && OrderType()==OP_SELL)
         {			
		    S_Profit=S_Profit+OrderProfit();	
	      }
	   }
	 if (NonMagic==1)
      {    
      if (OrderSymbol()==Symbol() && OrderType()==OP_SELL)
	     {			
		   S_Profit=S_Profit+OrderProfit();	
	     }
	   }
    }
}
  

//==================================================== And here's the lovely Buy/Sell Signal Generator  ============================================<<


  
  
  


  


int OpenOrdersBasedOnTrendRSX()

{
      int SignalOrderType=3;
     double  ma1prev=0,cci1=0,ma=0,ma1=0,ma2=0,ma3=0,jmav=0;
        

     
     ma=iMA(NULL,0,6,0,MODE_LWMA,PRICE_WEIGHTED,1);        
     ma1=iMA(NULL,0,5,0,MODE_LWMA,PRICE_WEIGHTED,1);
     ma1prev=iMA(NULL,0,5,0,MODE_LWMA,PRICE_WEIGHTED,2);
     ma2=iMA(NULL,0,12,0,MODE_SMMA,PRICE_WEIGHTED,1);
     ma3=iMA(NULL,0,21,0,MODE_EMA,PRICE_TYPICAL,1);    
     jmav=iCustom(Symbol(),Period(),"volumeMA",0,1);
     cci1=iCCI( NULL, 0, CCI_PeroidFast, PRICE_TYPICAL, 1);
   
     
     
   
 
//----------------------------Signal Generater-----------------------------------------------//
        
         if (jmav > JMA_Volume && ma1  > ma1prev && ma1 > ma && ma1 > ma2  && ma2 >  ma3 && ma1 > ma3 && cci1< L_cciblock )
       {
       //Long
       SignalOrderType=2;
       
       }
       if (jmav > JMA_Volume && ma1 < ma1prev && ma1 < ma && ma1 < ma2  && ma2 < ma3 && ma1 < ma3  && cci1 > S_cciblock )
       {
       //Short
       SignalOrderType=1;
       
       
       
        }
        if (S_OpenOrders == HedgeNumber && hedge==true)
        {
        
        SignalOrderType=2;
        
        }
        if (  S_OpenOrders == 5  && hedge==true)
        {
        SignalOrderType=2;
        
        }
        if (L_OpenOrders == 5  && hedge==true)
        {
        SignalOrderType=1;
        
        }
        if (L_OpenOrders == HedgeNumber && hedge==true  )
        {
        
        SignalOrderType=1;
       
        }
        return(SignalOrderType);
       }
       
         
     
      
   
     


