//+------------------------------------------------------------------+
//|                                                      BuyThis.mq4 |
//+------------------------------------------------------------------+
#property link      "MaxM"
//de-comment the next line to revise the input in live-trading
//#property show_inputs
//if Lot is zero it will be calculated
extern double Lot=0.5;
extern double Maximum_Risk = 0.5;//in percent
extern int    SL=500;
extern int    TP=250;
extern int    MagicNumber  = 274693;
extern int    slippage     = 2;
extern string TradeComment = "Fib";
extern bool   debug=false;
string        curr;
//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
   double mLots;
   if (Lot==0) mLots = LotsOptimized();
   else mLots=Lot;
   OrderSend(Symbol(),OP_BUY, mLots, MarketInfo(Symbol(),MODE_ASK),slippage, 
             MarketInfo(Symbol(),MODE_ASK)-SL*MarketInfo(Symbol(),MODE_POINT), 
             MarketInfo(Symbol(),MODE_ASK)+TP*MarketInfo(Symbol(),MODE_POINT), TradeComment,MagicNumber, 0, CLR_NONE);
   return(0);
  }
//+----------------------------------------------------------------------------------------------------+
double LotsOptimized()
{
double minimum_lots=MarketInfo(Symbol(),MODE_MINLOT);
double max_lots=MarketInfo(Symbol(),MODE_MAXLOT);
double lot=Lot;   

     if (minimum_lots==0.001){ lot=NormalizeDouble(AccountEquity()*Maximum_Risk/(SL/10)/1000,3);{}}
     if (minimum_lots==0.01){ lot=NormalizeDouble(AccountEquity()*Maximum_Risk/(SL/10)/10000,2);{}}
     if (minimum_lots==0.1){ lot=NormalizeDouble(AccountEquity()*Maximum_Risk/(SL/10)/100000,1); {}}  
     if (minimum_lots==1){ lot=NormalizeDouble(AccountEquity()*Maximum_Risk/(SL/10)/1000000,0);{}}
     
     if (lot<=minimum_lots){lot  = minimum_lots;{}}
     if (lot>=max_lots){lot  = max_lots;{}}
     if (lot<=Lot){lot  = Lot;{}}      // prevent lots from decreasing
     if (Maximum_Risk==0){lot  = Lot;{}}

if (debug) Alert("AccountBalance "+AccountBalance());
if (debug) Alert("AccountEquity  "+AccountEquity());
if (debug) Alert("minimum_lots   "+minimum_lots);
if (debug) Alert("max_lots       "+max_lots);
if (debug) Alert("lot            "+lot);
if (debug) Alert("minimum_lots   "+minimum_lots);
if (debug) return(0);

return(lot);
}

