//+------------------------------------------------------------------+
//|                                                         MTS                                |
//|                                              Goal: Follow SAR with RSI         |
//|                                              Timeframe: Start with H1          |
//|                                              Author: FrankC                          |
//+---------------------------------------------------------------------------+

extern double TakeProfit = 40;
extern double Lots = 1;
extern double TrailingStop = 20;
extern double StopLoss = 40;
//+------------------------------------------------------------------+
//|                                                                                    |
//+------------------------------------------------------------------+
int start()
  {
   int cnt, ticket, total,CurrentTrades=0;
   int risk=3;
   double O,C,H,L,O1,C1,H1,L1,O2,C2,H2,L2,sl,sarNow,sarBefore,rsiNow,rsiBefore,lotMM;
   int  maxTrades=6, maxTradesPerPair=1;
   double marg=2*Point;
   datetime prevtime=0;
     
// initial data checks

   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return(0);  // check TakeProfit
     }
     
//Define the beginning of a new bar
if(prevtime == Time[0]) return(0);
prevtime = Time[0];

     sarNow = iSAR(NULL,0,0.05,0.5,0);
     sarBefore = iSAR(NULL,0,0.05,0.5,1);
     rsiNow = iRSI(NULL,0,14,PRICE_CLOSE,0);
     rsiBefore = iRSI(NULL,0,14,PRICE_CLOSE,1);

	  O=iOpen(NULL,0,0);   
	  C=iClose(NULL,0,0);
	  H=iHigh(NULL,0,0);
	  L=iLow(NULL,0,0);
	  
	  O1=iOpen(NULL,0,1);
	  C1=iClose(NULL,0,1);
	  H1=iHigh(NULL,0,1);
	  L1=iLow(NULL,0,1);
	  
	  O2=iOpen(NULL,0,2);
	  C2=iClose(NULL,0,2);
	  H2=iHigh(NULL,0,2);
	  L2=iLow(NULL,0,2);

// ==================================================  ===============================
// PYRAMIDING - LINEAR
// Money Management risk exposure compounding
// ==================================================  ===============================
  lotMM = (MathCeil(AccountBalance() * risk / 10000) / 10);

  if (lotMM < 0.1) lotMM = Lots;
  if (lotMM > 1.0) lotMM = MathCeil(lotMM);


//============ Check for open orders =====================================
 total=OrdersTotal();
 
 if (total < 6)
 {
 for(cnt=0;cnt<total||total<1;cnt++)
  {
   OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
   if(OrderSymbol() != Symbol())
    {
 
    if(AccountFreeMargin()<(1000*Lots))
     {
      Print("We have no money. Free Margin = ", AccountFreeMargin());
      return(0);  
     }      
// ===== check for long position (BUY) possibility

      if((C > sarBefore+marg) && (rsiNow > 50) && (rsiNow > rsiBefore) && (sarNow < O)) 
       {
         ticket=OrderSend(Symbol(),OP_BUY,lotMM,Ask,3,Bid-StopLoss*Point,Ask+TakeProfit*Point,"MTS",86731,0,Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES  ))  Comment("BUY order opened : ",OrderOpenPrice());
           }
         else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }  // end of if for BUY position
       
        
// ===== check for short position (SELL) possibility

      if((C < sarBefore+marg) && (rsiNow < 50) && (rsiNow < rsiBefore) && (sarNow > O))
        {
         ticket=OrderSend(Symbol(),OP_SELL,lotMM,Bid,3,Ask+  StopLoss*Point,Bid-TakeProfit*Point,"MTS",86731,0,Red);  
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES  )) Comment("SELL order opened : ",OrderOpenPrice());
           }
         else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        } // end of if for SHORT position
              
      return(0); 
  }        
 } 
} // end of it total < 6
    
//============ ORDER MANAGEMENT ===============================

   for(cnt=0;cnt<total||total<1;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
           {
            // should it be closed?
            if((C < sarBefore+marg) || (rsiNow < 50))
                {
                 OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet)  ; // close position
                 return(0); // exit
                }
            // 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
           {
            // should it be closed?
            if((C > sarBefore+marg) || (rsiNow > 50))
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet)  ; // close position
               return(0); // exit
              }
            // 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);
                    }
                 }
              }
           } 
          }
        }
   return(0);
 
} // end of int start() 