//+------------------------------------------------------------------+
//|                                                 DMF AI Robot.mq5 |
//|                 Copyright 2021, ITace Inc. (Marve)Software Corp. |
//|                                            https://www.ITace.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, ITace Inc. (Marve)Software Corp."
#property link      "https://www.ITace.com"
#property version   "1.00"
#property strict

input string TradingBetween = "1:31-23:30";
input double SL = 0.5;
input double TP = 0.5;
input double TND = 50;
input double LotSize = 0.2;
input double SLS = 0.2;
input double SSL = 1;
input double STP = 0.5;
input double CLS = 0.2;
input double CTP = 0.5;
input double CSL = 0.5;
input double ElapsedSECONDS = 1*60;
input double MaxDailyProfit = 200;
input double MaxDailyLoss = -200;

void OnTick()
  {
   bool validTime = isValidTime2Trade(TradingBetween);
   double ask = SymbolInfoDouble(Symbol(), SYMBOL_ASK), bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);
   double iHi = iHigh(Symbol(), PERIOD_M1, 0);
   double iLo = iLow(Symbol(), PERIOD_M1, 0);
   bool SEL_condition = ask < iHi + TND;
   bool BUY_condition = ask < iHi + TND;
   int OrdrTotal = OrdersTotal();
   bool Done4Today = Calc_Today_Closed_Profits(Symbol()) + Calc_OpenOrders_Profits(Symbol()) > MaxDailyProfit;
   bool close4loss = Calc_Today_Closed_Profits(Symbol()) + Calc_OpenOrders_Profits(Symbol()) < MaxDailyLoss;
   if (Done4Today) CloseAllOpenPoss(Symbol());
   if (!Done4Today && OrdrTotal < 1 && validTime)
     {
      if (CheckMoneyForTrade(Symbol(), ORDER_TYPE_SELL, LotSize))
      {
         MqlTradeRequest request;
         MqlTradeResult result;
         request.action = TRADE_ACTION_DEAL;
         request.symbol = Symbol();
         request.volume = LotSize;
         request.price = bid;
         request.sl = bid + SL;
         request.tp = bid - TP;
         request.deviation = 0;
         request.type = ORDER_TYPE_SELL;
         request.magic = 2000;
         if (!OrderSend(request, result))
         {
             Print("OrderSend Error: ", result.retcode);
         }
      }
      if (CheckMoneyForTrade(Symbol(), ORDER_TYPE_BUY, SLS))
      {
         MqlTradeRequest request;
         MqlTradeResult result;
         request.action = TRADE_ACTION_DEAL;
         request.symbol = Symbol();
         request.volume = SLS;
         request.price = ask;
         request.sl = ask - SSL;
         request.tp = ask + STP;
         request.deviation = 0;
         request.type = ORDER_TYPE_BUY;
         request.magic = 2000;
         if (!OrderSend(request, result))
         {
             Print("OrderSend Error: ", result.retcode);
         }
      }
     }
   if (!Done4Today && OrdrTotal == 1 && OrderSelect(0, SELECT_BY_POS))
     {
      if (OrderGetInteger(ORDER_MAGIC) == 2000 && OrderGetString(ORDER_SYMBOL) == Symbol())
        {
         long ElapsSec = MathMin(MinOrdOpElaps(Symbol()), MinOrdClElaps(Symbol()));
         bool LastClosedByLoss = LastOrdClosedByLoss(Symbol());
         if (LastClosedByLoss) Print("LastClosedByLoss!!!");
         if ((OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) && validTime)
           {
            if (ElapsSec > ElapsedSECONDS && CheckMoneyForTrade(Symbol(), ORDER_TYPE_SELL, CLS))
              {
               Print("OrderSend... ", "ElapsSec:", ElapsSec, "  ElapsedSECONDS:", ElapsedSECONDS);
               MqlTradeRequest request;
               MqlTradeResult result;
               request.action = TRADE_ACTION_DEAL;
               request.symbol = Symbol();
               request.volume = CLS;
               request.price = bid;
               request.sl = bid + CSL;
               request.tp = bid - CTP;
               request.deviation = 0;
               request.type = ORDER_TYPE_SELL;
               request.magic = 2000;
               if (!OrderSend(request, result))
               {
                   Print("OrderSend Error: ", result.retcode);
               }
              }
           }
         if ((OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) && validTime)
           {
            if (ElapsSec > ElapsedSECONDS && CheckMoneyForTrade(Symbol(), ORDER_TYPE_BUY, CLS))
              {
               Print("OrderSend... ", "ElapsSec:", ElapsSec, "  ElapsedSECONDS:", ElapsedSECONDS);
               MqlTradeRequest request;
               MqlTradeResult result;
               request.action = TRADE_ACTION_DEAL;
               request.symbol = Symbol();
               request.volume = CLS;
               request.price = ask;
               request.sl = ask - CSL;
               request.tp = ask + CTP;
               request.deviation = 0;
               request.type = ORDER_TYPE_BUY;
               request.magic = 2000;
               if (!OrderSend(request, result))
               {
                   Print("OrderSend Error: ", result.retcode);
               }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
long MinOrdOpElaps(string symb)
  {
   long dif = 1e+16;
   for (int o = 0; o < OrdersTotal(); o++)
     {
      if (OrderSelect(o, SELECT_BY_POS))
        {
         if (OrderGetString(ORDER_SYMBOL) == symb)
           {
            if (TimeCurrent() - OrderGetInteger(ORDER_TIME_SETUP) < dif)
               dif = TimeCurrent() - OrderGetInteger(ORDER_TIME_SETUP);
           }
        }
     }
   return(dif);
  }
//+------------------------------------------------------------------+
long MinOrdClElaps(string symb)
  {
   long dif = 1e+16;
   int o = OrdersHistoryTotal(), a = OrdersHistoryTotal() - 10, b = OrdersHistoryTotal();
   for (o = a; o < b; o++)
     {
      if (OrderSelect(o, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderGetString(ORDER_SYMBOL) == symb)
           {
            if (TimeCurrent() - OrderGetInteger(ORDER_TIME_SETUP) < dif)
               dif = TimeCurrent() - OrderGetInteger(ORDER_TIME_SETUP);
            if (TimeCurrent() - OrderGetInteger(ORDER_TIME_DONE) < dif)
               dif = TimeCurrent() - OrderGetInteger(ORDER_TIME_DONE);
           }
        }
     }
   return(dif);
  }
//+------------------------------------------------------------------+
bool LastOrdClosedByLoss(string symb)
  {
   bool ClosedByLoss = false;
   static datetime lastOrderCloseTime;
   int o = OrdersHistoryTotal(), a = OrdersHistoryTotal() - 10, b = OrdersHistoryTotal();
   for (o = a; o < b; o++)
     {
      if (OrderSelect(o, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderGetString(ORDER_SYMBOL) == symb && OrderGetInteger(ORDER_TIME_DONE) > lastOrderCloseTime)
           {
            lastOrderCloseTime = OrderGetInteger(ORDER_TIME_DONE);
            ClosedByLoss = MathAbs(OrderGetDouble(ORDER_PRICE_CURRENT) - OrderGetDouble(ORDER_SL)) < MathAbs(OrderGetDouble(ORDER_PRICE_CURRENT) - OrderGetDouble(ORDER_TP));
           }
        }
     }
   return(ClosedByLoss);
  }
//+------------------------------------------------------------------+
#define HR2400 86400
#define SECONDS uint
SECONDS time(datetime when = 0) { return SECONDS(when == 0 ? TimeCurrent() : when) % HR2400; }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
datetime date(datetime when = 0) { return datetime((when == 0 ? TimeCurrent() : when) - time(when)); }
bool isValidTime(SECONDS t0, SECONDS t1, datetime when = 0) { SECONDS now = time(when); return t0 < t1 ? t0 <= now && now < t1 : !isValidTime(t1, t0, when); }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void TradingTimeSplit(string str, int& t0, int& t1)
  {
   string res[];
   StringSplit(str, StringGetCharacter("-", 0), res);
   string T0 = res[0], T1 = res[1];
   int H0, M0, H1, M1;
   ArrayFree(res);
   StringSplit(T0, ":", res);
   H0 = (int)StringToInteger(res[0]);
   M0 = (int)StringToInteger(res[1]);
   t0 = H0 * 60 * 60 + M0 * 60;
      ArrayFree(res);
   StringSplit(T1, ":", res);
   H1 = (int)StringToInteger(res[0]);
   M1 = (int)StringToInteger(res[1]);
   t1 = H1 * 60 * 60 + M1 * 60;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool isValidTime2Trade(string str)
  {
   int t0, t1;
   TradingTimeSplit(str, t0, t1);
   return isValidTime(t0, t1);
  }
//+------------------------------------------------------------------+
double Calc_Today_Closed_Profits(string symb)
  {
   double PNL = 0;
   for (int cnt = 0; cnt < OrdersHistoryTotal(); cnt++)
     {
      if (OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderGetString(ORDER_SYMBOL) == symb && OrderGetInteger(ORDER_TYPE) < 2 && iTime(symb, PERIOD_D1, 0) <= OrderGetInteger(ORDER_TIME_DONE))
            PNL += OrderGetDouble(ORDER_PROFIT) + OrderGetDouble(ORDER_SWAP) + OrderGetDouble(ORDER_COMMISSION);
        }
     }
   return (PNL);
  }
//+------------------------------------------------------------------+
double Calc_OpenOrders_Profits(string symb)
  {
   double profit = 0;
   for (int o = 0; o < OrdersTotal(); o++)
     {
      if (OrderSelect(o, SELECT_BY_POS))
        {
         if (OrderGetString(ORDER_SYMBOL) == symb)
           {
            profit += OrderGetDouble(ORDER_PROFIT);
           }
        }
     }
   return (profit);
  }
//+------------------------------------------------------------------+
void CloseAllOpenPoss(string symb)
  {
   int total = OrdersTotal();
   for (int i = total - 1; i >= 0; i--)
     {
      if (OrderSelect(i, SELECT_BY_POS) && OrderGetString(ORDER_SYMBOL) == symb)
        {
         bool result = false;
         MqlTradeRequest request;
         MqlTradeResult trade_result;
         switch (OrderGetInteger(ORDER_TYPE))
           {
            case ORDER_TYPE_BUY:
              request.action = TRADE_ACTION_DEAL;
              request.symbol = symb;
              request.volume = OrderGetDouble(ORDER_VOLUME_CURRENT);
              request.price = SymbolInfoDouble(symb, SYMBOL_BID);
              request.deviation = 5;
              request.type = ORDER_TYPE_SELL;
              if (!OrderSend(request, trade_result))
              {
                  Print("OrderSend Error: ", trade_result.retcode);
              }
              break;
            case ORDER_TYPE_SELL:
              request.action = TRADE_ACTION_DEAL;
              request.symbol = symb;
              request.volume = OrderGetDouble(ORDER_VOLUME_CURRENT);
              request.price = SymbolInfoDouble(symb, SYMBOL_ASK);
              request.deviation = 5;
              request.type = ORDER_TYPE_BUY;
              if (!OrderSend(request, trade_result))
              {
                  Print("OrderSend Error: ", trade_result.retcode);
              }
              break;
           }
         if (!result) Sleep(3000);
        }
     }
  }
//+------------------------------------------------------------------+
bool CheckMoneyForTrade(string symb, int type, double lots)
  {
   double free_margin = AccountInfoDouble(ACCOUNT_FREEMARGIN);
   double margin_required = 0;
   if (type == ORDER_TYPE_BUY)
     margin_required = SymbolInfoDouble(symb, SYMBOL_MARGIN_INITIAL);
   else if (type == ORDER_TYPE_SELL)
     margin_required = SymbolInfoDouble(symb, SYMBOL_MARGIN_INITIAL);
   if (free_margin - margin_required * lots > 0)
      return (true);
   return (false);
  }



erros:
'SELECT_BY_POS' - undeclared identifier	AI+EA_001.mq5	77	56
'OrderSelect' - wrong parameters count	AI+EA_001.mq5	77	41
   built-in: bool OrderSelect(ulong)	AI+EA_001.mq5	77	41
'SELECT_BY_POS' - undeclared identifier	AI+EA_001.mq5	137	26
'OrderSelect' - wrong parameters count	AI+EA_001.mq5	137	11
   built-in: bool OrderSelect(ulong)	AI+EA_001.mq5	137	11
'OrdersHistoryTotal' - undeclared identifier	AI+EA_001.mq5	152	12
')' - expression expected	AI+EA_001.mq5	152	31
'OrdersHistoryTotal' - undeclared identifier	AI+EA_001.mq5	152	38
')' - expression expected	AI+EA_001.mq5	152	57
'OrdersHistoryTotal' - undeclared identifier	AI+EA_001.mq5	152	69
')' - expression expected	AI+EA_001.mq5	152	88
'SELECT_BY_POS' - undeclared identifier	AI+EA_001.mq5	155	26
'MODE_HISTORY' - undeclared identifier	AI+EA_001.mq5	155	41
'OrderSelect' - wrong parameters count	AI+EA_001.mq5	155	11
   built-in: bool OrderSelect(ulong)	AI+EA_001.mq5	155	11
'OrdersHistoryTotal' - undeclared identifier	AI+EA_001.mq5	173	12
')' - expression expected	AI+EA_001.mq5	173	31
'OrdersHistoryTotal' - undeclared identifier	AI+EA_001.mq5	173	38
')' - expression expected	AI+EA_001.mq5	173	57
'OrdersHistoryTotal' - undeclared identifier	AI+EA_001.mq5	173	69
')' - expression expected	AI+EA_001.mq5	173	88
'SELECT_BY_POS' - undeclared identifier	AI+EA_001.mq5	176	26
'MODE_HISTORY' - undeclared identifier	AI+EA_001.mq5	176	41
'OrderSelect' - wrong parameters count	AI+EA_001.mq5	176	11
   built-in: bool OrderSelect(ulong)	AI+EA_001.mq5	176	11
possible loss of data due to type conversion from 'long' to 'datetime'	AI+EA_001.mq5	180	32
implicit conversion from 'string' to 'ushort'	AI+EA_001.mq5	206	21
implicit conversion from 'string' to 'ushort'	AI+EA_001.mq5	211	21
'OrdersHistoryTotal' - undeclared identifier	AI+EA_001.mq5	229	28
')' - expression expected	AI+EA_001.mq5	229	47
'SELECT_BY_POS' - undeclared identifier	AI+EA_001.mq5	231	28
'MODE_HISTORY' - undeclared identifier	AI+EA_001.mq5	231	43
'OrderSelect' - wrong parameters count	AI+EA_001.mq5	231	11
   built-in: bool OrderSelect(ulong)	AI+EA_001.mq5	231	11
'ORDER_PROFIT' - undeclared identifier	AI+EA_001.mq5	234	35
'OrderGetDouble' - no one of the overloads can be applied to the function call	AI+EA_001.mq5	234	20
could be one of 2 function(s)	AI+EA_001.mq5	234	20
   built-in: double OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE)	AI+EA_001.mq5	234	20
   built-in: bool OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE,double&)	AI+EA_001.mq5	234	20
'ORDER_SWAP' - undeclared identifier	AI+EA_001.mq5	234	66
'OrderGetDouble' - no one of the overloads can be applied to the function call	AI+EA_001.mq5	234	51
could be one of 2 function(s)	AI+EA_001.mq5	234	51
   built-in: double OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE)	AI+EA_001.mq5	234	51
   built-in: bool OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE,double&)	AI+EA_001.mq5	234	51
'ORDER_COMMISSION' - undeclared identifier	AI+EA_001.mq5	234	95
'OrderGetDouble' - no one of the overloads can be applied to the function call	AI+EA_001.mq5	234	80
could be one of 2 function(s)	AI+EA_001.mq5	234	80
   built-in: double OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE)	AI+EA_001.mq5	234	80
   built-in: bool OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE,double&)	AI+EA_001.mq5	234	80
'SELECT_BY_POS' - undeclared identifier	AI+EA_001.mq5	245	26
'OrderSelect' - wrong parameters count	AI+EA_001.mq5	245	11
   built-in: bool OrderSelect(ulong)	AI+EA_001.mq5	245	11
'ORDER_PROFIT' - undeclared identifier	AI+EA_001.mq5	249	38
'OrderGetDouble' - no one of the overloads can be applied to the function call	AI+EA_001.mq5	249	23
could be one of 2 function(s)	AI+EA_001.mq5	249	23
   built-in: double OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE)	AI+EA_001.mq5	249	23
   built-in: bool OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE,double&)	AI+EA_001.mq5	249	23
'SELECT_BY_POS' - undeclared identifier	AI+EA_001.mq5	261	26
'OrderSelect' - wrong parameters count	AI+EA_001.mq5	261	11
   built-in: bool OrderSelect(ulong)	AI+EA_001.mq5	261	11
possible loss of data due to type conversion from 'long' to 'int'	AI+EA_001.mq5	266	18