//+------------------------------------------------------------------+
//|                                       Strategy: XxLESSOxX1.1.mq4 |
//|                                 Created BY JeremyXxLESSOxXLester |
//|                                                lesso88@gmail.com |
//+------------------------------------------------------------------+
#property copyright "Created by JeremyXxLESSOxXLester"
#property link      "lesso88@gmail.com"
#property version   "1.1"
#property description ""

#include <stdlib.mqh>
#include <stderror.mqh>

extern string TimeFrameX = "15";
extern double CCI_LOWERVALUE = -200;
extern double CCI_HIGHERVALUE = 200;
extern double STOPLOSS = 0;
extern double TAKEPROFIT = 0;
extern int Position_Percent = 100;
extern double BreakEvenafter = 10;
extern string closetimeframe = "5";
extern int TMAPeriod = 20;
extern double arrowdistance = 6;
extern int PARTIALCLOSEPERCENT = 50;
int LotDigits; //initialized in OnInit
extern int MagicNumber = 684847;
extern int NextOpenTradeAfterBars = 5; //next open trade after time
datetime LastTradeTime = 0;
extern int TOD_From_Hour = 02; //time of the day
extern int TOD_From_Min = 00; //time of the day
extern int TOD_To_Hour = 16; //time of the day
extern int TOD_To_Min = 15; //time of the day
extern double MM_Martingale_Start = 0.1;
extern double MM_Martingale_ProfitFactor = 1.1;
extern double MM_Martingale_LossFactor = 0.8;
extern bool MM_Martingale_RestartProfit = false;
extern bool MM_Martingale_RestartLoss = false;
extern int MM_Martingale_RestartLosses = 1000;
extern int MaxSlippage = 3; //adjusted in OnInit
extern bool TradeMonday = true;
extern bool TradeTuesday = true;
extern bool TradeWednesday = true;
extern bool TradeThursday = true;
extern bool TradeFriday = true;
extern bool TradeSaturday = false;
extern bool TradeSunday = false;
extern bool Send_Email = true;
extern bool Audible_Alerts = true;
extern int MaxOpenTrades = 10;
int MaxLongTrades = 1000;
int MaxShortTrades = 1000;
int MaxPendingOrders = 1000;
bool Hedging = false;
int OrderRetry = 5; //# of retries if sending order returns error
int OrderWait = 5; //# of seconds to wait if sending order returns error
double myPoint; //initialized in OnInit

bool inTimeInterval(datetime t, int TOD_From_Hour, int TOD_From_Min, int TOD_To_Hour, int TOD_To_Min)
  {
   string TOD = TimeToString(t, TIME_MINUTES);
   string TOD_From = StringFormat("%02d", TOD_From_Hour)+":"+StringFormat("%02d", TOD_From_Min);
   string TOD_To = StringFormat("%02d", TOD_To_Hour)+":"+StringFormat("%02d", TOD_To_Min);
   return((StringCompare(TOD, TOD_From) >= 0 && StringCompare(TOD, TOD_To) <= 0)
     || (StringCompare(TOD_From, TOD_To) > 0
       && ((StringCompare(TOD, TOD_From) >= 0 && StringCompare(TOD, "23:59") <= 0)
         || (StringCompare(TOD, "00:00") >= 0 && StringCompare(TOD, TOD_To) <= 0))));
  }

bool SelectLastHistoryTrade()
  {
   int lastOrder = -1;
   int total = OrdersHistoryTotal();
   for(int i = total-1; i >= 0; i--)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
      if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
        {
         lastOrder = i;
         break;
        }
     } 
   return(lastOrder >= 0);
  }

double BOProfit(int ticket) //binary options profit
  {
   int total = OrdersHistoryTotal();
   for(int i = total-1; i >= 0; i--)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
      if(StringSubstr(OrderComment(), 0, 2) == "BO" && StringFind(OrderComment(), "#"+ticket+" ") >= 0)
         return OrderProfit();
     }
   return 0;
  }

bool ConsecutiveLosses(int n)
  {
   int count = 0;
   int total = OrdersHistoryTotal();
   for(int i = total-1; i >= 0; i--)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
      if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
        {
         double orderprofit = OrderProfit();
         double boprofit = BOProfit(OrderTicket());
         if(orderprofit + boprofit >= 0)
            break;
         count++;
        }
     }
   return(count >= n);
  }

double MM_Size() //martingale / anti-martingale
  {
   double lots = MM_Martingale_Start;
   double MaxLot = MarketInfo(Symbol(), MODE_MAXLOT);
   double MinLot = MarketInfo(Symbol(), MODE_MINLOT);
   if(SelectLastHistoryTrade())
     {
      double orderprofit = OrderProfit();
      double orderlots = OrderLots();
      double boprofit = BOProfit(OrderTicket());
      if(orderprofit + boprofit > 0 && !MM_Martingale_RestartProfit)
         lots = orderlots * MM_Martingale_ProfitFactor;
      else if(orderprofit + boprofit < 0 && !MM_Martingale_RestartLoss)
         lots = orderlots * MM_Martingale_LossFactor;
     }
   if(ConsecutiveLosses(MM_Martingale_RestartLosses))
      lots = MM_Martingale_Start;
   if(lots > MaxLot) lots = MaxLot;
   if(lots < MinLot) lots = MinLot;
   return(lots);
  }

bool TradeDayOfWeek()
  {
   int day = DayOfWeek();
   return((TradeMonday && day == 1)
   || (TradeTuesday && day == 2)
   || (TradeWednesday && day == 3)
   || (TradeThursday && day == 4)
   || (TradeFriday && day == 5)
   || (TradeSaturday && day == 6)
   || (TradeSunday && day == 0));
  }

void myAlert(string type, string message)
  {
   if(type == "print")
      Print(message);
   else if(type == "error")
     {
      Print(type+" | XxLESSOxX1.1 @ "+Symbol()+","+Period()+" | "+message);
     }
   else if(type == "order")
     {
      if(Audible_Alerts) Alert(type+" | XxLESSOxX1.1 @ "+Symbol()+","+Period()+" | "+message);
      if(Send_Email) SendMail("XxLESSOxX1.1", type+" | XxLESSOxX1.1 @ "+Symbol()+","+Period()+" | "+message);
     }
   else if(type == "modify")
     {
     }
  }

int TradesCount(int type) //returns # of open trades for order type, current symbol and magic number
  {
   int result = 0;
   int total = OrdersTotal();
   for(int i = 0; i < total; i++)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) continue;
      if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() || OrderType() != type) continue;
      result++;
     }
   return(result);
  }

int myOrderSend(int type, double price, double volume, string ordername) //send order, return ticket ("price" is irrelevant for market orders)
  {
   if(!IsTradeAllowed()) return(-1);
   int ticket = -1;
   int retries = 0;
   int err;
   int long_trades = TradesCount(OP_BUY);
   int short_trades = TradesCount(OP_SELL);
   int long_pending = TradesCount(OP_BUYLIMIT) + TradesCount(OP_BUYSTOP);
   int short_pending = TradesCount(OP_SELLLIMIT) + TradesCount(OP_SELLSTOP);
   string ordername_ = ordername;
   if(ordername != "")
      ordername_ = "("+ordername+")";
   //test Hedging
   if(!Hedging && ((type % 2 == 0 && short_trades + short_pending > 0) || (type % 2 == 1 && long_trades + long_pending > 0)))
     {
      myAlert("print", "Order"+ordername_+" not sent, hedging not allowed");
      return(-1);
     }
   //test maximum trades
   if((type % 2 == 0 && long_trades >= MaxLongTrades)
   || (type % 2 == 1 && short_trades >= MaxShortTrades)
   || (long_trades + short_trades >= MaxOpenTrades)
   || (type > 1 && long_pending + short_pending >= MaxPendingOrders))
     {
      myAlert("print", "Order"+ordername_+" not sent, maximum reached");
      return(-1);
     }
   //prepare to send order
   while(IsTradeContextBusy()) Sleep(100);
   RefreshRates();
   if(type == OP_BUY)
      price = Ask;
   else if(type == OP_SELL)
      price = Bid;
   else if(price < 0) //invalid price for pending order
     {
      myAlert("order", "Order"+ordername_+" not sent, invalid price for pending order");
	  return(-1);
     }
   int clr = (type % 2 == 1) ? clrRed : clrBlue;
   while(ticket < 0 && retries < OrderRetry+1)
     {
      ticket = OrderSend(Symbol(), type, NormalizeDouble(volume, LotDigits), NormalizeDouble(price, Digits()), MaxSlippage, 0, 0, ordername, MagicNumber, 0, clr);
      if(ticket < 0)
        {
         err = GetLastError();
         myAlert("print", "OrderSend"+ordername_+" error #"+err+" "+ErrorDescription(err));
         Sleep(OrderWait*1000);
        }
      retries++;
     }
   if(ticket < 0)
     {
      myAlert("error", "OrderSend"+ordername_+" failed "+(OrderRetry+1)+" times; error #"+err+" "+ErrorDescription(err));
      return(-1);
     }
   string typestr[6] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell Stop"};
   myAlert("order", "Order sent"+ordername_+": "+typestr[type]+" "+Symbol()+" Magic #"+MagicNumber);
   return(ticket);
  }

int myOrderModify(int ticket, double SL, double TP) //modify SL and TP (absolute price), zero targets do not modify
  {
   if(!IsTradeAllowed()) return(-1);
   bool success = false;
   int retries = 0;
   int err;
   SL = NormalizeDouble(SL, Digits());
   TP = NormalizeDouble(TP, Digits());
   if(SL < 0) SL = 0;
   if(TP < 0) TP = 0;
   //prepare to select order
   while(IsTradeContextBusy()) Sleep(100);
   if(!OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
     {
      err = GetLastError();
      myAlert("error", "OrderSelect failed; error #"+err+" "+ErrorDescription(err));
      return(-1);
     }
   //prepare to modify order
   while(IsTradeContextBusy()) Sleep(100);
   RefreshRates();
   if(CompareDoubles(SL, 0)) SL = OrderStopLoss(); //not to modify
   if(CompareDoubles(TP, 0)) TP = OrderTakeProfit(); //not to modify
   if(CompareDoubles(SL, OrderStopLoss()) && CompareDoubles(TP, OrderTakeProfit())) return(0); //nothing to do
   while(!success && retries < OrderRetry+1)
     {
      success = OrderModify(ticket, NormalizeDouble(OrderOpenPrice(), Digits()), NormalizeDouble(SL, Digits()), NormalizeDouble(TP, Digits()), OrderExpiration(), CLR_NONE);
      if(!success)
        {
         err = GetLastError();
         myAlert("print", "OrderModify error #"+err+" "+ErrorDescription(err));
         Sleep(OrderWait*1000);
        }
      retries++;
     }
   if(!success)
     {
      myAlert("error", "OrderModify failed "+(OrderRetry+1)+" times; error #"+err+" "+ErrorDescription(err));
      return(-1);
     }
   string alertstr = "Order modified: ticket="+ticket;
   if(!CompareDoubles(SL, 0)) alertstr = alertstr+" SL="+SL;
   if(!CompareDoubles(TP, 0)) alertstr = alertstr+" TP="+TP;
   myAlert("modify", alertstr);
   return(0);
  }

int myOrderModifyRel(int ticket, double SL, double TP) //modify SL and TP (relative to open price), zero targets do not modify
  {
   if(!IsTradeAllowed()) return(-1);
   bool success = false;
   int retries = 0;
   int err;
   SL = NormalizeDouble(SL, Digits());
   TP = NormalizeDouble(TP, Digits());
   if(SL < 0) SL = 0;
   if(TP < 0) TP = 0;
   //prepare to select order
   while(IsTradeContextBusy()) Sleep(100);
   if(!OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
     {
      err = GetLastError();
      myAlert("error", "OrderSelect failed; error #"+err+" "+ErrorDescription(err));
      return(-1);
     }
   //prepare to modify order
   while(IsTradeContextBusy()) Sleep(100);
   RefreshRates();
   //convert relative to absolute
   if(OrderType() % 2 == 0) //buy
     {
      if(NormalizeDouble(SL, Digits()) != 0)
         SL = OrderOpenPrice() - SL;
      if(NormalizeDouble(TP, Digits()) != 0)
         TP = OrderOpenPrice() + TP;
     }
   else //sell
     {
      if(NormalizeDouble(SL, Digits()) != 0)
         SL = OrderOpenPrice() + SL;
      if(NormalizeDouble(TP, Digits()) != 0)
         TP = OrderOpenPrice() - TP;
     }
   if(CompareDoubles(SL, 0)) SL = OrderStopLoss(); //not to modify
   if(CompareDoubles(TP, 0)) TP = OrderTakeProfit(); //not to modify
   if(CompareDoubles(SL, OrderStopLoss()) && CompareDoubles(TP, OrderTakeProfit())) return(0); //nothing to do
   while(!success && retries < OrderRetry+1)
     {
      success = OrderModify(ticket, NormalizeDouble(OrderOpenPrice(), Digits()), NormalizeDouble(SL, Digits()), NormalizeDouble(TP, Digits()), OrderExpiration(), CLR_NONE);
      if(!success)
        {
         err = GetLastError();
         myAlert("print", "OrderModify error #"+err+" "+ErrorDescription(err));
         Sleep(OrderWait*1000);
        }
      retries++;
     }
   if(!success)
     {
      myAlert("error", "OrderModify failed "+(OrderRetry+1)+" times; error #"+err+" "+ErrorDescription(err));
      return(-1);
     }
   string alertstr = "Order modified: ticket="+ticket;
   if(!CompareDoubles(SL, 0)) alertstr = alertstr+" SL="+SL;
   if(!CompareDoubles(TP, 0)) alertstr = alertstr+" TP="+TP;
   myAlert("modify", alertstr);
   return(0);
  }

void myOrderClose(int type, int volumepercent, string ordername) //close open orders for current symbol, magic number and "type" (OP_BUY or OP_SELL)
  {
   if(!IsTradeAllowed()) return;
   if (type > 1)
     {
      myAlert("error", "Invalid type in myOrderClose");
      return;
     }
   bool success = false;
   int err;
   string ordername_ = ordername;
   if(ordername != "")
      ordername_ = "("+ordername+")";
   int total = OrdersTotal();
   for(int i = total-1; i >= 0; i--)
     {
      while(IsTradeContextBusy()) Sleep(100);
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() || OrderType() != type) continue;
      while(IsTradeContextBusy()) Sleep(100);
      RefreshRates();
      double price = (type == OP_SELL) ? Ask : Bid;
      double volume = NormalizeDouble(OrderLots()*volumepercent * 1.0 / 100, LotDigits);
      if (NormalizeDouble(volume, LotDigits) == 0) continue;
      success = OrderClose(OrderTicket(), volume, NormalizeDouble(price, Digits()), MaxSlippage, clrWhite);
      if(!success)
        {
         err = GetLastError();
         myAlert("error", "OrderClose"+ordername_+" failed; error #"+err+" "+ErrorDescription(err));
        }
     }
   string typestr[6] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell Stop"};
   if(success) myAlert("order", "Orders closed"+ordername_+": "+typestr[type]+" "+Symbol()+" Magic #"+MagicNumber);
  }

void TrailingStopBE(int type, double profit) //set Stop Loss to open price if in profit
  {
   int total = OrdersTotal();
   profit = NormalizeDouble(profit, Digits());
   for(int i = total-1; i >= 0; i--)
     {
      while(IsTradeContextBusy()) Sleep(100);
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() || OrderType() != type) continue;
      RefreshRates();
      if((type == OP_BUY && Ask > OrderOpenPrice() + profit)
      || (type == OP_SELL && Bid < OrderOpenPrice() - profit))
         myOrderModify(OrderTicket(), OrderOpenPrice(), 0);
     }
  }

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {   
   //initialize myPoint
   myPoint = Point();
   if(Digits() == 5 || Digits() == 3)
     {
      myPoint *= 10;
      MaxSlippage *= 10;
     }
   //initialize LotDigits
   double LotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
   if(LotStep >= 1) LotDigits = 0;
   else if(LotStep >= 0.1) LotDigits = 1;
   else if(LotStep >= 0.01) LotDigits = 2;
   else LotDigits = 3;
   LastTradeTime = 0;
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   int ticket = -1;
   double price;   
   double SL;
   double TP;
   
   TrailingStopBE(OP_BUY, BreakEvenafter * myPoint); //Trailing Stop = go break even
   TrailingStopBE(OP_SELL, BreakEvenafter * myPoint); //Trailing Stop = go break even
   
   //Close Long Positions
   if(iCustom(NULL, PERIOD_CURRENT, "XxLESSOxXarrow1.2", TMAPeriod, TimeFrameX, arrowdistance, CCI_LOWERVALUE, CCI_HIGHERVALUE, 20, 1, 0) != 0 && iCustom(NULL, PERIOD_CURRENT, "XxLESSOxXarrow1.2", TMAPeriod, TimeFrameX, arrowdistance, CCI_LOWERVALUE, CCI_HIGHERVALUE, 20, 1, 0) != EMPTY_VALUE //XxLESSOxXarrow1.2 is not equal to fixed value
   )
     {   
      if(IsTradeAllowed())
         myOrderClose(OP_BUY, 100, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Close Long Positions
   RefreshRates();
   if(Ask >= iCustom(NULL, PERIOD_CURRENT, "FastTMALine with slope alert", closetimeframe, 20, PRICE_CLOSE, 2.0, 100, 0.5, false, false, false, false, false, false, false, 5000, 0, 0) //Price >= FastTMALine with slope alert
   )
     {   
      if(IsTradeAllowed())
         myOrderClose(OP_BUY, PARTIALCLOSEPERCENT, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Close Short Positions
   if(iCustom(NULL, PERIOD_CURRENT, "XxLESSOxXarrow1.2", TMAPeriod, TimeFrameX, arrowdistance, CCI_LOWERVALUE, CCI_HIGHERVALUE, 20, 0, 0) != 0 && iCustom(NULL, PERIOD_CURRENT, "XxLESSOxXarrow1.2", TMAPeriod, TimeFrameX, arrowdistance, CCI_LOWERVALUE, CCI_HIGHERVALUE, 20, 0, 0) != EMPTY_VALUE //XxLESSOxXarrow1.2 is not equal to fixed value
   )
     {   
      if(IsTradeAllowed())
         myOrderClose(OP_SELL, 100, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Close Short Positions
   RefreshRates();
   if(Bid <= iCustom(NULL, PERIOD_CURRENT, "FastTMALine with slope alert", closetimeframe, 20, PRICE_CLOSE, 2.0, 100, 0.5, false, false, false, false, false, false, false, 5000, 0, 0) //Price <= FastTMALine with slope alert
   )
     {   
      if(IsTradeAllowed())
         myOrderClose(OP_SELL, PARTIALCLOSEPERCENT, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Open Buy Order
   if(iCustom(NULL, PERIOD_CURRENT, "XxLESSOxXarrow1.2", TMAPeriod, TimeFrameX, arrowdistance, CCI_LOWERVALUE, CCI_HIGHERVALUE, 20, 0, 0) != 0 && iCustom(NULL, PERIOD_CURRENT, "XxLESSOxXarrow1.2", TMAPeriod, TimeFrameX, arrowdistance, CCI_LOWERVALUE, CCI_HIGHERVALUE, 20, 0, 0) != EMPTY_VALUE //XxLESSOxXarrow1.2 is not equal to fixed value
   )
     {
      RefreshRates();
      price = Ask;
      SL = STOPLOSS * myPoint; //Stop Loss = value in points (relative to price)
      TP = TAKEPROFIT * myPoint; //Take Profit = value in points (relative to price)
      if(TimeCurrent() - LastTradeTime < NextOpenTradeAfterBars * PeriodSeconds()) return; //next open trade after time
      if(!inTimeInterval(TimeCurrent(), TOD_From_Hour, TOD_From_Min, TOD_To_Hour, TOD_To_Min)) return; //open trades only at specific times of the day
      if(!TradeDayOfWeek()) return; //open trades only on specific days of the week   
      if(IsTradeAllowed())
        {
         ticket = myOrderSend(OP_BUY, price, MM_Size() * Position_Percent * 1.0 / 100, "");
         if(ticket <= 0) return;
        }
      else //not autotrading => only send alert
         myAlert("order", "");
      LastTradeTime = TimeCurrent();
      myOrderModifyRel(ticket, SL, 0);
      myOrderModifyRel(ticket, 0, TP);
     }
   
   //Open Sell Order
   if(iCustom(NULL, PERIOD_CURRENT, "XxLESSOxXarrow1.2", TMAPeriod, TimeFrameX, arrowdistance, CCI_LOWERVALUE, CCI_HIGHERVALUE, 20, 1, 0) != 0 && iCustom(NULL, PERIOD_CURRENT, "XxLESSOxXarrow1.2", TMAPeriod, TimeFrameX, arrowdistance, CCI_LOWERVALUE, CCI_HIGHERVALUE, 20, 1, 0) != EMPTY_VALUE //XxLESSOxXarrow1.2 is not equal to fixed value
   )
     {
      RefreshRates();
      price = Bid;
      SL = STOPLOSS * myPoint; //Stop Loss = value in points (relative to price)
      TP = TAKEPROFIT * myPoint; //Take Profit = value in points (relative to price)
      if(TimeCurrent() - LastTradeTime < NextOpenTradeAfterBars * PeriodSeconds()) return; //next open trade after time
      if(!inTimeInterval(TimeCurrent(), TOD_From_Hour, TOD_From_Min, TOD_To_Hour, TOD_To_Min)) return; //open trades only at specific times of the day
      if(!TradeDayOfWeek()) return; //open trades only on specific days of the week   
      if(IsTradeAllowed())
        {
         ticket = myOrderSend(OP_SELL, price, MM_Size() * Position_Percent * 1.0 / 100, "");
         if(ticket <= 0) return;
        }
      else //not autotrading => only send alert
         myAlert("order", "");
      LastTradeTime = TimeCurrent();
      myOrderModifyRel(ticket, SL, 0);
      myOrderModifyRel(ticket, 0, TP);
     }
  }
//+------------------------------------------------------------------+