//+------------------------------------------------------------------+
#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 ECNBroker = True;
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 UseSystemStopLoss = True;
extern bool UseFixedStopLoss = False;
extern int StopLoss = 100;
extern bool UseTakeProfit = 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 TimeFrameUsed = 0;
extern int MaxTradesPerDay = 2;




//Version 2.01

int OpenBarCount;
int CloseBarCount;

int RemainingTrades = 0;

datetime TimeFrameUsed1;

string BrokerType = "4-Digit Broker";
double BrokerMultiplier = 1;

int Current;
bool TickCheck = False;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   OpenBarCount = Bars;
   CloseBarCount = Bars;
   
   if(Digits == 3 || Digits == 5)
      {
      BrokerType = "5-Digit Broker";
      BrokerMultiplier = 10;
      }

   RemainingTrades = MaxTradesPerDay;

   if (EachTickMode) Current = 0; else Current = 1;

   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {

ObjectDelete("LongReEntry");
ObjectDelete("ShortReEntry");

   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() 


{
   int Order = SIGNAL_NONE;
   int Total, Ticket;
   double StopLossLevel, TakeProfitLevel;
   double PotentialStopLoss;
   double BreakEven; 
   double TrailingStop;



   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*BrokerMultiplier*100)/(Ask*MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_MINLOT)))*MarketInfo(Symbol(),MODE_MINLOT);
      }
   }

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+

if(TimeFrameUsed1 != iTime(NULL, TimeFrameUsed, 0))
   {
   RemainingTrades = MaxTradesPerDay;
   TimeFrameUsed1 = iTime(NULL, TimeFrameUsed, 0);
   }

string PreviousCandle = "None";
double Open1 = iOpen(NULL, TimeFrameUsed, 1);
double Close1 = iClose(NULL, TimeFrameUsed, 1);

if(Open1 > Close1) PreviousCandle = "Short";
if(Close1 > Open1) PreviousCandle = "Long";

//Check to see if re-entry is posible. 

datetime PeriodStart = iTime(NULL, TimeFrameUsed, 0);
datetime EarliestOrder = 0;
int TradeCount = 0;
int Totals = OrdersHistoryTotal();

for (int p = 0; p < Totals; p++)
   {
   OrderSelect(p, SELECT_BY_POS, MODE_HISTORY);
   if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber && (OrderType() == OP_BUY || OrderType() == OP_SELL) && OrderOpenTime() >= PeriodStart && OrderOpenTime() <= EarliestOrder)
      {
      EarliestOrder = OrderOpenTime();
      TradeCount++;
      }   
   }

bool FirstOrderTaken = False;
if(TradeCount > 0) FirstOrderTaken = True;

//Determine ReEntryPrice and stoploss
double LongReEntry = 0;
double ShortReEntry = 0;
double PreviousClose = iClose(NULL, TimeFrameUsed, 1);
double PreviousOpen = iOpen(NULL, TimeFrameUsed, 1);

if(PreviousCandle == "Long") 
   {
   LongReEntry = PreviousClose;
   ShortReEntry = 0;
   }

if(PreviousCandle == "Short") 
   {
   LongReEntry = 0;
   ShortReEntry = PreviousClose;
   }

string TradeTrigger = "None";
if(RemainingTrades > 0 && ( (!FirstOrderTaken && PreviousCandle == "Long") || (FirstOrderTaken && PreviousCandle == "Long" && Low[0] < LongReEntry && Close[0] >= LongReEntry) ) ) TradeTrigger = "Open Long";
if(RemainingTrades > 0 && ( (!FirstOrderTaken && PreviousCandle == "Short") || (FirstOrderTaken && PreviousCandle == "Short" && High[0] > ShortReEntry && Close[0] <= ShortReEntry) ) ) TradeTrigger = "Open Short";

string CloseTrigger = "None";
if(PreviousCandle == "Short") CloseTrigger = "Close Long";
if(PreviousCandle == "Long") CloseTrigger = "Close Short";

Comment("Broker Type: ", BrokerType, "\n",
        "Previous Candle: ", PreviousCandle, "\n",
        "Long ReEntry: ", LongReEntry, "\n",
        "Short ReEntry: ", ShortReEntry, "\n",
        "Remaining Trades: ", RemainingTrades, "\n",
        "Trade Trigger: ", TradeTrigger, "\n",
        "Close Trigger: ", CloseTrigger);
        
ObjectDelete("LongReEntry");
if(Close[0] < LongReEntry) 
   {
   ObjectCreate("LongReEntry", OBJ_HLINE, 0, 0, LongReEntry);
   ObjectSet("LongReEntry", OBJPROP_COLOR, Yellow);
   ObjectSet("LongReEntry", OBJPROP_STYLE, STYLE_DASH);
   ObjectSet("LongReEntry", OBJPROP_BACK, True);
   }

ObjectDelete("ShortReEntry");
if(Close[0] > ShortReEntry)
   {
   ObjectCreate("ShortReEntry", OBJ_HLINE, 0, 0, ShortReEntry);
   ObjectSet("ShortReEntry", OBJPROP_COLOR, Yellow);
   ObjectSet("ShortReEntry", OBJPROP_STYLE, STYLE_DASH);
   ObjectSet("ShortReEntry", OBJPROP_BACK, True);
   }

   //+------------------------------------------------------------------+
   //| 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)                                           |
            //+------------------------------------------------------------------+


  if(CloseTrigger == "Close Long") Order = SIGNAL_CLOSEBUY;

            //+------------------------------------------------------------------+
            //| 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;
            }
            
            PotentialStopLoss = OrderStopLoss();
            BreakEven = BreakEvenValue(OrderTicket(), MoveStopTo, MoveStopWhenPrice);
            TrailingStop = TrailingStopValue(OrderTicket(), TrailingStop);
            
            if(BreakEven > PotentialStopLoss && BreakEven != 0) PotentialStopLoss = BreakEven;
            if(TrailingStop > PotentialStopLoss && TrailingStop != 0) PotentialStopLoss = TrailingStop;
             
            if(PotentialStopLoss != OrderStopLoss()) OrderModify(OrderTicket(),OrderOpenPrice(), PotentialStopLoss, OrderTakeProfit(), 0, MediumSeaGreen); 
         
         } else {
        
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Sell)                                          |
            //+------------------------------------------------------------------+

if(CloseTrigger == "Close Short") Order = SIGNAL_CLOSESELL;

            //+------------------------------------------------------------------+
            //| 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;
            }
            
            PotentialStopLoss = OrderStopLoss();
            BreakEven = BreakEvenValue(OrderTicket(), MoveStopTo, MoveStopWhenPrice);
            TrailingStop = TrailingStopValue(OrderTicket(), TrailingStop);
            
            if(BreakEven < PotentialStopLoss && BreakEven != 0) PotentialStopLoss = BreakEven;
            if(TrailingStop < PotentialStopLoss && TrailingStop != 0) PotentialStopLoss = TrailingStop;
            
            if(PotentialStopLoss != OrderStopLoss()) OrderModify(OrderTicket(),OrderOpenPrice(), PotentialStopLoss, OrderTakeProfit(), 0, DarkOrange);
              
         }
      }
   }

   //+------------------------------------------------------------------+
   //| 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 && UseSystemStopLoss && (StopLossLevel != 0 || PreviousOpen >= StopLossLevel)) StopLossLevel = PreviousOpen;
         if (UseStopLoss && UseFixedStopLoss && (StopLossLevel != 0 || (Ask - StopLoss * Point) >= StopLossLevel)) StopLossLevel = Ask - StopLoss * Point; 
         if (!UseStopLoss) StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel = 0.0;
         Print(StopLossLevel+" BUY "+TakeProfitLevel);
         
         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");
                RemainingTrades--;
			} 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 && UseSystemStopLoss && (StopLossLevel == 0 || PreviousOpen <= StopLossLevel)) StopLossLevel = PreviousOpen;
         if (UseStopLoss && UseFixedStopLoss && (StopLossLevel == 0 || (Bid + StopLoss * Point)) <= StopLossLevel) StopLossLevel = Bid + StopLoss * Point; 
         if (!UseStopLoss) StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel = 0.0;
         Print(StopLossLevel+" BUY "+TakeProfitLevel);

         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");
                RemainingTrades--;
			} else {
				Print("Error opening SELL order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) OpenBarCount = Bars;
         return(0);
      }
   }

   if (!EachTickMode) CloseBarCount = Bars;

   return(0);
}


double BreakEvenValue (int OrderTicketNum, int MoveStopTo, int MoveStopwhenPrice)
   {
   //Select the appropriate order ticket
   OrderSelect(OrderTicketNum, SELECT_BY_TICKET, MODE_TRADES);
   
   //If the Order is a BUY order...
   if(OrderType() == OP_BUY)
      {
      //Check if the user wants to use the MoveStopOnce function and did it correctly
      if(MoveStopOnce && MoveStopWhenPrice > 0) 
         {
         //Check if the trade is above the required profit threshold
         if(Bid - OrderOpenPrice() >= Point * MoveStopWhenPrice) 
            {
            //Return the value of the stoploss
            return(OrderOpenPrice() + Point * MoveStopTo);
            }
         }
      }
   
   //If the Order is a SELL order...   
   if(OrderType() == OP_SELL)
      {
      //Check if the user wants to use the MoveStopOnce function and did it correctly
      if(MoveStopOnce && MoveStopWhenPrice > 0) 
         {
         //Check if the trade is above the required profit threshold
         if(OrderOpenPrice() - Ask >= Point * MoveStopWhenPrice) 
            {
            //Return the value of the stoploss
            return(OrderOpenPrice() - Point * MoveStopTo);
            }
         }
      }   
      
   if(OrderType() != OP_BUY || OrderType() != OP_SELL) return(0);
   }
   
double TrailingStopValue (int OrderTicketNum, int TrailingStop)
   {
   //Select the appropriate order ticket
   OrderSelect(OrderTicketNum, SELECT_BY_TICKET, MODE_TRADES);
   
   //If the Order is a BUY order...
   if(OrderType() == OP_BUY)
      {
      //Check if the user wants to use teh Trailingstop function and did it correctly
      if(UseTrailingStop && TrailingStop > 0) 
         {                 
         //Check to see that the profit threshold is met
         if(Bid - OrderOpenPrice() > Point * TrailingStop) 
            {
            //Return the value of the potential stoploss
            return(Bid - Point * TrailingStop);
            }
         }
      }
   //If the Order is a SELL order...
   if(OrderType() == OP_SELL)
      {
      //Check if the user wants to use teh Trailingstop function and did it correctly
      if(UseTrailingStop && TrailingStop > 0) 
         {                 
         //Check to see that the profit threshold is met
         if((OrderOpenPrice() - Ask) > (Point * TrailingStop)) 
            {
            //Return the value of the potential stoploss
            return(Ask + Point * TrailingStop);
            }
         }
      }     
   //If the trade is not the right order type, give a stoploss of 0   
   if(OrderType() != OP_BUY || OrderType() != OP_SELL) return(0);
   }