//+------------------------------------------------------------------+
#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 int StopLossBuffer = 5;
extern bool UseFixedStopLoss = False;
extern int StopLoss = 100;
extern bool UseTakeProfit = False;
extern bool UseSystemTakeProfit = True;
extern double TPDivisor = 2;
extern bool UseFixedTakeProfit = 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 string Remark2 = "";
extern string Remark3 = "== Pin Bar Settings ==";
extern bool      CheckPinBars=true;
extern bool      CheckI4Bars=false;
extern int       Min_Nose_Ratio=70;
extern int       Max_Body_Ratio=30;



//Version 2.01

int OpenBarCount;
int CloseBarCount;

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;
      }


   if (EachTickMode) Current = 0; else Current = 1;

   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {

ObjectDelete("UpperShift");
ObjectDelete("LowerShift");
   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                                                   |
   //+------------------------------------------------------------------+

//find most recent upper
bool UpperFound = False;
int UpperShift = 1;
while (!UpperFound)
   {
   if(iCustom(NULL, 0, "PinI4Bbar AHA 0.2", CheckPinBars, CheckI4Bars, Min_Nose_Ratio, Max_Body_Ratio, 0, UpperShift) > 0)
      {
      UpperFound = True;
      }
      else
      {
      UpperShift++;
      }
   }

//find most recent lower
bool LowerFound = False;
int LowerShift = 1;
while (!LowerFound)
   {
   if(iCustom(NULL, 0, "PinI4Bbar AHA 0.2", CheckPinBars, CheckI4Bars, Min_Nose_Ratio, Max_Body_Ratio, 1, UpperShift) > 0)
      {
      LowerFound = True;
      }
      else
      {
      LowerShift++;
      }
   }

double PinIndiUpper = iCustom(NULL, 0, "PinI4Bbar AHA 0.2", CheckPinBars, CheckI4Bars, Min_Nose_Ratio, Max_Body_Ratio, 0, Current + 1);
double PinIndiLower = iCustom(NULL, 0, "PinI4Bbar AHA 0.2", CheckPinBars, CheckI4Bars, Min_Nose_Ratio, Max_Body_Ratio, 1, Current + 1);

string TradeTrigger = "None";
if(PinIndiUpper != 0 && PinIndiLower != PinIndiUpper) TradeTrigger = "Open Short";
if(PinIndiLower != 0 && PinIndiLower != PinIndiUpper) TradeTrigger = "Open Long";

Comment("Trade Trigger: ", TradeTrigger);

ObjectDelete("LowerShift");
ObjectCreate("LowerShift", OBJ_VLINE, 0, iTime(NULL, 0, LowerShift), 0);
ObjectSet("LowerShift", OBJPROP_COLOR, Lime);
ObjectSet("LowerShift", OBJPROP_STYLE, STYLE_DASH);
ObjectSet("LowerShift", OBJPROP_BACK, True);

ObjectDelete("UpperShift");
ObjectCreate("UpperShift", OBJ_VLINE, 0, iTime(NULL, 0, UpperShift), 0);
ObjectSet("UpperShift", OBJPROP_COLOR, Red);
ObjectSet("UpperShift", OBJPROP_STYLE, STYLE_DASH);
ObjectSet("UpperShift", 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)                                           |
            //+------------------------------------------------------------------+


  

            //+------------------------------------------------------------------+
            //| 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)                                          |
            //+------------------------------------------------------------------+


            //+------------------------------------------------------------------+
            //| 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 && UseFixedStopLoss && Ask - StopLoss * Point > StopLossLevel) StopLossLevel = Ask - StopLoss * Point; 
         if (UseStopLoss && UseSystemStopLoss && (iLow(NULL, 0, Current + 1) - (StopLossBuffer * Point)) > StopLossLevel) StopLossLevel = iLow(NULL, 0, Current + 1) - (StopLossBuffer * Point);
         if (!UseStopLoss) StopLossLevel = 0.0;
         
         if (UseTakeProfit && UseFixedTakeProfit && TakeProfitLevel < (Ask + TakeProfit * Point)) TakeProfitLevel = Ask + TakeProfit * Point; 
         if (UseTakeProfit && UseSystemTakeProfit && TakeProfitLevel < Ask + ((Ask - (iLow(NULL, 0, Current + 1) - (StopLossBuffer * Point))) / TPDivisor)) TakeProfitLevel = Ask + (Ask - (iLow(NULL, 0, Current + 1) - (StopLossBuffer * Point))) / TPDivisor;
         if (!UseTakeProfit) 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");
			} 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 && UseFixedStopLoss && Bid + StopLoss * Point < StopLossLevel) StopLossLevel = Bid + StopLoss * Point; 
         if (UseStopLoss && UseSystemStopLoss && (iHigh(NULL, 0, Current + 1) - (StopLossBuffer * Point)) < StopLossLevel) StopLossLevel = iHigh(NULL, 0, Current + 1) + (StopLossBuffer * Point);
         if (!UseStopLoss) StopLossLevel = 0.0;
         
         if (UseTakeProfit && UseFixedTakeProfit && (Bid - TakeProfit * Point) < TakeProfitLevel) TakeProfitLevel = Bid - TakeProfit * Point; 
         if (UseTakeProfit && UseSystemTakeProfit && TakeProfitLevel > Bid + (Bid - ((iHigh(NULL, 0, Current + 1) - (StopLossBuffer * Point))) / TPDivisor)) TakeProfitLevel = Bid + (Bid - (iHigh(NULL, 0, Current + 1) - (StopLossBuffer * Point))) / TPDivisor;
         if (!UseTakeProfit) 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");
			} 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);
   }