//+------------------------------------------------------------------+
#define SIGNAL_NONE 0
#define SIGNAL_BUY   1
#define SIGNAL_SELL  2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

#property copyright "Ronald Raygun"

extern string Remark1 = "== Main Settings ==";
extern int MagicNumber = 0;
extern bool SignalsOnly = False;
extern bool Alerts = False;
extern bool SignalMail = False;
extern bool PlaySounds = False;
extern bool EachTickMode = True;
extern double Lots = 0;
extern bool MoneyManagement = False;
extern int Risk = 0;
extern int Slippage = 5;
extern  bool UseStopLoss = True;
extern bool OverRideStopLoss = False;
extern int StopLoss = 100;
extern bool UseTakeProfit = False;
extern bool OverRideTakeProfit = False;
extern int TakeProfit = 60;
extern bool UseTrailingStop = False;
extern int TrailingStop = 30;
extern bool MoveStopOnce = False;
extern int MoveStopWhenPrice = 50;
extern int MoveStopTo = 1;
extern int PipBuffer = 20; 
extern string Remark2 = "";
extern string Remark3 = "== Day Settings ==";
extern bool TradeSunday = False;
extern bool TradeMonday = False;
extern bool TradeTuesday = True;
extern bool TradeWednesday = True;
extern bool TradeThursday = True;
extern bool TradeFriday = False;


//Version 2.01

int OpenBarCount;
int CloseBarCount;

int SellCount;
int BuyCount;

int Current;
bool TickCheck = False;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   OpenBarCount = Bars;
   CloseBarCount = Bars;

   if (EachTickMode) Current = 0; else Current = 1;

   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {
   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() 


{
   int Order = SIGNAL_NONE;
   int Total, Ticket;
   double StopLossLevel, TakeProfitLevel;



   if (EachTickMode && Bars != CloseBarCount) TickCheck = False;
   Total = OrdersTotal();
   Order = SIGNAL_NONE;

//Money Management sequence
 if (MoneyManagement)
   {
      if (Risk<1 || Risk>100)
      {
         Comment("Invalid Risk Value.");
         return(0);
      }
      else
      {
         Lots=MathFloor((AccountFreeMargin()*AccountLeverage()*Risk*Point*100)/(Ask*MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_MINLOT)))*MarketInfo(Symbol(),MODE_MINLOT);
      }
   }

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+
int CurrentDay;

if(CurrentDay != TimeDayOfYear(TimeCurrent())) {
   CurrentDay = TimeDayOfYear(TimeCurrent());
   BuyCount = 0;
   SellCount = 0;
   }
   

//Calculate Pivot Points
double Highd1 = iHigh(NULL, PERIOD_D1, Current + 1);
double Lowd1 = iLow(NULL, PERIOD_D1, Current + 1);
double Closed1 = iClose(NULL, PERIOD_D1, Current + 1);

double Pivot = (Highd1 + Lowd1 + Closed1) / 3;
double R1 = Pivot * 2 - Lowd1;
double R2 = Pivot + (Highd1 - Lowd1);
double R3 = Highd1 + 2 * (Pivot - Lowd1);
double S1 = Pivot * 2 - Highd1;
double S2 = Pivot - (Highd1 - Lowd1);
double S3 = Lowd1 - 2 * (Highd1 - Pivot);

//Determine current Day
string Today;
if(DayOfWeek() == 0) Today = "Sunday";
if(DayOfWeek() == 1) Today = "Monday";
if(DayOfWeek() == 2) Today = "Tuesday";
if(DayOfWeek() == 3) Today = "Wednesday";
if(DayOfWeek() == 4) Today = "Thursday";
if(DayOfWeek() == 5) Today = "Friday";
if(DayOfWeek() == 6) Today = "Saturday";

string TradingDay = "Cannot Trade";
if(Today == "Sunday" && TradeSunday) TradingDay = "Can Trade";
if(Today == "Monday" && TradeSunday) TradingDay = "Can Trade";
if(Today == "Tuesday" && TradeSunday) TradingDay = "Can Trade";
if(Today == "Wednesday" && TradeSunday) TradingDay = "Can Trade";
if(Today == "Thursday" && TradeSunday) TradingDay = "Can Trade";
if(Today == "Friday" && TradeSunday) TradingDay = "Can Trade";


//Previous Day's Range
double PreviousRange = iHigh(NULL, PERIOD_D1, 1) - iLow(NULL, PERIOD_D1, 1);

//Previous Week's Range
double PreviousWeek = iHigh(NULL, PERIOD_W1, 1) - iLow(NULL, PERIOD_W1, 1);

double BuyPrice = R1 + (PipBuffer * Point);
double SellPrice = S1 - (PipBuffer * Point);
double BuyDistance = ((R2 - R1) * 2) / 3;
double SellDistance = ((S1 - S2) * 2) / 3;
double BuyClose = R1 - BuyDistance;
double SellClose = S1 + SellDistance;
double BuyProfit = R2 - (PipBuffer * Point);
double SellProfit = S2 + (PipBuffer * Point);




string TradeTrigger = "None";
if(BuyCount < 1 && TradingDay == "Can Trade" && Close[0] >= BuyPrice && Open[0] < BuyPrice) {
   TradeTrigger = "Open Long";
   }
if(SellCount < 1 && TradingDay == "Can Trade" && Close[0] <= SellPrice && Open[0] > SellPrice) {
   TradeTrigger = "Open Short";
   }


Comment("Today is: ", Today, "\n",
        "R3: ", R3, "\n",
        "R2: ", R2, "\n",
        "R1: ", R1, "\n",
        "Pivot: ", Pivot, "\n",
        "S1: ", S1, "\n",
        "S2: ", S2, "\n",
        "S3: ", S3, "\n",
        "Previous Week Range: ", PreviousWeek, "\n",
        "Previous Day Range: ", PreviousRange, "\n",
        "Buy Price: ", BuyPrice, "\n",
        "Sell Price: ", SellPrice, "\n",
        "Trade Trigger: ", TradeTrigger);


   //+------------------------------------------------------------------+
   //| Variable End                                                     |
   //+------------------------------------------------------------------+

   //Check position
   bool IsTrade = False;

   for (int i = 0; i < Total; i ++) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() <= OP_SELL &&  OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) {
         IsTrade = True;
         if(OrderType() == OP_BUY) {
         
            
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Buy)                                           |
            //+------------------------------------------------------------------+


  

            //+------------------------------------------------------------------+
            //| Signal End(Exit Buy)                                             |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != CloseBarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
               if (!EachTickMode) CloseBarCount = Bars;
               IsTrade = False;
               continue;
            }
            //MoveOnce
            if(MoveStopOnce && MoveStopWhenPrice > 0) {
               if(Bid - OrderOpenPrice() >= Point * MoveStopWhenPrice) {
                  if(OrderStopLoss() < OrderOpenPrice() + Point * MoveStopTo) {
                  OrderModify(OrderTicket(),OrderOpenPrice(), OrderOpenPrice() + Point * MoveStopTo, OrderTakeProfit(), 0, Red);
                     if (!EachTickMode) CloseBarCount = Bars;
                     continue;
                  }
               }
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) {                 
               if(Bid - OrderOpenPrice() > Point * TrailingStop) {
                  if(OrderStopLoss() < Bid - Point * TrailingStop) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0, MediumSeaGreen);
                     if (!EachTickMode) CloseBarCount = Bars;
                     continue;
                  }
               }
            }
         } else {
        
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Sell)                                          |
            //+------------------------------------------------------------------+


            //+------------------------------------------------------------------+
            //| Signal End(Exit Sell)                                            |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != CloseBarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Close Sell");
               if (!EachTickMode) CloseBarCount = Bars;
               IsTrade = False;
               continue;
            }
            //MoveOnce
            if(MoveStopOnce && MoveStopWhenPrice > 0) {
               if(OrderOpenPrice() - Ask >= Point * MoveStopWhenPrice) {
                  if(OrderStopLoss() > OrderOpenPrice() - Point * MoveStopTo) {
                  OrderModify(OrderTicket(),OrderOpenPrice(), OrderOpenPrice() - Point * MoveStopTo, OrderTakeProfit(), 0, Red);
                     if (!EachTickMode) CloseBarCount = Bars;
                     continue;
                  }
               }
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) {                 
               if((OrderOpenPrice() - Ask) > (Point * TrailingStop)) {
                  if((OrderStopLoss() > (Ask + Point * TrailingStop)) || (OrderStopLoss() == 0)) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop, OrderTakeProfit(), 0, DarkOrange);
                     if (!EachTickMode) CloseBarCount = Bars;
                     continue;
                  }
               }
            }
         }
      }
   }

   //+------------------------------------------------------------------+
   //| Signal Begin(Entry)                                              |
   //+------------------------------------------------------------------+

if(TradeTrigger == "Open Long") Order = SIGNAL_BUY;
if(TradeTrigger == "Open Short") Order = SIGNAL_SELL;

   //+------------------------------------------------------------------+
   //| Signal End                                                       |
   //+------------------------------------------------------------------+

   //Buy
   if (Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != OpenBarCount)))) {
      if(SignalsOnly) {
         if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + "Buy Signal");
         if (Alerts) Alert("[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + "Buy Signal");
         if (PlaySounds) PlaySound("alert.wav");
     
      }
      
      if(!IsTrade && !SignalsOnly) {
         //Check free margin
         if (AccountFreeMargin() < (1000 * Lots)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss && !OverRideStopLoss) StopLossLevel = BuyClose;
         if (UseStopLoss && OverRideStopLoss) StopLossLevel = Ask - StopLoss * Point; 
         if (!UseStopLoss && !OverRideStopLoss) StopLossLevel = 0.0;
         
         if (UseTakeProfit && !OverRideTakeProfit) TakeProfitLevel = BuyProfit;
         if (UseTakeProfit && OverRideTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; 
         if (!UseTakeProfit && !OverRideTakeProfit) TakeProfitLevel = 0.0;

         Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
				Print("BUY order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + "Buy Signal");
			       if (Alerts) Alert("[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + "Buy Signal");
                if (PlaySounds) PlaySound("alert.wav");
                BuyCount++;
			} else {
				Print("Error opening BUY order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) OpenBarCount = Bars;
         return(0);
      }
   }

   //Sell
   if (Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != OpenBarCount)))) {
      if(SignalsOnly) {
          if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + "Sell Signal");
          if (Alerts) Alert("[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + "Sell Signal");
          if (PlaySounds) PlaySound("alert.wav");
         }
      if(!IsTrade && !SignalsOnly) {
         //Check free margin
         if (AccountFreeMargin() < (1000 * Lots)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss && !OverRideStopLoss) StopLossLevel = SellClose;
         if (UseStopLoss && OverRideStopLoss) StopLossLevel = Bid + StopLoss * Point;
         if (!UseStopLoss && !OverRideStopLoss) StopLossLevel = 0.0;
         
         if (UseTakeProfit && !OverRideTakeProfit) TakeProfitLevel = SellProfit;
         if (UseTakeProfit && OverRideTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point;
         if (!UseTakeProfit && !OverRideTakeProfit) TakeProfitLevel = 0.0;
         

         Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
				Print("SELL order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + "Sell Signal");
			       if (Alerts) Alert("[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + "Sell Signal");
                if (PlaySounds) PlaySound("alert.wav");
                SellCount++;
			} else {
				Print("Error opening SELL order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) OpenBarCount = Bars;
         return(0);
      }
   }

   if (!EachTickMode) CloseBarCount = Bars;

   return(0);
}