//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2020, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2022, A3migo Project."
#property link        "https://no-website.yet"
#property version     "443.776"
#property description "RSI D "
#property description "modified from 24.0321"
//#include "PositionInfo.mqh"   CPositionInfo     position;
#include "TradeAlt.mqh"//       CTradeAlt         trade;
//#include "AccountInfo.mqh"    CAccountInfo      info;
//#include "SymbolInfo.mqh"     CSymbolInfo       sym;
#resource "IND5.rRSI(oma)(ds)22.1212.ex5"
#resource "IND5.rRsi2Macd25.1111.ex5"
//#resource "IND5.rJmacd23.0416.ex5"
#resource "Macd_Tema.ex5"
//#resource "IND5.rmacd23.0716.ex5"
//#include "MT4Orders.mqh"
#include "INC5.rMt4Orders25.0910.mqh"
//#include <MT4Orders.mqh> // https://www.mql5.com/en/code/16006
//#define Amount (int) HistoryOrdersTotal()
#define Reason (ENUM_DEAL_REASON) DEAL_REASON_SL
#define Reasonb (ENUM_DEAL_REASON) DEAL_REASON_TP
#define buy ORDER_TYPE_BUY
#define sel ORDER_TYPE_SELL
#define none -1
//#define sym (string)Symbol()
#define dig (uchar)Digits()
#define total (ushort)PositionsTotal()
static string sym0 = Symbol();
static string sym = sym0;
#define ask (double)SymbolInfoDouble(Symbol(),SYMBOL_ASK)
#define bid (double)SymbolInfoDouble(Symbol(),SYMBOL_BID)
#define bal (double)AccountInfoDouble(ACCOUNT_BALANCE)
#define equ (double)AccountInfoDouble(ACCOUNT_EQUITY)
#define apft (double)AccountInfoDouble(ACCOUNT_PROFIT)
#define pnt (double)SymbolInfoDouble(Symbol(),SYMBOL_POINT)
#define mlvl (double)AccountInfoDouble(ACCOUNT_MARGIN_LEVEL)
#define fmlvl (double)AccountInfoDouble(ACCOUNT_MARGIN_FREE)
input double   iEquityStop    = 18.00;    // Profit Target (Percent of Start Lot)
//input double
input double   iStartLots     = 0.25;   // Trade Lot
input double   i2ndLot     = 0.10;   // Trade Lot
input double   iStart3Lots     = 0.35;   // Trade Lot
input int          iPointOrderStep     = 125;      // Group Step (in pnts)
input bool         iVerbose            = false;     // Show more Trade details
//input double       iCloseTarget        = 40.05;     // Next Closing target
//input double       iProfitInc          = 5;         // Inc Equity Amount
//input double       iDrawdown           = 5;         // Comfortable Drawdown
input int      iMagicNumber   = 227;    // Magic Number
input int          iSlippage           = 1;       // Slippage (in pips)
input int          Spread              = 7;       // Spread (in pips)

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
class AutoA3m
  {
private:
public:

   //   bool              openNewTrade(bool buySignal, bool selSignal); //, int totalBuy, int totalSel);//, int buyCount, int sellCount)
   //   bool              openNewTrade(int typ, int buyCount, int sellCount);
   bool              IsInDDmode(double worsProfit);
   //void              CloseTrades(int no2close = 999, bool worsParty = false);
   void              CloseTrades(int dcount, int no2close = 999, bool worsParty = false);
   bool              openNewTrade(bool buySignal, bool selSignal, int buyCount, int sellCount);
   bool              buffers();
   bool              trendy();
   bool              checkRsi();
   void              accounts();
   bool              IsFridayTrue();
   //   bool              IsHourTrue();
   bool              osd();
   bool              release();
   bool              checkGV();
   double            GetLastHistoryPositions(bool firstTime = false);
   double            CalculateHedgeAveragePrice();
   //   void              findLasts();//ENUM_TIMEFRAMES Higher1TF         = PERIOD_M6; // Filter - Higher TF
   //   bool              doalerts(bool docloseAll, int numClose); */
   ENUM_TIMEFRAMES   Higher2TF; //         = PERIOD_M20; // Filter - Higher TF
   ENUM_TIMEFRAMES   Higher3TF; //         = PERIOD_M30; // Filter - Higher TF
   ENUM_TIMEFRAMES   Higher4TF; //         = PERIOD_H1; // Filter - Higher TF
   ENUM_TIMEFRAMES   macdTF2; //         = PERIOD_M5; // Filter - Higher TF
   ENUM_TIMEFRAMES   macdTF; //         = PERIOD_M12; // Filter - Higher TF
   //const ENUM_TIMEFRAMES macdTF4         = PERIOD_H3; // Filter - Higher TF
   //const ENUM_TIMEFRAMES macdTF5         = PERIOD_H8; // Filter - Higher TF
   double            tsla, tslb, mlvl0; //, qq0e, qq1e, qq2e; // MinLoss,
   ulong             worsTics[];
   //const string sym = Symbol();
   int               rsiMacd_handle, tapMa_handle, TF1_RSO_handle, TF1_macd_handle, TF2_RSO_handle, TF2_macd_handle;
   double            rsimacd40[], tap[], rsimacd41[], TF1_RSO[], macd20[], macd21[], TF2_RSO[], macd30[], macd31[];
   datetime          Time[], hi1Time[], hi2Time[], hi3Time[], hi4Time[]; //, ot;
   bool              testing, osd_to_be_called, marg, check;
   datetime          historyBalTime, dt[1], currTime, new3htfBuy, new3htfSel;
   double ask0, bid0, pnt0, bal0, equ0, apft0, trend[2], Last[2], LastLot[2], tsl[2], pft, sw, ltv, totalLosses, net, minLoss, maxLoss
   , lever, pftTotal, pft2Total, iMinimalProfit, pntStep, xcm // losr_buy, losr_sel, pft_buy, pft_sel,
   , trailPft, dista, maxLot  //eqplus, , temaDistance=90*Point()
   , tsltotal, buyMng, selMng, buyMxg, selMxg, prevClose; //hi4, lo4, hi5, lo5, //, start = fmax(iStartLots,iStartLots*1000/1618000*equ0/1000);
   int               totalbuy, totalsel, ccount, LastError, ps3, ps1, b, s, b4, s4, bs, b2, s2; //, openTradeType;
  };
CPositionInfo     position;
CTradeAlt         trade;
AutoA3m           auto;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//double  GetLastHistoryPositions(bool firstTime = false)
double AutoA3m::GetLastHistoryPositions(bool firstTime = false)
  {
//   if(testing)
//      return 0.000;
   static int ordtotal = OrdersHistoryTotal(), bcount;
   prevClose = GlobalVariableGet("prevClose");
   tsltotal = 0;
   bcount = 0;
   const double comish = iStartLots * 6; // * ccount;
   for(int i = ordtotal - 1; (i >= 0); i--)
      if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) > 0) // && (OrderType()==OP_BUY || OrderType()==OP_SELL))
        {
         if(OrderCloseTime() > prevClose) //  || (firstTime && (OrderCloseReason() == Reason || OrderCloseReason() == Reasonb)))
           {
            if(OrderProfit() <= comish)
               continue;
            ++bcount;
            tsltotal += (OrderProfit() + OrderSwap()); //+OrderCommission());
           }
         else
            break;
        }
//   if(__prevClose != prevClose)
//      GlobalVariableSet("prevClose",__prevClose);
   return (tsltotal - (1.62 * iMinimalProfit * bcount)); // - (comish*ccount));
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
   auto.testing = MQLInfoInteger(MQL_TESTER);
   auto.historyBalTime = 0;
   auto.prevClose = 0;
//    buy = 0;
//    sel = 1;
//   start = iStartLots * 1620;
   auto.Higher2TF         = PERIOD_M20; // Filter - Higher TF
   auto.Higher3TF         = PERIOD_M30; // Filter - Higher TF
   auto.Higher4TF         = PERIOD_H1; // Filter - Higher TF
   auto.macdTF2         = PERIOD_M5; // Filter - Higher TF
   auto.macdTF         = PERIOD_M12; // Filter - Higher TF
   auto.rsiMacd_handle =  auto.TF1_RSO_handle =  auto.TF1_macd_handle =  auto.TF2_RSO_handle =  auto.TF2_macd_handle = INVALID_HANDLE;
//    yesHour = false;
//   testing = MQLInfoInteger(MQL_TESTER);
   auto.osd_to_be_called = true;
   auto.marg = false;
   auto.check = false; // ddManage = false,
   auto.minLoss = iStartLots * 1000 * 0.35;
   auto.maxLoss = -iStartLots * 1000 * 8.24;
   auto.lever = (double)AccountInfoInteger(ACCOUNT_LEVERAGE);
   auto.iMinimalProfit = 6 * iStartLots * 1.618033;
   auto.pntStep = (iPointOrderStep * pnt);
   auto.xcm = -iStartLots * 27;// losr_buy, losr_sel, pft_buy, pft_sel,
   auto.trailPft =  auto.iMinimalProfit;
//   eqplus = iEquityStop * iStartLots * 10;
   auto.dista = NormalizeDouble(2.618034 / pow(10, _Digits - 1), _Digits + 2);
   auto.maxLot = SymbolInfoDouble(NULL, SYMBOL_VOLUME_MAX); //, temaDistance=90*Point()
   auto.ccount = 3;
   auto.LastError = 0;
   auto.ps3 = PeriodSeconds(auto.Higher3TF);
   auto.ps1 = PeriodSeconds(auto.macdTF);
//   openTradeType = none;
   auto.accounts();
   auto.ps1 = PeriodSeconds(auto.macdTF);
   auto.ps3 = PeriodSeconds(auto.Higher3TF);
//   temaDistance = 90*Point();
   Comment("");
   auto.maxLot = SymbolInfoDouble(NULL, SYMBOL_VOLUME_MAX);
   auto.dista = NormalizeDouble(2.618034 / pow(10, _Digits - 1), _Digits + 2);
   auto.lever = (int)AccountInfoInteger(ACCOUNT_LEVERAGE); // info.Leverage()*1.618033;
   TesterHideIndicators(true);
//   iPointOrderStep     = 75;
   auto.pntStep = (iPointOrderStep * pnt);
   if(auto.testing != false || !iVerbose)
      trade.LogLevel(LOG_LEVEL_NO);
   else
      trade.LogLevel(LOG_LEVEL_ALL);
   trade.SetExpertMagicNumber(iMagicNumber);
   trade.SetDeviationInPoints(iSlippage);
   trade.SetMarginMode();
   trade.SetTypeFillingBySymbol(Symbol());
   if(!auto.testing)
      trade.SetAsyncMode(true);
   ArraySetAsSeries(auto.tap, true);
   ArraySetAsSeries(auto.TF1_RSO, true);
   ArraySetAsSeries(auto.TF2_RSO, true);
   ArraySetAsSeries(auto.Time, true);
   ArraySetAsSeries(auto.hi1Time, true);
   ArraySetAsSeries(auto.hi2Time, true);
   ArraySetAsSeries(auto.hi3Time, true);
   ArraySetAsSeries(auto.hi4Time, true);
   ArraySetAsSeries(auto.macd20, true);
   ArraySetAsSeries(auto.macd21, true);
   ArraySetAsSeries(auto.macd30, true);
   ArraySetAsSeries(auto.macd31, true);
   ArraySetAsSeries(auto.rsimacd40, true);
   ArraySetAsSeries(auto.rsimacd41, true);
   ArrayResize(auto.tap, 5, 5);
   ArrayResize(auto.TF1_RSO, 5, 5);
   ArrayResize(auto.TF2_RSO, 5, 5);
   ArrayResize(auto.Time, 5, 5);
   ArrayResize(auto.hi1Time, 5, 5);
   ArrayResize(auto.hi2Time, 5, 5);
   ArrayResize(auto.hi3Time, 5, 5);
   ArrayResize(auto.hi4Time, 5, 5);
   ArrayResize(auto.macd20, 5, 5);
   ArrayResize(auto.macd21, 5, 5);
   ArrayResize(auto.macd30, 5, 5);
   ArrayResize(auto.macd31, 5, 5);
   ArrayResize(auto.rsimacd40, 5, 5);
   ArrayResize(auto.rsimacd41, 5, 5);
   auto.tapMa_handle = iTEMA(NULL,  auto.macdTF, 9, 0, PRICE_MEDIAN);
   if(auto.tapMa_handle < 0)
     {
      Print("The creation of tapMa has failed: tapMa_handle=", INVALID_HANDLE);
      Print("Runtime error = ", GetLastError());
      return(INIT_FAILED);
     }
   auto.rsiMacd_handle = iCustom(NULL,  auto.macdTF2, "::IND5.rRsi2Macd25.1111.ex5", 12, 34, 9, PRICE_CLOSE, false, false, false);
   if(auto.rsiMacd_handle < 0)
     {
      Print("The creation of rsiMacd has failed: rsiMacd_handle=", INVALID_HANDLE);
      Print("Runtime error = ", GetLastError());
      return(INIT_FAILED);
     }
   auto.TF1_RSO_handle = iCustom(NULL,  auto.macdTF, "::IND5.rRSI(oma)(ds)22.1212.ex5", 5, 8, MODE_EMA, PRICE_CLOSE);
   if(auto.TF1_RSO_handle < 0)
     {
      Print("The creation of TF1_RSO has failed: TF1_RSO_handle=", INVALID_HANDLE);
      Print("Runtime error = ", GetLastError());
      return(INIT_FAILED);
     }
   auto.TF1_macd_handle = iCustom(NULL,  auto.macdTF, "::Macd_Tema.ex5", 12, 26, 9, PRICE_WEIGHTED, false, false, false);
   if(auto.TF1_macd_handle < 0)
     {
      Print("The creation of Hi4TF_Macd has failed: Hi4TF_handle=", INVALID_HANDLE);
      Print("Runtime error = ", GetLastError());
      return(INIT_FAILED);
     }
   auto.TF2_RSO_handle = iCustom(NULL,  auto.macdTF2, "::IND5.rRSI(oma)(ds)22.1212.ex5", 5, 8, MODE_EMA, PRICE_CLOSE);
   if(auto.TF2_RSO_handle < 0)
     {
      Print("The creation of TF1_RSO has failed: TF1_RSO_handle=", INVALID_HANDLE);
      Print("Runtime error = ", GetLastError());
      return(INIT_FAILED);
     }
   auto.TF2_macd_handle = iCustom(NULL,  auto.macdTF2, "::Macd_Tema.ex5", 12, 34, 9, PRICE_WEIGHTED, false, false, false);
   if(auto.TF2_macd_handle < 0)
     {
      Print("The creation of Hi4TF_Macd has failed: Hi4TF_handle=", INVALID_HANDLE);
      Print("Runtime error = ", GetLastError());
      return(INIT_FAILED);
     }
   ushort total0 = total;
   if(GlobalVariableCheck("_tsl") <= 0 || (GlobalVariableCheck("_tsl") > 0 && (total0 <= 0 ||  auto.bs < 1)))
      GlobalVariableSet("_tsl", 0.00);
   if(GlobalVariableCheck("_t2sl") <= 0 || (GlobalVariableCheck("_t2sl") > 0 && (total0 <= 0 ||  auto.bs < 1)))
      GlobalVariableSet("_t2sl", 0.00);
   auto.bal0 = bal;
   if(total0 < 1 ||  auto.bs < 1)
     {
      auto.tsl[0] =  auto.tsl[1] = 0.00;
      GlobalVariableSet("_tsl",  auto.tsl[0]);
      GlobalVariableSet("_t2sl",  auto.tsl[1]);
     }
   else
     {
      auto.tsl[0] = GlobalVariableGet("_tsl");
      auto.tsl[1] = GlobalVariableGet("_t2sl");
     }
   auto.currTime = iTime(NULL,  auto.macdTF, 0);
   auto.new3htfBuy = iTime(NULL,  auto.Higher3TF, 0) + 33 * 60; // ps3 +  ps3;
   auto.new3htfSel = iTime(NULL,  auto.Higher3TF, 0) + 33 * 60; // ps3 +  ps3;
   auto.tsltotal =  auto.GetLastHistoryPositions(true);
   Print("Profit from Closed trades by Trail stop= " + DoubleToString(auto.tsltotal, 2));
   auto.osd_to_be_called = true;
//if(!GlobalVariableCheck("LowTarget"))
//   GlobalVariableSet("LowTarget",0);
   if(!GlobalVariableCheck("prevClose") ||  auto.prevClose <= 0 || GlobalVariableGet("prevClose")<=0)
     {
      auto.prevClose = 0;
      auto.GetLastHistoryPositions(false);
      GlobalVariableSet("prevClose", (double) auto.historyBalTime);
      auto.prevClose = (double) auto.historyBalTime;
     }
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   auto.accounts();
   if(auto.checkGV() == true)
     {
      auto.check = true;
      auto.osd_to_be_called = true;
      auto.osd();
     }
   static int i, j;
   if(auto.osd_to_be_called)
      auto.osd();
   ulong tk = 0;
   auto.selMxg = auto.buyMxg = 0;
   auto.buyMng = auto.selMng = DBL_MAX;
   auto.pft =  auto.pftTotal =  auto.totalLosses =  auto.net =  auto.ltv = 0.00; // losr_buy=losr_sel=pft_buy=pft_sel=
   tk = 0;
   auto.b =  auto.s =  auto.b4 =  auto.s4 = auto.totalbuy = auto.totalsel = 0;
   auto.b2 =  auto.s2 = 1;
   int dig0 = Digits(), otyp = -1;
   static double worstp; //, eqplusb;
   double op = 0.000, stl = 0.000;
   double worsPft[]; //= {0,0,0,0,0,0,0,0,0,0,0,0};
   const double worsPrft = (-iStartLots * 450);
   static int worsCount, wors2Count, wors3Count;
   wors3Count = fmax(5,worsCount);
   i = -1;
   j =  auto.b2 +  auto.s2;
   auto.ltv = iStartLots;
   ushort total0 = total;
//   static double closeTarget, __ct; //, lowTarget, __lt;
//   static bool hitLow;
   if(total >= 1)
     {
      //      if(!hitLow)
      ///         hitLow = AccountInfoDouble(ACCOUNT_PROFIT)<=-iDrawdown*1000; //auto.equ0 <= closeTarget - iDrawdown * 1000;
      if(auto.testing)
        {
         //         __ct = closeTarget;
         //         closeTarget = ((__ct <= 0) ? fmax(iCloseTarget*1000,closeTarget) : __ct);
         //         closeTarget = fmax(iCloseTarget*1000,closeTarget);
         //         if(!hitLow)
         //            closeTarget = fmax(iCloseTarget*1000,fmax(equ0+iProfitInc*1000,closeTarget));
         //         else
         //            if(equ0 > 0 && equ0 > closeTarget) // && hitLow) // && lowTarget >= closeTarget
         //              {
         //               closeTarget = fmax(equ0,__ct); // + iProfitInc*1000;
         //               CloseTrades(j, 999, false, hitLow);
         //              }
        }
      static int wors4Cnt;
      wors4Cnt = fmax(4,wors3Count + 1);
      ArrayResize(worsPft, wors4Cnt, wors4Cnt);
      ArrayResize(auto.worsTics, wors4Cnt, wors4Cnt);
      if(!GlobalVariableCheck("prevClose") ||  auto.prevClose <= 0 || GlobalVariableGet("prevClose")<=0)
        {
         auto.GetLastHistoryPositions(false);
         GlobalVariableSet("prevClose", (double) auto.historyBalTime);
         auto.prevClose = (double) auto.historyBalTime;
        }
     }
   else
     {
      //      closeTarget = equ0+iProfitInc*1000;
      //      hitLow = false;
      ArrayResize(worsPft, worsCount + 1, worsCount + 1);
      ArrayResize(auto.worsTics, worsCount + 1, worsCount + 1);
     }
   static double worsLot;
//   static datetime ot;
   worsLot = 0.000;
   worsCount = wors2Count = 0;
   worstp = worsPft[0] = 0;
//   static string sym0;
//      sym0 = Symbol();
   for(int k = total0 - 1; k >= 0; k--)
      //   for(int k = PositionsTotal() - 1; k >= 0; k--)
     {
      if(position.SelectByIndex(k))
        {
         tk = position.Ticket();
         if(tk <= 0 || tk != position.Ticket())
            break;
         int otyp = position.Type();
         if(otyp != POSITION_TYPE_SELL && otyp != POSITION_TYPE_BUY)
            continue;
         auto.ltv = position.Volume();
         //auto.ot = position.Time();
         auto.pft = position.Profit(); /*
         if( ltv>i2ndLot)
           {
            if( pft>4.6)
               trade.PositionClosePartial(tk,i2ndLot,-1);
            //         if( ltv> iStartLot2 &&  pft>0)
            continue;
           } */
         auto.sw = position.Swap();
         //            xcm=position.Commission()*2;
         //auto.ot = position.Time();
         //         xltv += (ltv>iStartLots)? (ltv - iStartLots) * 24 : 0;
         auto.net =  auto.pft -  auto.iMinimalProfit +  auto.sw;
         auto.net += ((auto.net > - auto.xcm) ?  auto.xcm : - auto.iMinimalProfit);
         if(otyp == POSITION_TYPE_SELL)
           {
            //            sym0 = position.Symbol();
            //            dig0 = (int)SymbolInfoInteger(sym0,SYMBOL_DIGITS);
            //            op=position.PriceOpen();
            //            stl=position.StopLoss();
            auto.s++;
            auto.s2 += (auto.net > 0) ? 1 : 0;
            //            sym0 = position.Symbol();
            if(position.Symbol() == _Symbol)
              {
               auto.s4 += 1;
               if(auto.ltv >= iStartLots)
                 {
                  auto.totalsel+=1;
                  if(position.PriceOpen() > auto.selMxg)
                     auto.selMxg = position.PriceOpen();
                  if(position.PriceOpen() < auto.selMng)
                     auto.selMng = position.PriceOpen();
                 }
              }
           }
         else
            //            if(otyp==POSITION_TYPE_BUY)
           {
            auto.b++;
            auto.b2 += (auto.net > 0) ? 1 : 0;
            if(position.Symbol() == _Symbol)
              {
               auto.b4 += 1;
               if(auto.ltv >= iStartLots)
                 {
                  auto.totalbuy+=1;
                  if(position.PriceOpen() > auto.buyMxg)
                     auto.buyMxg = position.PriceOpen();
                  if(position.PriceOpen() < auto.buyMng)
                     auto.buyMng = position.PriceOpen();
                 }
              }
           }
         // ===
         if(auto.net <= 0)
            ++wors2Count;
         if(auto.net <= (- auto.minLoss))
           {
            ++worsCount;
            for(int f = 0; f <= wors3Count - 1; ++f)
               if(auto.net <= worsPft[f])
                 {
                  //                  for(int j=worsCount-1; j>=f+1; --j)
                  for(int j = wors3Count - 1; j > f; --j)
                    {
                     auto.worsTics[j] =  auto.worsTics[j - 1];
                     worsPft[j] = worsPft[j - 1];
                    }
                  worsPft[f] =  auto.net;
                  auto.worsTics[f] = tk;
                  worsLot =  auto.ltv;
                 }
           }
         if(auto.net > 0)
            auto.pftTotal +=  auto.net;
         else
            auto.totalLosses +=  auto.net;
        }
     }
   static ushort ptotal;
   auto.ccount=-1;
   if(total0 != ptotal)
     {
      if(!GlobalVariableCheck("prevClose"))
        {
         GlobalVariableSet("prevClose", (double)TimeCurrent());
         auto.prevClose = (double)TimeCurrent();
        }
      auto.trailPft =  auto.iMinimalProfit;
      //       tsltotal =  GetLastHistoryPositions(ptotal <= 0);
      ptotal = total0;
      auto.osd();
      auto.osd_to_be_called = true;
     }
   auto.bs =  auto.b +  auto.s;
   i = -1;
   j =  auto.b2 +  auto.s2;
   worstp = worsPft[0];
   double worstpc = 0.000; //worstp;
   worstpc = worsLot >= i2ndLot && worstp <= worsPrft ? fmin(i2ndLot,worsLot)/iStartLots*worstp : worstp;
   static double worsCalc, pftMinTrades;
   worsCalc = (auto.tsltotal < 0.00 ?  auto.tsltotal / 3 :  auto.tsltotal-fmax(0,1.62 *  auto.iMinimalProfit * j));
   pftMinTrades =  auto.trailPft;
   i = 0;
   auto.pft2Total =  auto.pftTotal + worsCalc;
   static uint tick;
   if(fmax(auto.pftTotal + auto.tsltotal, auto.pftTotal) + worstp > 1320 * i2ndLot) // iMinimalProfit * 4)
     {
      tick = GetTickCount() + 1;
      //      if(!hitLow)
      auto.CloseTrades(j, 1, false); //, hitLow);
      //      else
      //         CloseTrades(j, 1, false);
      return;
     }
   if((auto.pft2Total) / (auto.b2 +  auto.s2) >=  auto.trailPft)
      //      if(apft0<-minLoss || worstpc<-minLoss || equ0>bal0 || worstp>-minLoss) // && equ<fmin(MaxEqu[0],bal))
     {
      if(auto.pft2Total >= pftMinTrades && (auto.tsla <= 0 || (auto.tsla > 0 &&  auto.pftTotal >=  auto.tsla +  auto.trailPft)))
        {
         static bool pft3;
         if(!pft3 &&  auto.equ0 >  auto.bal0)
           {
            pft3 = true;
            auto.trailPft =  auto.iMinimalProfit * 1.38;
            auto.tsl[0] =  auto.tsla =  auto.pftTotal;
            GlobalVariableSet("_tsl",  auto.tsla);
           }
         else
            if(auto.equ0 <  auto.bal0)
               pft3 = false;
         GlobalVariableGet("_tsl",  auto.tsla);
         auto.trailPft +=  auto.iMinimalProfit * (auto.trailPft >  auto.iMinimalProfit * 4 ? 1.62 : 1.38);
         auto.tsl[0] =  auto.tsla =  auto.pftTotal;
         GlobalVariableSet("_tsl",  auto.tsla);
        }
      else
         if(auto.tsla > 0 &&  auto.pftTotal <  auto.tsla - (auto.iMinimalProfit * (auto.trailPft >  auto.iMinimalProfit * 4 ? 1.19 : 1)))
           {
            static double tpTotal;
            tpTotal =  auto.tsltotal+ auto.pftTotal;
            int worsCntb = worsCount; //fmin(worsCount,total0-1);
            //            worsPft[i] /= divisor;
            worsCalc = i = 0;
            //                           if(worsCntb >= 1 && worstpc + tpTotal >= pftMinTrades +  trailPft)
            if(worsCount > 1 && worsPft[0] + worsPft[1] + tpTotal > pftMinTrades +  auto.trailPft) // || worsPft[0]<-iStartLots*1000 || equ0+totalLosses<0.75*bal0)
               for(i = 0; i < worsCntb-1; ++i)
                 {
                  if(worsCntb < i)
                     break;
                  worsCalc += worsPft[i];
                  if(worsCalc + tpTotal < pftMinTrades +  auto.trailPft) // || worsPft[0]<-iStartLots*1000 || equ0+totalLosses<0.75*bal0)
                     break;
                 }
            tick = GetTickCount()+1;
            //            if(!hitLow)
            auto.CloseTrades(j, i, false); //, hitLow);
            //            else
            //               CloseTrades(j, i, false);
            return;
           }
     }
   auto.pntStep = (iPointOrderStep * pnt);
   static int ototal, htotal; // remember total open positions
   if((OrdersHistoryTotal() != htotal || PositionsTotal() != ototal) && GetTickCount() > tick + 2)
     {
      //       tsltotal =  GetLastHistoryPositions();
      static int __htotal;
      __htotal = htotal;
      htotal = OrdersHistoryTotal();
      if(PositionsTotal() == 1 || (__htotal != htotal)) // && htotal > __htotal))
         auto.tsltotal = auto.GetLastHistoryPositions(); //-fmax(0,1.62 * auto.iMinimalProfit * j);
      ototal = PositionsTotal();
      tick = GetTickCount() + 2;
      if(!auto.testing && __htotal > htotal) // && auto.tsltotal > 0) // && __prevTsltotal < auto.tsltotal)
        {
         Print("Profit from Closed trades by Trail stop= " + DoubleToString(auto.tsltotal, 2));
         Print("Prev Closed Time= " + TimeToString((datetime)GlobalVariableGet("prevClose"), TIME_DATE | TIME_MINUTES | TIME_SECONDS));
         //         c = 5;
        }
      __htotal = htotal;
      //      return;
     }
   if(!(CopyTime(NULL, PERIOD_CURRENT, 0, 5,  auto.Time) > sel)) // || (Time[0]<=new3htfSel && Time[0]<=new3htfBuy)) // && !gapBuy && !gapSel))
      return;
   datetime prevTime =  auto.currTime;
   auto.currTime =  auto.Time[0];
//   if(prevTime ==  currTime) // && (Time[0]<=new3htfSel && Time[0]<=new3htfBuy && !gapBuy && !gapSel))
//      return;
   if(!auto.buffers())
      return;
   auto.currTime =  auto.Time[0];
   if((auto.currTime >  auto.new3htfBuy ||  auto.currTime >  auto.new3htfSel) &&  auto.ask0 -  auto.bid0 <= Spread * 10 *  auto.pnt0)
     {
      static bool rsiThreshold;
      rsiThreshold =  auto.checkRsi();
      //      if(fabs(rsi40b - rsi40a) <= 5 && (fabs(rsi40b - rsi40a) >= 4 || fabs(rsi40a - rsi40b) >= 4 || fabs(rsi40a - rsi41a) >= 4 || fabs(rsi41a - rsi40a) >= 4))
      if(rsiThreshold)
        {
         rsiThreshold = false;
         static bool sigBuy, sigSel;
         sigSel =  auto.currTime >  auto.new3htfSel ? true : false; // openTradeType += 3;
         sigBuy =  auto.currTime >  auto.new3htfBuy ? true : false; // openTradeType += ( openTradeType == 2) ? 2 : 4;
         //         if(auto.openNewTrade(sigBuy, sigSel, auto.totalbuy, auto.totalsel) >= true)  // openTradeType) >= true)
         if(auto.openNewTrade(sigBuy, sigSel, auto.totalbuy, auto.totalsel) >= true) //auto.openTradeType) >= true)
            auto.CalculateHedgeAveragePrice();
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool AutoA3m::openNewTrade(bool buySignal, bool selSignal, int buyCount, int sellCount)
  {
   static double h0, h01;
   ResetLastError();
//   if(fabs(rsimacd40[2] - rsimacd40[1]) < 2.65 || fabs(rsimacd40[1] - rsimacd40[2]) < 2.65 || fabs(rsimacd40[1] - rsimacd41[1]) < 2.65 || fabs(rsimacd41[1] - rsimacd40[1]) < 2.65)
//      return false;
   /*   if(fabs(rsimacd40[2] - rsimacd40[1]) > 3.65 || fabs(rsimacd40[1] - rsimacd40[2]) > 3.65 || fabs(rsimacd40[1] - rsimacd41[1]) > 3.65 || fabs(rsimacd41[1] - rsimacd40[1]) > 3.65)
         buySignalb = selSignalb = true;
         else
         buySignalb = selSignalb = true; */
//   const double mgdistance = NormalizeDouble(160 / pow(10,dig),dig);
   static double mgdistance;
//   double maxi = fmin(maxLot, fmax(iStartLot, (equ0 * 2 - bal0) / 1000)); //  && (s4 < 1 || lastSel < pnt0)
   if(selSignal)
     {
      h0 = TF1_RSO[0];
      h01 = TF2_RSO[0];
      if(trend[0] == sel || trend[1] == sel) //trend[3]==sel ||
         if(h01 < TF2_RSO[1] - 3 || h0 < TF1_RSO[1] - 3)
           {
            new3htfSel = Time[0];
            ccount = 5;
            //           LastLot[sel] = iStartLots; //!bigsel ? iStartLots : (selMng < DBL_MAX && Last[sel] == selMng && (selMxg - selMng) / (160 / pow(10,dig)) < totalsel) ? iStart3Lots : i2ndLot;
            //double lotSel;
            if(sellCount < 2)
               LastLot[sel] = iStartLots;
            else
               //                  LastLot[sel] = i2ndLot;
              {
               mgdistance = NormalizeDouble(160 / pow(10,dig),dig);
               double distSel = bid - selMxg;
               if(distSel > mgdistance) // && selMxg > 0 && sellCount > 1) // && s4 >= 2)
                  LastLot[sel] = iStart3Lots;
               else
                  LastLot[sel] = i2ndLot;
              }
            //            LastLot[sel] = lotSel;
            osd();
            Last[sel] = bid;
            if(!trade.Sell(NormalizeDouble(LastLot[sel], 2)))
              {
               LastError = GetLastError();
               Print("OrderSend error #", LastError);
               if(testing != false && LastError == 10019 && LastError != 0)
                  ExpertRemove();
               new3htfSel = iTime(NULL, PERIOD_M6, 0);
               ResetLastError();
              }
            else
               if(!buySignal)
                  return true;
           }
     }
   if(buySignal)
     {
      h0 = TF1_RSO[0];
      h01 = TF2_RSO[0];
      if(trend[0] == buy || trend[1] == buy) //trend[3]==sel ||
         if(h01 > TF2_RSO[1] + 3 || h0 > TF1_RSO[1] + 3)
           {
            new3htfBuy = Time[0];
            ccount = 5;
            //           LastLot[buy] = iStartLots; //!bigbuy ? iStartLots : (buyMxg > 0 && Last[buy] == buyMxg && (buyMxg - buyMng) / (160 / pow(10,dig)) < totalbuy) ? iStart3Lots : i2ndLot;
            //double lotBuy;
            if(buyCount < 2)
               LastLot[buy] = iStartLots;
            else
               //                  LastLot[buy] = i2ndLot;
              {
               mgdistance = NormalizeDouble(160 / pow(10,dig),dig);
               double distBuy = buyMng - ask;
               if(distBuy > mgdistance) // && buyMng < DBL_MAX && buyCount > 1) // && b4 >= 2)
                  LastLot[buy] = iStart3Lots;
               else
                  LastLot[buy] = i2ndLot;
               //LastLot[buy] = lotBuy;
              }
            osd();
            Last[buy] = ask;
            if(!trade.Buy(NormalizeDouble(LastLot[buy], 2)))
              {
               LastError = GetLastError();
               Print("OrderSend error #", LastError);
               if(testing != false && LastError == 10019 && LastError != 0)
                  ExpertRemove();
               new3htfBuy = iTime(NULL, PERIOD_M6, 0);
               ResetLastError();
              }
            else
               return true;
           }
     }
   return false;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   Comment("");
//   if(reason==REASON_PARAMETERS || reason==REASON_RECOMPILE)
   auto.osd_to_be_called = true;
   if(auto.tsl[0] >  auto.pnt0)
      GlobalVariableSet("_tsl",  auto.tsl[0]);
   if(auto.tsl[1] >  auto.pnt0)
      GlobalVariableSet("_t2sl",  auto.tsl[1]);
//   tsl[0]=tsla=0.00;
//   tsl[1]=tslb=0.00;
   auto.tsltotal =  auto.GetLastHistoryPositions();
   auto.trailPft =  auto.iMinimalProfit;
   auto.ccount = 3;
   auto.release();
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool  AutoA3m::buffers()
  {
   int i = 1, j = i - 1;
   double h0 = 999, h1 = 999, h02 = 999, h12 = 999;
   ArrayResize(tap, 5, 5);
   ArrayResize(TF1_RSO, 5, 5);
   ArrayResize(TF2_RSO, 5, 5);
   ArrayResize(Time, 5, 5);
   ArrayResize(macd20, 5, 5);
   ArrayResize(macd21, 5, 5);
   ArrayResize(macd30, 5, 5);
   ArrayResize(macd31, 5, 5);
   ArrayResize(hi1Time, 5, 5);
   ArrayResize(hi2Time, 5, 5);
   ArrayResize(hi3Time, 5, 5);
   ArrayResize(hi4Time, 5, 5);
   ArrayResize(rsimacd40, 5, 5);
   ArrayResize(rsimacd41, 5, 5);
   for(i = 1; i < 6; ++i)
     {
      if(!(CopyTime(NULL, Higher3TF, 0, 5, hi3Time) > j))
         continue;
      else
         if(!(CopyTime(NULL, macdTF2, 0, 5, hi1Time) > j))
            continue;
         else
            if(!(CopyTime(NULL, Higher2TF, 0, 5, hi2Time) > j))
               continue;
            else
               if(!(CopyTime(NULL, Higher4TF, 0, 5, hi4Time) > j))
                  continue;
               else
                  if(!(CopyBuffer(tapMa_handle, 0, 0, 5, tap) > j))
                     continue;
                  else
                     if(!(CopyBuffer(TF2_macd_handle, 1, 0, 5, macd31) > j)) // || macd21[0]==EMPTY_VALUE)
                        continue;
                     else
                        if(!(CopyBuffer(TF2_macd_handle, 0, 0, 5, macd30) > j))
                           continue;
                        else
                           if(!(CopyBuffer(TF2_RSO_handle, 0, 0, 5, TF2_RSO) > j)) // || TF1_RSO[0]==EMPTY_VALUE || TF1_RSO[1]==EMPTY_VALUE || TF1_RSO[2]==EMPTY_VALUE)
                              continue;
                           else
                              if(!(CopyBuffer(rsiMacd_handle, 1, 0, 5, rsimacd41) > j)) // || macd21[0]==EMPTY_VALUE)
                                 continue;
                              else
                                 if(!(CopyBuffer(rsiMacd_handle, 0, 0, 5, rsimacd40) > j))
                                    continue;
                                 else
                                    if(!(CopyBuffer(TF1_macd_handle, 1, 0, 5, macd21) > j)) // || macd21[0]==EMPTY_VALUE)
                                       continue;
                                    else
                                       if(!(CopyBuffer(TF1_macd_handle, 0, 0, 5, macd20) > j))
                                          continue;
                                       else
                                          if(!(CopyBuffer(TF1_RSO_handle, 0, 0, 5, TF1_RSO) > j)) // || TF1_RSO[0]==EMPTY_VALUE || TF1_RSO[1]==EMPTY_VALUE || TF1_RSO[2]==EMPTY_VALUE)
                                             continue;
                                          else
                                            {
                                             h0 = TF1_RSO[0];
                                             h1 = TF1_RSO[1];
                                             h02 = TF2_RSO[0];
                                             h12 = TF2_RSO[1];
                                             if(i < 6 && ((h0 <= 100.00 && h1 <= 100.00 && h0 >= 0.00 && h1 >= 0.00 && (h0 < h1 - 3 || h0 > h1 + 3))
                                                          || (h02 <= 100.00 && h12 <= 100.00 && h02 >= 0.00 && h12 >= 0.00 && (h02 < h12 - 3 || h02 > h12 + 3))))
                                               {
                                                if(trendy())
                                                   return true;
                                               }
                                             else
                                                break;
                                            }
     }
   return false;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool  AutoA3m::trendy()
  {
   datetime hi4t = Time[0];
   int newCandle = hi4t > new3htfSel ? hi4t > new3htfBuy ? 3 : sel : buy;
   int can1dle = hi4t == hi1Time[0] ? 1 : 0; // M20
   int can2dle = hi4t == hi2Time[0] ? 1 : 0; // M20
   int can3dle = hi2Time[0] == hi3Time[0] ? 1 : 0; // H1
   int can4dle = hi3Time[0] == hi4Time[0] ? 1 : 0; // H3
   if(newCandle == sel)
      return true;
   if(tap[0]<tap[1] && (trend[1] != sel || trend[0] != sel))
     {
      if(macd20[can2dle + 0] < macd20[can2dle + 2] - (dista * 1.62) && (macd20[can2dle + 0] < macd21[can2dle + 1] - dista || macd21[can2dle + 0] < macd20[can2dle + 1] - dista))
         trend[1] = sel;
      if(macd30[can1dle + 0] < macd30[can1dle + 2] - (dista * 1.62) && (macd30[can1dle + 0] < macd31[can1dle + 1] - dista || macd31[can1dle + 0] < macd30[can1dle + 1] - dista))
         trend[0] = sel;
     }
   else
      if(tap[0]>tap[1] && (trend[1] != buy || trend[0] != buy))
        {
         if(macd20[can2dle + 0] > macd20[can2dle + 2] + (dista * 1.62) && (macd20[can2dle + 0] > macd21[can2dle + 1] + dista || macd21[can2dle + 0] > macd20[can2dle + 1] + dista))
            trend[1] = buy;
         if(macd30[can1dle + 0] > macd30[can1dle + 2] + (dista * 1.62) && (macd30[can1dle + 0] > macd31[can1dle + 1] + dista || macd31[can1dle + 0] > macd30[can1dle + 1] + dista))
            trend[0] = buy;
        }
   return true;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void  AutoA3m::CloseTrades(int dcount, int no2close = 999, bool worsParty = false) //, bool closeddtrade = true)
  {
   ulong tk;
   const double com = -iStartLots * 6;
   int neg = 0, otyp = 9;
//   const double divisor = iStartLots / 0.01 + 1;
   uint worst = no2close != 999 && no2close >= 1 ? (uint)worsTics[0] : 0;
   for(int k = total - 1; k >= 0; k--)
     {
      if(position.SelectByIndex(k))
        {
         otyp = position.Type();
         if(otyp != POSITION_TYPE_SELL && otyp != POSITION_TYPE_BUY)
            continue;
         tk = position.Ticket();
         if(no2close==999)
           {
            trade.PositionClose(tk,-1);
            continue;
           }
         sw = position.Swap();
         pft = position.Profit();
         xcm = com;
         //         ltv=(!party?position.Volume():NormalizeDouble(fmax(position.Volume()/divisor,0.01),2));
         ltv = position.Volume();
         double party = ltv / i2ndLot;
         xcm *= (ltv / iStartLots);
         net = pft + sw + xcm;
         //         if(net > iMinimalProfit || (no2close == 999 || (no2close == 1 && tk==worst)))
         if(net > iMinimalProfit || (no2close == 999 || (no2close == 1 && tk==worst)))
           {
            if(tk == worst)
               ++neg;
            if(net > iMinimalProfit || no2close == 999 || (no2close == 1 && tk == worst && (!worsParty || ltv <= i2ndLot)))
               trade.PositionClose(tk);
            else
               if(worsParty && tk == worst && ltv > i2ndLot)
                  //               if(no2close == 1 && net < minLoss && worsParty)
                 {
                  tsltotal+=i2ndLot/iStartLots*net;
                  ltv = (NormalizeDouble(i2ndLot, 2));
                  trade.PositionClosePartial(tk, ltv, -1);
                 }
           }
         else
            if(worst > 1 && no2close > 1 && net < -minLoss && neg < no2close)
              {
               for(int i = 0; i < no2close; ++i)
                 {
                  tk = position.Ticket();
                  if((worsTics[i] > 0 && tk == worsTics[i]) || tk == worst)
                    {
                     ++neg;
                     if(ltv <= i2ndLot || !worsParty) // || ltv < half)
                        trade.PositionClose(tk);
                     else
                       {
                        ltv = (NormalizeDouble(i2ndLot, 2));
                        trade.PositionClosePartial(tk, ltv, -1);
                       }
                    }
                 }
              }
        }
     }
   if(no2close >= 1)
     {
      prevClose = (double)TimeCurrent() + 0.05; //TimeTradeServer(); //GlobalVariableGet("time");
      GlobalVariableSet("prevClose", prevClose);
      tsltotal -= fmax(0,1.62 * iMinimalProfit * dcount);
     }
   osd_to_be_called = true;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void  AutoA3m::accounts()
  {
   bal0 = bal;
   equ0 = equ;
   apft0 = apft;
   ask0 = ask;
   bid0 = bid;
   pnt0 = pnt;
   pntStep = (iPointOrderStep * pnt0);
   mlvl0 = mlvl;
   maxLoss = -iStartLots * 1000 * 3.24;
   iMinimalProfit = 6 * iStartLots * 1.618033;
//   eqplus = iEquityStop * iStartLots * 10;
   xcm = -iStartLots * 27;
   marg = mlvl0 > lever * 16.18034;
   minLoss = 1000 * iStartLots * (mlvl0 > lever * 16.18034 ? 0.35 : mlvl0 > lever * 6.18034 ? 0.25 : 0.15);
//   eqplus = ((mlvl0 < lever && bs >= 1) ? 35 : iEquityStop) * iStartLots * 10;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool  AutoA3m::IsFridayTrue()
  {
   MqlDateTime structTime;
   TimeCurrent(structTime);
   if(structTime.day_of_week == 5 && structTime.hour >= 18)
      return true;
//---
   return false;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
/*bool  AutoA3m::IsHourTrue()
  {
   MqlDateTime structTime;
   TimeCurrent(structTime);
   if(structTime.hour >= 2 && structTime.hour <= 21)
      return true;
//---
   return false;
  } */
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool  AutoA3m::osd()
  {
//   lastselOT = lastbuyOT = LastOT[buy] = LastOT[sel] = 0;
//   start = fmax(iStartLots,iStartLots*1000/baseStart*equ0/1000);
   iMinimalProfit      = 6 * iStartLots * 2;
   minLoss = 1000 * iStartLots * (mlvl0 > lever * 16.18034 ? 0.35 : mlvl0 > lever * 6.18034 ? 0.25 : 0.15);
   pntStep = (iPointOrderStep * pnt0);
   xcm = -iStartLots * 27;
//   openTradeType = none;
   GlobalVariableSet("_tsl", 0.00);
   GlobalVariableSet("_t2sl", 0.00);
   tsl[0] = tsla = 0.00;
   tsl[1] = tslb = 0.00;
   trailPft = iMinimalProfit;
   if(!testing)
      if(PositionsTotal() < 1 || bs < 1 || check)
        {
         Print("GVs updated");
         Print("Profit from Closed trades by Trail stop= " + DoubleToString(tsltotal, 2));
        }
   if(!testing)
      Comment(//"                                          Manager = " + (iManager?"Yes":"No")+
         //         "\n                                           Profit Target = $" + DoubleToString(eqplus, 2) +
         //      ", Trades = " + DoubleToString(Trades,0)+
         //      ", TargetProfit = " + DoubleToString(TargetProfit,2) +
         "\n                                           Minimal Profit per Trade = " + DoubleToString(iMinimalProfit, 2) +
         ", MinLoss = " + DoubleToString(minLoss, 2) +
         ", Trade Lot = " + DoubleToString(iStartLots, 2) +
         //      ", MagicNumber = " + DoubleToString(MagicNumber,0)+
         ", Slippage = " + DoubleToString(iSlippage * 10, 0) +
         ", Spread = " + DoubleToString(Spread * 10, 0)
      );
   osd_to_be_called = check = false;
   return true;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool  AutoA3m::release()
  {
   IndicatorRelease(TF1_RSO_handle);
   IndicatorRelease(TF2_RSO_handle);
   IndicatorRelease(TF1_macd_handle);
   IndicatorRelease(TF2_macd_handle);
   IndicatorRelease(rsiMacd_handle);
   rsiMacd_handle = TF1_RSO_handle = TF1_macd_handle = TF2_RSO_handle = TF2_macd_handle = INVALID_HANDLE;
   return true;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool  AutoA3m::checkGV()
  {
   bool chk3 = GlobalVariableGet("_tsl") == tsl[0];
   bool chk4 = GlobalVariableGet("_t2sl") == tsl[1];
   if(chk3 != chk4)
      return true;
   return false;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double  AutoA3m::CalculateHedgeAveragePrice()
  {
   dt[0] = iTime(_Symbol, PERIOD_M1, 0);
   return 0;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool  AutoA3m::checkRsi()
  {
   static double rsi40a, rsi40b, rsi41a;
   rsi40a =  rsimacd40[1];
   rsi40b =  rsimacd40[2];
   rsi41a =  rsimacd41[1];
   if(fabs(rsi40b - rsi40a) <= 5 && (fabs(rsi40b - rsi40a) >= 4 || fabs(rsi40a - rsi40b) >= 4 || fabs(rsi40a - rsi41a) >= 4 || fabs(rsi41a - rsi40a) >= 4))
      return true;
   return false;
  }
//+------------------------------------------------------------------+
