//+------------------------------------------------------------------+
//| script "send pending buy stop order with expiration data"
//| Variable spacing function added   
//| Variable TP function added
//+------------------------------------------------------------------+
#property show_inputs

extern double Lots = 0.1;
extern bool   UseMoneyMgmt = false;
extern double RiskPercent = 2;
extern bool   UseStop = true;
extern bool   UseTakeProfit = true;
extern double StopLoss = 60;
extern double TakeProfit = 30;
extern string Note="0 in Entry field means Market Order Sell";
extern double Entry = 0.0000;

string Input = " Sell Price ";

extern int maxtrade = 1; 
extern double lotsize = 0.3; 
extern double exphours = 440;
extern int pipspace1 = 30;
extern double ExpectedPrice = 0;
extern int takeprofit = 30;
extern double StopLoss2 = 60;
extern string UserComment = "some comment";
extern int MagicNumber = 16384;
double   myPoint;




//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
  double Risk = RiskPercent / 100;
  if (UseMoneyMgmt)
    Lots = NormalizeDouble( AccountBalance()*Risk/StopLoss/(MarketInfo(Symbol(), MODE_TICKVALUE)),2); 
  int Mode = OP_SELLSTOP;
  if (Bid < Entry && Entry > 0) Mode = OP_SELLLIMIT; 
  if (Entry == 0)  {Entry = Bid; Mode = OP_SELL;}
   myPoint = SetPoint(Symbol()); 
  double  SLS = Entry+StopLoss*myPoint, TPS = Entry - TakeProfit * myPoint;
  if (UseStop == false) SLS = 0;
  if (UseTakeProfit == false) TPS = 0;
  if(Lots > 0)
   OrderSend(Symbol(),Mode, Lots, Entry, 2, SLS, TPS, "Sell Script",0, NULL, Red);
    
 int  ticket,expiration;
   double e;
   if (ExpectedPrice < 0.1) e = Bid ; else e = ExpectedPrice;   
   expiration=TimeCurrent()+PERIOD_D1*(exphours*2.5);
   for(int i=maxtrade-1;i>=0;i--)

   while(true)
     
   {  double  SLS2 = Entry+StopLoss2*myPoint;
      
//      ticket=OrderSend(Symbol(),OP_BUYSTOP,lotsize,e+(pipspace1*myPoint),SLS2,0,e+((pipspace1+takeprofit)*myPoint),UserComment,MagicNumber,expiration,Green);
      ticket=OrderSend(Symbol(),OP_BUYSTOP,lotsize,e+(pipspace1*myPoint),0, SLS2,e+((pipspace1+takeprofit)*myPoint),UserComment,MagicNumber,expiration,Green);
      pipspace1=pipspace1;
      if(ticket<=0) Print("Error = ",GetLastError());
      else { Print("ticket = ",ticket); break; }
      Sleep(5000); }
            
   return(0);  }

double SetPoint(string mySymbol)
{  double myPoint, myDigits;
   myDigits = MarketInfo (mySymbol, MODE_DIGITS);
   if (myDigits < 4)     myPoint = 0.01;
   else
       myPoint = 0.0001;
   
   return(myPoint);}