//+------------------------------------+
//| TRUE_SCALPER                       |
//+------------------------------------+

#property link      "http://www.forex-instruments.info/"


// variables declared here are GLOBAL in scope

#property copyright "Jacob Yego"
#property link      "http://www.PointForex.com/"
// MT4 conversion and some improvements by Ron Thompson

// generic user input
extern double     Lots              =0.1;
extern int        TakeProfit        =44;
static int        BarsTSL           =3;
static int        BarsTP            =13;
static int        BarsSL            =13;
static int        BarShift          =0;
static int        ScalpProfit       =100;
extern int        StopLoss          =90;
static int        RSIPos            =50;
static int        RSINeg            =50;
static int        Slippage          =2;
static int        abandon           =101;
extern double     MaximumRisk       =0.02;
static double     DecreaseFactor    =3;
double            SPoint;

double            Spread;

double            SDigits;

double CalcSlBuy()   { return (MathMin((Low[Lowest(NULL,0,MODE_LOW,BarsSL,BarShift)]-Spread),(Bid-(StopLoss*Point)))); }
double CalcSlSell()  { return (MathMax((High[Highest(NULL,0,MODE_HIGH,BarsSL,BarShift)]+Spread),(Ask+(StopLoss*Point)))); }
double CalcTpBuy()   { return (MathMin((High[Highest(NULL,0,MODE_HIGH,BarsTP,BarShift)]-Spread),(Ask+(TakeProfit*Point)))); }
double CalcTpSell()  { return (MathMax((Low[Lowest(NULL,0,MODE_LOW,BarsTP,BarShift)]+Spread),(Bid-(TakeProfit*Point)))); }

double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
   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);
     }
   if(lot<0.1) lot=0.1;
   return(lot);
   }

void PrintComments() {  Comment("Current Time: ",Hour(),":",Minute(),"\n");  }

// Bar handling
datetime bartime=0;
int      bartick=0;

//+------------------------------------+
//| EA load code                       |
//+------------------------------------+

int init()
  {
   // set up the symbol optimizations
    if (Symbol()=="GBPUSD")  {TakeProfit= 44; StopLoss= 90; abandon=101;}
    if (Symbol()=="AUDUSD")  {TakeProfit= 60; StopLoss= 23; abandon=103;}
    if (Symbol()=="EURAUD")  {TakeProfit= 95; StopLoss=141; abandon=33;}
    if (Symbol()=="EURCHF")  {TakeProfit= 81; StopLoss= 77; abandon=97;}
    if (Symbol()=="EURGBP")  {TakeProfit= 11; StopLoss= 77; abandon=108;}
    if (Symbol()=="EURJPY")  {TakeProfit= 38; StopLoss= 75; abandon=183;}
    if (Symbol()=="EURUSD")  {TakeProfit=196; StopLoss= 22; abandon=103;}
    if (Symbol()=="GBPCHF")  {TakeProfit= 79; StopLoss= 98; abandon=113;}
    if (Symbol()=="GBPJPY")  {TakeProfit= 13; StopLoss= 98; abandon=117;}
    if (Symbol()=="GBPUSD")  {TakeProfit= 55; StopLoss=100; abandon=69;}
    if (Symbol()=="USDCAD")  {TakeProfit= 66; StopLoss= 76; abandon=106;}
    if (Symbol()=="USDCHF")  {TakeProfit=117; StopLoss= 78; abandon=111;}
    if (Symbol()=="USDJPY")  {TakeProfit= 53; StopLoss= 74; abandon=110;}


  }


//+------------------------------------+
//| EA unload code                     |
//+------------------------------------+

int deinit()
  {
  }



//+------------------------------------+
//| EA main code                       |
//+------------------------------------+

int start()
  {
SDigits   =MarketInfo(NULL, MODE_DIGITS);
SPoint     =MarketInfo(NULL, MODE_POINT);Spread     =Ask-Bid;
   double p=Point;
   int      cnt=0;

   int      OrdersPerSymbol=0;

   double  bullMA3=0;
   double  bearMA7=0;
   double  RSI=0;
   bool    RSIPOS=0;
   bool    RSINEG=0;
   
   double TP;
   double SL;


   // Error checking & bar counting
   if(AccountFreeMargin()<(200*Lots))        {Print("-----NO MONEY"); 
return(0);}
   if(Bars<100)                               {Print("-----NO BARS "); 
return(0);}
   if(bartime!=Time[0])                       {bartime=Time[0]; 
bartick++;       }

   // 3-period moving average on Bar[1]
   bullMA3=iMA(Symbol(),0,3,0,MODE_EMA,PRICE_CLOSE,1);
   // 7-period moving average on Bar[1]
   bearMA7=iMA(Symbol(),0,7,0,MODE_EMA,PRICE_CLOSE,1);
   
   // 2-period moving average on Bar[2]
   RSI=iRSI(Symbol(),0,2,PRICE_CLOSE,2);

   // Determine what polarity RSI is in
   if(RSI>RSIPos) {RSIPOS=true;  RSINEG=false;}
   if(RSI<RSINeg) {RSIPOS=false; RSINEG=true;}


   // count the open orders for this symbol 
   OrdersPerSymbol=0;
   for(cnt=OrdersTotal();cnt>=0;cnt--)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if( OrderSymbol()==Symbol() )
        {
         OrdersPerSymbol++;
        }
     }


   // place new order based on direction
   // only if no other orders are open on this Symbol 
   if(OrdersPerSymbol==0)
     {
      //ENTRY Ask(buy, long) 
      if(bullMA3>(bearMA7+p) && RSINEG)
		  {
		   SL=CalcSlBuy();//Ask-(StopLoss*p);
		   TP=CalcTpBuy();//Ask+(TakeProfit*p);
         OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,Slippage,SL,TP,"TSv11-1.11",0,0,White);
         bartick=0;
        }
        
      //ENTRY Bid (sell, short)
      if(bullMA3<(bearMA7-p) && RSIPOS)
        {
		   SL=CalcSlSell();//Bid+(StopLoss*p);
		   TP=CalcTpSell();//Bid-(TakeProfit*p);
         OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,Slippage,SL,TP,"TSv11-1.11",0,0,Red);
         bartick=0;
        }
     } //if


   // have we run out of ticks for average time-to-profit?
   if(OrdersPerSymbol==1 && bartick==abandon)
     {

      if(OrderType()==OP_BUY)
        {
         // close losing BUY order to avoid more loss
         OrderClose(OrderTicket(),Lots,Bid,Slippage,White);
         // setup and trade new order 
         SL=CalcSlBuy();//Bid+(StopLoss*p);
         TP=CalcTpBuy();//Bid-(TakeProfit*p);
         OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,Slippage,SL,TP,"TSv11-1.11",0,0,Red);
         // bump bartick to prevent multiple buys
         bartick++;
        } // if BUY

      if(OrderType()==OP_SELL)
        {
         // close losing SELL order to avoid more loss
         OrderClose(OrderTicket(),Lots,Ask,Slippage,Red);
         // setup and trade new order 
         SL=CalcSlSell();//Ask-(StopLoss*p);
         TP=CalcTpSell();//Ask+(TakeProfit*p);
         OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,Slippage,SL,TP,"TSv11-1.11",0,0,White);
         // bump bartick to prevent multiple buys
         bartick++;
        } //if SELL

     } //if OrdersPerSymbol
     for(cnt=0;cnt<OrdersTotal();cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if( OrderSymbol()==Symbol() )
         {
         if(OrderType()==OP_BUY)
            {
            if (OrderMagicNumber()==0)
               {
               if(  Bid-OrderOpenPrice() > (ScalpProfit*Point)  )
                  {
                  OrderClose(OrderTicket(),Lots,Bid,0,White);
                  return(0);
                  } // if profit made
                 } // if magic
                } // if Buy
 
         if(OrderType()==OP_SELL)
            {           
            if (OrderMagicNumber()==0)
               {
               if(  OrderOpenPrice()-Ask > (ScalpProfit*Point)   )
                  {
                  OrderClose(OrderTicket(),Lots,Ask,0,Red);
                  return(0);
                  } // if profit made
                 } // if magic
               } //if Sell
              } // if Symbol
             } // for

   double btsl,stsl;int i;
   for(i = 0; i < OrdersTotal(); i++ ) {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderMagicNumber()==0 &&
         OrderSymbol()==Symbol())  {
         btsl=(Low[Lowest(NULL,0,MODE_LOW,BarsTSL,BarShift)]-Spread);               
         stsl=(High[Highest(NULL,0,MODE_HIGH,BarsTSL,BarShift)]+Spread);         
         if(OrderType()==OP_BUY &&
            Bid>OrderOpenPrice() &&
            btsl>OrderStopLoss() &&
            btsl>OrderOpenPrice())   {
               OrderModify(OrderTicket(),
                           OrderOpenPrice(),
                           btsl,
                           OrderTakeProfit(),
                           0,
                           LimeGreen);
               return(0);
         }
         if(OrderType()==OP_SELL &&
            Ask<OrderOpenPrice() &&
            stsl<OrderStopLoss() &&
            stsl<OrderOpenPrice())   {
               OrderModify(OrderTicket(),
                           OrderOpenPrice(),
                           stsl,
                           OrderTakeProfit(),
                           0,
                           HotPink);
               return(0);
         }
      }
   }
   PrintComments();
   return(0);
} // start()

