////////////////////////////////////////////////////////////////////////////
//
// Buy one order with a specified lot size for the current symbol with a
// corresponding backup buy order. Optionally you can set a stop loss as
// pips calculated from price.
//
// This script supports four or five digit broker pricing.
//
// To receive the best possible price (i.e. price with the lowest slippage
// amount), set MinSlippage to 0 and MaxSlippage to an acceptable value
// defined by your trading rules. Using an example of 0 (Min) and 3 (Max),
// this script will submit an order at current price and slippage of 0. 
// If the broker accepts the order, the script is done. However, if the
// order is rejected this script will submit an order with the same price
// and slippage of 1, etc. until the order is accepted or the maximum
// slippage value is reached. To turn off this functionality set the
// MinSlippage and MaxSlippage to the same value (e.g. 3).
//
////////////////////////////////////////////////////////////////////////////
#property copyright "Steve"
#property link      ""
#property show_inputs
#include <stdlib.mqh>

// Inputs
extern string Title1           = "Buy Order";
extern double Lots             = 0.1;
extern double ScaleInLots      = 0.5;
extern double ScaleReduction   = 0.1;
extern double MinLots          = 0.1; // Robert added so check can be made for microlots
extern int    MinSlippage      = 0;
extern int    MaxSlippage      = 3;
extern int    StopLossPips     = 50;
extern int    TakeProfitPips   = 25;
extern int    Number_Of_Scaled_Trades = 2;
extern int    Scale_Width      = 5;
extern bool   Use_Multiplier   = false;
extern bool   UseTradeExpire   = false;

extern bool   createBackup     = true;
extern string Title2           = "Backup Buy Order";
extern double BackupPercentage = 75;

extern string Title3           = "Other";
extern string TradeComment     = "";
extern int    MagicNumber      = 12001;

double   myPoint; // Robert added for better handling of 4 and 5 digit brokers

int init() {
   myPoint = SetPoint();
   return (0);
}

int start()
{
   // Variables
   double price        = 0.0;
   double stopLoss     = 0.0;
   double takeProfit   = 0.0;
   double trade_price  = 0.0;
   double next_trade_price  = 0.0;
   double BackupLots   = 0.0;
   double backupPrice  = 0.0;
   double Save_Lots    = 0.0;
   int    tries        = 0;
   int    ticket       = 0;
   int    point_width  = 0;
   int    cnt          = 0;
   datetime ExpDate = 0;

   // Min/Max slippage
   if (MinSlippage < 0) MinSlippage = 0;
   if (MinSlippage > MaxSlippage) MinSlippage = MaxSlippage;

   if(Use_Multiplier == true)
   {
      Lots = (Lots * 1.5);
   }

   BackupLots = (Lots * 2);
   // Create order
   for (tries = MinSlippage; tries <= MaxSlippage; tries++)
   {
   // Refresh rates
      RefreshRates();
      price = Ask;
      ticket = OrderSend(Symbol(), OP_BUY, Lots, price, tries, 0, 0, TradeComment, MagicNumber, 0, Green);
      if (ticket > 0)
      {
         if(OrderSelect(ticket, SELECT_BY_TICKET) == true)
         {
// Robert moved code here to do calculations based on OrderOpenPrice 

   // Calculate price
           price = OrderOpenPrice();

   // Calculate take profit
   // Calculate stop loss
   // Calcualte backup price
           if(TakeProfitPips > 0) takeProfit  = (price + (TakeProfitPips * myPoint));
           stopLoss    = (price - (StopLossPips * myPoint));
           backupPrice = (price - ((StopLossPips * (BackupPercentage / 100)) * myPoint));
           
   // Normalize stoploss / takeprofit to the proper # of digits.
           if (Digits > 0) 
           {
             stopLoss = NormalizeDouble( stopLoss, Digits);
             takeProfit = NormalizeDouble( takeProfit, Digits); 
             backupPrice = NormalizeDouble( backupPrice, Digits); 
           }

         // Modify order
           if (OrderModify(ticket, OrderOpenPrice(), stopLoss, takeProfit, 0, CLR_NONE))
           {
               PlaySound("ok.wav");
               if(UseTradeExpire == true) ExpDate = TimeCurrent() + 43200;
               trade_price = OrderOpenPrice();
               point_width = Scale_Width;
               Lots = ScaleInLots;
                  for(cnt = 0 ; cnt < Number_Of_Scaled_Trades ; cnt++)
                  {
                     if(Use_Multiplier == true)
                     {
                        if(cnt > 0)
                        {
                           Lots = (Lots - ScaleReduction);
                           if(Lots < MinLots) // Allow for use of microlots
                           {
                              Lots = MinLots;
                           }
                        }
                        Save_Lots = Lots;
                        Lots = (Lots * 1.5);
                     }
                     else if(cnt > 0)
                     {
                        Lots = (Lots - ScaleReduction);
                        if(Lots < MinLots)  // Allow for use of MicroLots
                        {
                           Lots = MinLots;
                        }
                     }
                     next_trade_price = trade_price+(point_width*myPoint);
                     next_trade_price = NormalizeDouble(next_trade_price, Digits);
                     ticket=OrderSend(OrderSymbol(),OP_BUYSTOP,Lots,next_trade_price,MaxSlippage,stopLoss,takeProfit,TradeComment,MagicNumber,ExpDate,Green);
                     point_width = point_width + Scale_Width;
                     if(Use_Multiplier == true)
                     {
                        Lots = Save_Lots;
                     }
                  }
            }
         }
         else
         {
            Alert("Failed to set stop loss of ", stopLoss, " and/or take profit of ", takeProfit, " for ", Symbol(), " buy order ", ticket, ". Error: ", ErrorDescription(GetLastError()));
            Alert("Failed to create ", Symbol(), " backup buy limit order. Error: Failed to set stop loss and/or take profit on buy order.");
            createBackup = false;
         }
      }
 
      WindowScreenShot("MMMBE_"+Symbol()+ "_" + TimeToStr(iTime(NULL, 0, 0),TIME_DATE)+"_1_"+TimeHour(iTime(NULL, 0, 0))+".gif",1024,768);
      OrderPrint();
      break;
   }

   if (ticket < 1)
   {
      Alert("Failed to create ", Symbol(), " buy order at a price of ", price, ". Error: ", ErrorDescription(GetLastError()));
      Alert("Failed to create ", Symbol(), " backup buy limit order. Error: Failed to create ", Symbol(), " buy order.");
   }

   else if (createBackup == true)
   {
      // Create backup order
      if (OrderSend(Symbol(), OP_BUYLIMIT, BackupLots, backupPrice, MaxSlippage, stopLoss, takeProfit, TradeComment, MagicNumber, ExpDate, Green) > 0)
      {
         PlaySound("ok.wav");
         OrderPrint();
      }
      else
      {
         Alert("Failed to create ", Symbol(), " backup buy limit order at a price of ", backupPrice, ", stop loss of ", stopLoss, " and take profit of ", takeProfit, ". Error: ", ErrorDescription(GetLastError()));
      }
   }

   return(0);
}

double SetPoint()
{
   double mPoint;
   
   if (Digits < 4)
      mPoint = 0.01;
   else
      mPoint = 0.0001;
   
   return(mPoint);
}

