//+------------------------------------------------------------------+
#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 bool UseTimes = True;
extern int HourStart = 8;
extern int HourEnd = 16;
extern double Lots = 0;
extern bool MoneyManagement = False;
extern int Risk = 0;
extern int Slippage = 5;
extern  bool UseStopLoss = True;
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 string Remark2 = "";
extern string Remark3 = "== Indicator Settings ==";
extern int       rsi_period=8;
extern int       rsi_price=PRICE_CLOSE;
extern bool      chk_rsi = true;

extern     bool      check_ema_angle = true;
extern     bool      enablealertbuy = true;
extern     bool      enablealertsell = true;
extern     bool      enablealertexit = true;
extern     bool      alertpair = true;
extern     bool      display_fxprime_short = true;
extern     bool      display_fxprime_long = true;
extern     bool      display_fxprime_exit = true;

extern     int       indicator_period = PERIOD_M1;
extern     int       previous_shift = 1;
extern     int       cci_period = 34;
extern     int       long_period = 170;
extern     int       short_rsi = 8;
extern     int       long_rsi = 14;
extern     int       filter_out_cci = 5;
extern     double    filter_out_long = 165;
extern     double    filter_out_short = -165;

extern     double    exit_cci_cross_long = 0;
extern     double    exit_cci_cross_short = 0;
extern     double    long_rsi_cross = 55;
extern     double    short_rsi_cross = 45;

extern     double    small_long_cci_cross = 30;
extern     double    small_short_cci_cross = -30;
extern     double    large_long_cci_cross = 25;
extern     double    large_short_cci_cross = -25;
extern     int       sto_K = 5;
extern     int       sto_D = 3;
extern     int       sto_S = 3;
extern     int       adx_period = 20;
extern     double    adx_level = 15;
extern     bool      chk_adx = false;
extern     int       cci_price = PRICE_TYPICAL;

extern     int       ea_EMAPeriod=34;
extern     double    ea_AngleTreshold=0.3;
extern     int       ea_StartEMAShift=6;
extern     int       ea_EndEMAShift=0;
extern     bool      display_ema_angle = false;

extern     string    alertbuymsg = "#fxprime BUY (Canadian dude says: happy pippin')";
extern     string    alertsellmsg = "#fxprime SELL (Canadian dude says: happy pippin')";
extern     string    alertexitmsg = "#fxprime EXIT";

extern int EMAPeriod=34;
extern double AngleTreshold=0.3;
extern int StartEMAShift=6;
extern int EndEMAShift=0;
extern string Remark4 = "";
extern string Remark5 = "== MTF CCI Settings ==";
extern bool UseMTFCCI = True;
extern int CCIPeriod = 50;
extern int Period1 = 5;
extern int Period2 = 5;
extern int Period3 = 15;
extern int Period4 = 30;
extern string Remark6 = "";
extern string Remark7 = "== Heiken Ashi KusKus Settings ==";
extern bool HeikenAshiExit = True;
extern int TimeFrame = 0;
extern int MaMetod  = 2;
extern int MaPeriod = 6;



//Version 2.01

int OpenBarCount;
int CloseBarCount;

int SignalBarCount;

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                                                   |
   //+------------------------------------------------------------------+

double IndicatorRed = iCustom(NULL, 0, "fxprime_v231", rsi_period, rsi_price, chk_rsi, check_ema_angle, enablealertbuy, enablealertsell, enablealertexit, alertpair, display_fxprime_short, display_fxprime_long, display_fxprime_exit, indicator_period, previous_shift, cci_period, long_period, short_rsi, long_rsi, filter_out_cci, filter_out_long, filter_out_short, exit_cci_cross_long, exit_cci_cross_short, long_rsi_cross, short_rsi_cross, small_long_cci_cross, small_short_cci_cross, large_long_cci_cross, large_short_cci_cross, sto_K, sto_D, sto_S, adx_period, adx_level, chk_adx, cci_price,  ea_EMAPeriod, ea_AngleTreshold, ea_StartEMAShift, ea_EndEMAShift, display_ema_angle, alertbuymsg, alertsellmsg, alertexitmsg, EMAPeriod, AngleTreshold, StartEMAShift, EndEMAShift, 4, Current + 0);
double IndicatorGreen = iCustom(NULL, 0, "fxprime_v231", rsi_period, rsi_price, chk_rsi, check_ema_angle, enablealertbuy, enablealertsell, enablealertexit, alertpair, display_fxprime_short, display_fxprime_long, display_fxprime_exit, indicator_period, previous_shift, cci_period, long_period, short_rsi, long_rsi, filter_out_cci, filter_out_long, filter_out_short, exit_cci_cross_long, exit_cci_cross_short, long_rsi_cross, short_rsi_cross, small_long_cci_cross, small_short_cci_cross, large_long_cci_cross, large_short_cci_cross, sto_K, sto_D, sto_S, adx_period, adx_level, chk_adx, cci_price,  ea_EMAPeriod, ea_AngleTreshold, ea_StartEMAShift, ea_EndEMAShift, display_ema_angle, alertbuymsg, alertsellmsg, alertexitmsg, EMAPeriod, AngleTreshold, StartEMAShift, EndEMAShift, 3, Current + 0);

double IndicatorRed1 = iCustom(NULL, 0, "fxprime_v231", rsi_period, rsi_price, chk_rsi, check_ema_angle, enablealertbuy, enablealertsell, enablealertexit, alertpair, display_fxprime_short, display_fxprime_long, display_fxprime_exit, indicator_period, previous_shift, cci_period, long_period, short_rsi, long_rsi, filter_out_cci, filter_out_long, filter_out_short, exit_cci_cross_long, exit_cci_cross_short, long_rsi_cross, short_rsi_cross, small_long_cci_cross, small_short_cci_cross, large_long_cci_cross, large_short_cci_cross, sto_K, sto_D, sto_S, adx_period, adx_level, chk_adx, cci_price,  ea_EMAPeriod, ea_AngleTreshold, ea_StartEMAShift, ea_EndEMAShift, display_ema_angle, alertbuymsg, alertsellmsg, alertexitmsg, EMAPeriod, AngleTreshold, StartEMAShift, EndEMAShift, 4, Current + 1);
double IndicatorGreen1 = iCustom(NULL, 0, "fxprime_v231", rsi_period, rsi_price, chk_rsi, check_ema_angle, enablealertbuy, enablealertsell, enablealertexit, alertpair, display_fxprime_short, display_fxprime_long, display_fxprime_exit, indicator_period, previous_shift, cci_period, long_period, short_rsi, long_rsi, filter_out_cci, filter_out_long, filter_out_short, exit_cci_cross_long, exit_cci_cross_short, long_rsi_cross, short_rsi_cross, small_long_cci_cross, small_short_cci_cross, large_long_cci_cross, large_short_cci_cross, sto_K, sto_D, sto_S, adx_period, adx_level, chk_adx, cci_price,  ea_EMAPeriod, ea_AngleTreshold, ea_StartEMAShift, ea_EndEMAShift, display_ema_angle, alertbuymsg, alertsellmsg, alertexitmsg, EMAPeriod, AngleTreshold, StartEMAShift, EndEMAShift, 3, Current + 1);

string TradingTime = "Outside Trading Times";
if(UseTimes && TimeHour(TimeCurrent()) >= HourStart && TimeHour(TimeCurrent()) < HourEnd) TradingTime = "Inside Trading Times";
if(!UseTimes) TradingTime = "Not Used";

double CCI11 = iCCI(NULL, Period1, CCIPeriod, PRICE_CLOSE, 0);
double CCI12 = iCCI(NULL, Period1, CCIPeriod, PRICE_CLOSE, 1);

double CCI21 = iCCI(NULL, Period2, CCIPeriod, PRICE_CLOSE, 0);
double CCI22 = iCCI(NULL, Period2, CCIPeriod, PRICE_CLOSE, 1);

double CCI31 = iCCI(NULL, Period3, CCIPeriod, PRICE_CLOSE, 0);
double CCI32 = iCCI(NULL, Period3, CCIPeriod, PRICE_CLOSE, 1);

double CCI41 = iCCI(NULL, Period4, CCIPeriod, PRICE_CLOSE, 0);
double CCI42 = iCCI(NULL, Period4, CCIPeriod, PRICE_CLOSE, 1);

string CCI1Direction = "None";
if(CCI11 > 0) CCI1Direction = "Long";
if(CCI11 < 0) CCI1Direction = "Short";

string CCI2Direction = "None";
if(CCI21 > 0) CCI2Direction = "Long";
if(CCI21 < 0) CCI2Direction = "Short";

string CCI3Direction = "None";
if(CCI31 > 0) CCI3Direction = "Long";
if(CCI31 < 0) CCI3Direction = "Short";

string CCI4Direction = "None";
if(CCI41 > 0) CCI4Direction = "Long";
if(CCI41 < 0) CCI4Direction = "Short";

string FxPrimeIndicator = "None";
if(IndicatorRed != 0.2 && IndicatorGreen == 0.2) FxPrimeIndicator = "Long";
if(IndicatorRed == 0.2 && IndicatorGreen != 0.2) FxPrimeIndicator = "Short";

string FxPrimeIndicator1 = "None";
if(IndicatorRed1 != 0.2 && IndicatorGreen1 == 0.2) FxPrimeIndicator1 = "Long";
if(IndicatorRed1 == 0.2 && IndicatorGreen1 != 0.2) FxPrimeIndicator1 = "Short";

double HAOpen = iCustom(NULL, TimeFrame, "Heiken_Ashi_kuskus", MaMetod, MaPeriod, 2, Current + 0);
double HAClose = iCustom(NULL, TimeFrame, "Heiken_Ashi_kuskus", MaMetod, MaPeriod, 3, Current + 0);

double HAOpen1 = iCustom(NULL, TimeFrame, "Heiken_Ashi_kuskus", MaMetod, MaPeriod, 2, Current + 1);
double HAClose1 = iCustom(NULL, TimeFrame, "Heiken_Ashi_kuskus", MaMetod, MaPeriod, 3, Current + 1);

string HADirection = "None";
if(HAOpen < HAClose) HADirection = "Long";
if(HAOpen > HAClose) HADirection = "Short";


string TradeTrigger = "None";
if(TradingTime != "Outside Trading Times" && CCI1Direction == "Long" && CCI2Direction == "Long" && CCI3Direction == "Long" && CCI4Direction == "Long" && FxPrimeIndicator == "Long" && FxPrimeIndicator1 == "None") TradeTrigger = "Open Long";
if(TradingTime != "Outside Trading Times" && CCI1Direction == "Short" && CCI2Direction == "Short" && CCI3Direction == "Short" && CCI4Direction == "Short" && FxPrimeIndicator == "Short" && FxPrimeIndicator1 == "None") TradeTrigger = "Open Short";

string CloseTrigger = "None";
if(IndicatorRed != 0.2 && IndicatorGreen != 0.2) CloseTrigger = "Close Trade";
if(HADirection == "Long" && HeikenAshiExit) CloseTrigger = "Close Short";
if(HADirection == "Short" && HeikenAshiExit) CloseTrigger = "Close Long";



Comment("TradingTime: ", TradingTime, "\n",
        "FxPrime Indicator Current: ", FxPrimeIndicator, "\n",
        "FxPrime Indicator Previous: ", FxPrimeIndicator1, "\n",
        "CCI 1 Direction: ", CCI1Direction, "\n",
        "CCI 2 Direction: ", CCI2Direction, "\n",
        "CCI 3 Direction: ", CCI3Direction, "\n",
        "CCI 4 Direction: ", CCI4Direction, "\n",
        "Heiken Ashi Direction: ", HADirection, "\n",
        "Bars: ", Bars, "\n",
        "Signal Bar Count: ", SignalBarCount, "\n",
        "Trade Trigger: ", TradeTrigger, "\n",
        "Close Trigger: ", CloseTrigger);

   //+------------------------------------------------------------------+
   //| 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 Trade" || 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;
            }
            //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)                                          |
            //+------------------------------------------------------------------+

if(CloseTrigger == "Close Trade" || 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;
            }
            //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 && SignalBarCount != Bars && ((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) StopLossLevel = Ask - StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else 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");
                SignalBarCount = Bars;
			} else {
				Print("Error opening BUY order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) OpenBarCount = Bars;
         return(0);
      }
   }

   //Sell
   if (Order == SIGNAL_SELL && SignalBarCount != Bars && ((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) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else 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");
                SignalBarCount = Bars;
			} else {
				Print("Error opening SELL order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) OpenBarCount = Bars;
         return(0);
      }
   }

   if (!EachTickMode) CloseBarCount = Bars;

   return(0);
}
}




