//+------------------------------------------------------------------+
//|          Free and OpenSource code under MIT License              |
//|              (https://opensource.org/licenses/MIT)               |
//|                 Copyright 2018 penyuperwira                      |
//|          (https://www.forexfactory.com/penyuperwira)             |
//|                  updated : 30.06.2018                            |
//+------------------------------------------------------------------+

#property copyright "BUY at market with TP/SL"
#property show_inputs
extern int    MagicNumber=274693;
extern string info="If 'lots' is set to 0, it will try to use the 'ordersize' GlobalVariable(F3)";
extern double start_lot=0.01;
extern double SLpips = 0;
extern double TPpips = 13;
extern string    Use_MM_lots="IF you want to decrease lot by Equity";
extern string    Enable_MM_Percentage_Lots="set Mode_Lots = [2]";
extern bool      Mode_MM_Lots=true;
extern double    MM_Risk_Percent_Lots=0.25;
extern double    MM_Lot_Digits_Decimal=2;
extern bool      ProfitPercen=true;
extern double    ProfitPercent=0.25;
extern bool      StopPercen=false;
extern double    StopPercent=5.00;

#include <stdlib.mqh>
double pip;
double Credit;
int digits;
double Balance;
double GetoLots;
//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
   double SL,TP;
   int i,Total;
   Total=OrdersTotal();
   int err;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

   double AE=AccountEquity();
//      pl_bal=AE;
//    if(T()==0){ pl_factor=AE/pl_bal; }
//+------------------------------------------------------------------+
   double Bprofit=0,BLots=0,BLotsSymbol=0,SLotsSymbol=0;
   for(int j=0; j<OrdersTotal(); j++)
     {
      int ticket2=OrderSelect(j,SELECT_BY_POS,MODE_TRADES);
      if(ticket2<0)//----added by tradercapaym
        {
         // Print("CL-849 , OrderSelect Error: ", GetLastError());
        }
      else
        {
         // Print("CL-853 , Order Select Successfully, Ticket # is : " + OrderTicket());
        }
      // if(cmd()>1) continue;
      if(OrderSymbol()==Symbol()) Bprofit+=OrderProfit();
      if(OrderSymbol()==Symbol() && OrderType()==OP_BUY) BLotsSymbol+=OrderLots();
      if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)SLotsSymbol+=OrderLots();
     }
//double tp_m2=Bprofit;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

   getpip();
   Credit=AccountCredit();
   Balance=AccountBalance();
   GetoLots=GetLots();
   double StopPercentage=(Balance+Credit) *(StopPercent/100);
   double StopPipsMath=NormalizeDouble((StopPercentage-(Bprofit))/((BLotsSymbol+GetoLots-SLotsSymbol)/10),0);
   double ProfitPercentage=(Balance+Credit) *(ProfitPercent/100);
   double ProfitpipsMath=NormalizeDouble((ProfitPercentage-(Bprofit))/((BLotsSymbol+GetoLots-SLotsSymbol)/10),0);
   if(start_lot==0) start_lot = GlobalVariableGet("ordersize");
   if(start_lot==0)
     {
      Alert("!!! "+WindowExpertName()+" "+Symbol()+": 'ordersize' not defined !!!");
     }
   double SLprice=0;
   double TPprice=0;
   double Price=Bid;
   if(!StopPercen   && SLpips        !=0) SLprice=Price-SLpips*pip;
   if(StopPercen    && StopPercent   !=0) SLprice=Price-StopPipsMath*pip;
   if(!ProfitPercen && TPpips        !=0) TPprice=Price+TPpips*pip;
   if(ProfitPercen  && ProfitPercent !=0) TPprice=Price+ProfitpipsMath*pip;
   int ticket=OrderSend(Symbol(),OP_BUY,GetoLots,Price,30,SLprice,TPprice,"",0,0,Green);
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

//  double SL,TP;
//int i,Total;
// int Dig=MarketInfo(Symbol(),MODE_DIGITS);     

//+------------------------------------------------------------------+

   if(Total>0)
     {
      if(SLpips>0)SL=SLprice;else SL=0;
      if(TPpips>0)TP=TPprice;else TP=0;
      for(i=Total-1; i>=0; i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
           {
            if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
              {
               int ticket4=OrderModify(OrderTicket(),OrderOpenPrice(),TP,SL,OrderExpiration(),CLR_NONE);
              }
            if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
              {
               int ticket3=OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,OrderExpiration(),CLR_NONE);
              }
           }
        }
     }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

   if(ticket<0)
     {
      err=GetLastError();
      Alert(Symbol()+":BUY FAILED ("+err+"): "+ErrorDescription(err));
        } else {
      Alert(Symbol()+":BUY at "+DoubleToStr(Price,Digits)+" TP="+DoubleToStr(TPprice,Digits)+",SL="+DoubleToStr(SLprice,Digits));
     }

   Alert("--- END "+WindowExpertName()+" "+Symbol());

   return(0);
  }
//+------------------------------------------------------------------+

//--------------------------------------------------------------------------------------
// getpip
//--------------------------------------------------------------------------------------

void getpip()
  {
   if(Digits==2 || Digits==4) pip=Point;
   else if(Digits==3 || Digits==5) pip = 10*Point;
   else if(Digits==6) pip = 100*Point;

   if(Digits==3 || Digits==2) digits=2;
   else digits=4;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
/* getpip*/

//end
//+------------------------------------------------------------------+
//|                       Money Management                           |
//+------------------------------------------------------------------+
//
double GetLots()
  {
   double MM_minlot = MarketInfo(Symbol(), MODE_MINLOT);
   double MM_maxlot = MarketInfo(Symbol(), MODE_MAXLOT);
   double MM_leverage= AccountLeverage();
   double MM_lotsize = MarketInfo(Symbol(),MODE_LOTSIZE);
   double MM_stoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
   double xecn=1; if(Digits==5 || Digits==3){xecn=10;}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
   if(Mode_MM_Lots)
     {
      double MM_lots;
      //MM_lots = NormalizeDouble(AccountFreeMargin() * MM_Risk_Percent_Lots/100 / 1000.0, MM_Lot_Digits_Decimal);
      //MM_lots = MathFloor((AccountFreeMargin() *AccountLeverage()*MM_Risk_Percent_Lots*Point*100)/(Ask*MarketInfo(Symbol(),MODE_LotSIZE)*MarketInfo(Symbol(),MODE_MINLOT )))*MarketInfo(Symbol(),MODE_MINLOT );
      MM_lots=NormalizeDouble((AccountFreeMargin()*MM_leverage*MM_Risk_Percent_Lots*Point*xecn*100/(Ask*MM_lotsize*MM_minlot)*MM_minlot),MM_Lot_Digits_Decimal);
      if(MM_lots < MM_minlot) MM_lots = MM_minlot;
      if(MM_lots > MM_maxlot) MM_lots = MM_maxlot;
      if(AccountFreeMargin()<Ask*MM_lots*MM_lotsize/MM_leverage)
        {
         Print("We have no money. Lots = ",MM_lots," , Free Margin = ",AccountFreeMargin());
         Comment("We have no money. Lots = ",MM_lots," , Free Margin = ",AccountFreeMargin());
        }
     }
   else MM_lots=NormalizeDouble(start_lot,Digits);
   return(MM_lots);
  }
//+------------------------------------------------------------------+
