//+------------------------------------------------------------------+
//|                                                   Project EA.mq4 |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+


#property copyright "Copyright © Forex AutoPilot: Supercharged! LLC \n All rights reserved.  \nNone of this EA may be reproduced in part or in full without the expressed written consent of Forex Autopilot:SUPERCHARGED! LLC."
#property link      ""

//+------ Project EA ------+

extern string Remark1 = "== Main Settings ==";
extern double Lots = 0.1;
extern double LotsRiskReductor = 1.0;
extern int MaxOrders = 1;
extern int MaxLots = 100;
extern int StopTime = 20;
extern double EquityStopPercent=10.0;
extern bool CloseEndMonth = True;
extern int SlipPage = 3;
extern int OrderMagic = 1;

extern string Remark2 = "== Trader Functions ==";
extern double TakeProfit = 15.0;
extern double StopLoss = 0.0;
extern bool TradeTrip = False;
extern double TripLevel = 5.0;
extern bool TradeTrailing=true;
extern double TrailingStop = 0.0;
extern double TrailingStep=5;

extern string Remark3 = "== Filter settings are lookback periods for filters ==";
extern bool UseFilterA = True;
extern int FilterAPeriod = 13;
int ChartDeM = 0;
double DeMLow = 0.5;
double DeMHigh = 0.5;
extern bool UseFilterB = True;
extern int FilterBPeriod = 14;
int ChartWPR = 0;
double WPRBuy = 0.25;
double WPRSell = 0.75;
extern bool UseFilterC = True;
extern int FilterCPeriod = 14;
extern int FilterCTF = 5;
int RSIHigh = 55;
int RSILow = 45;
extern bool UseMAControl = True;

extern string Remark4 = "== Timeframe inputs 60=h1, 240=h4 ,1440=d1, 10080=W1, 40320=Monthly ==";
extern int ChartMa =1440; //Daily
extern int PeriodMA = 100;

extern string Remark5 = "== 0=close, 1=open, 2=high, 3=low, 4=median((H+L)/2), 5=typical((H+L+C)/3), 6=Weighted close((H+L+C+C)/4) ==";
extern int PriceMA_0_6 = 0;
extern double SpanGator = 0.5;

extern string Remark6 = "== 0=simple, 1=exponential, 2=smoothed, 3=linear weighted ==";
extern int TypeMA_0_3 = 0;

extern string Remark7 = "== Hedger Functions ==";
extern bool Hedger=true;
extern double Hedger_PipsAway=10;
extern double Hedger_LotMultiplier=2;
extern string ExpiredMinutesNote   =   "minimum input=20";
extern int Hedger_ExpiredMinutes=20;


//extern bool BreakEven=true;

extern bool BasketBreakEven=true;  // all trades=0
extern bool TraderHedgerBreakEven=true;  // trade+hedge=0
 

extern bool Hedger_TradeTrip = False;
extern double Hedger_TripLevel = 5.0;
extern bool Hedger_TradeTrailing=true;
extern double Hedger_TrailingStop = 0.0;
extern double Hedger_TrailingStep=5;
extern string Hours = "== Time of Day ==";
extern int StartWorkTimeHour = 0;
extern int StartWorkTimeMin = 0;
extern int EndWorkTimeHour = 0;
extern int EndWorkTimeMin = 0;
extern string DoW = "== Day of Week Sunday=0,Monday=1, Tueday=2, Wednesday=3, Thursday=4, Friday=5 ==";
extern int DoWStart = 0;
extern int DoWEnd = 6;
extern string DoY = "== Day of Year ==";
extern int DoYStart = 7;
extern int DoYEnd = 360;

bool RSILong = True;
bool RSIShort = True;
int gi_208;
double RSI;
double dblPoints;
double aligator0;
double aligator1;
double aligator2;
double ddigit;
double g_str2dbl_244;
double fractalLow;
double fractalUp;
double ma1;
double ma0;
string g_dbl2str_284;
double deMarker[];
double wpr[];
double orderHistVal[9];
int g_datetime_300;
double YesterdayHigh;
double YesterdayLow;
double YesterdayClose;
double Day_Price[][6];
double Pivot,S1,S2,S3,R1,R2,R3;
double WeekHigh;
double WeekLow;
double WeekClose;
double Weekly_Price[][6];
double WeekPivot;
double MonthHigh;
double MonthLow;
double MonthClose;
double Month_Price[][6];
double MonthPivot,MS1,MR1;
static double blcStop;
double idm, iwpr;

string xsgn, thdnnote;
bool systemON=true;
string BEStatus="go";


int init() 
{  blcStop=AccountBalance()-(AccountBalance()*EquityStopPercent/100);
   //blcStop=AccountBalance()*EquityStopPercent/100;
   dblPoints = GetPoints();
   if (StartWorkTimeHour < 0 || StartWorkTimeHour > 23) StartWorkTimeHour = 0;
   if (StartWorkTimeMin < 0 || StartWorkTimeMin > 59) StartWorkTimeMin = 0;
   if (EndWorkTimeHour < 0 || EndWorkTimeHour > 23) EndWorkTimeHour = 0;
   if (EndWorkTimeMin < 0 || EndWorkTimeMin > 59) EndWorkTimeMin = 0;
   if (Hedger_ExpiredMinutes < 20) Hedger_ExpiredMinutes = 20;
   return (0);
}

int deinit() 
{
   return (0);
}
//=================
void cleanHedge() 
{  if(jmlOrderTrade()==0)
      { if(jmlOrderPending()>0)  cleanPendingOrders(); }

}
int jmlOrderTrade()
{ int gantung;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() != Symbol()) continue;
      if (OrderCloseTime()==0 ) continue;
      if(OrderType()!=OP_BUY || OrderType()!=OP_SELL ) continue;
      if(OrderMagicNumber()!=OrderMagic  ) continue;
      if(StringFind(OrderComment(),"Hedger")>=0) continue;
      gantung++;
   }
 return(gantung);
 }

int jmlOrderHedge()
{ int gantung;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() != Symbol()) continue;
      if(OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP ) continue;
      if(OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT ) continue;
      if(OrderMagicNumber()!=OrderMagic  ) continue;
      if(StringFind(OrderComment(),"Hedger")==-1) continue;
      gantung++;
   }
 return(gantung);
 }

int jmlOrderPending()
{ int gantung;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() != Symbol()) continue;
      if(OrderType()==OP_BUY || OrderType()==OP_SELL ) continue;
      if(OrderMagicNumber()!=OrderMagic  ) continue;
      gantung++;
   }
 return(gantung);
 }

double jmlProfitTrade()
{ double gantung;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() != Symbol()) continue;
      if(OrderType()!=OP_BUY && OrderType()!=OP_SELL ) continue;
      if(OrderMagicNumber()!=OrderMagic  ) continue;
      if(StringFind(OrderComment(),"Hedger")>-1) continue;
      gantung=gantung+OrderProfit();
   }
 return(gantung);
 }

double jmlProfitHedge()
{ double gantung;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() != Symbol()) continue;
      if(OrderType()!=OP_BUY && OrderType()!=OP_SELL ) continue;
      if(OrderMagicNumber()!=OrderMagic  ) continue;
      if(StringFind(OrderComment(),"Hedger")==-1) continue;
      gantung=gantung+OrderProfit();
   }
 return(gantung);
 }

double jmlProfitAll()
{ double gantung;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() != Symbol()) continue;
      if(OrderType()!=OP_BUY && OrderType()!=OP_SELL ) continue;
      if(OrderMagicNumber()!=OrderMagic  ) continue;
      gantung=gantung+OrderProfit();
   }
 return(gantung);
 }
 
 void closeBEBasket()
 { if(jmlOrderHedge()>0)
   {  if(jmlProfitAll()>=0) { Print("closeBEBasket()");  BEStatus="wait"; //CloseIt(); } }
    CloseAllOrders(); } }
 }

 void closeBETraderHedge()
 { //if(jmlOrderHedge()>0)
    // {  if(jmlProfitHedge()+jmlProfitTrade()>=0) { Print("closeBEHedge()");  BEStatus="wait"; //CloseIt(); } }
    //CloseAllOrders(); } }
   double hdgBuyRange, hdgSellRange, xspread, slip, xp=Point;
   xspread=Ask-Bid;
   slip=SlipPage*xp;
   if(Digits==3 || Digits==5) xp=Point*10;
   hdgBuyRange= Hedger_PipsAway * xp + xspread; 
   hdgSellRange = Hedger_PipsAway * xp ;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() != Symbol()) continue;
      if(OrderType()!=OP_BUY && OrderType()!=OP_SELL ) continue;
      if(OrderMagicNumber()!=OrderMagic  ) continue;
     
           
      if(StringFind(OrderComment(),"Hedger")>-1) 
         {  int trdTicket;
            int hdgTicket = OrderTicket();
            double hdgProfit=OrderProfit();
            double hdgPrice=NormalizeDouble(OrderOpenPrice(),Digits);
            int hdgDir=OrderType();
            
             for (int cnt2 = OrdersTotal()-1 ; cnt2 >= 0; cnt2--) 
               {  OrderSelect(cnt2,SELECT_BY_POS,MODE_TRADES); 
                  if (  OrderSymbol() == Symbol() &&  OrderMagicNumber()==OrderMagic &&
                        StringFind(OrderComment(),"Hedger")==-1 &&
                        (  (hdgDir==0 && OrderType()==OP_SELL) ||  
                           (hdgDir==1 && OrderType()==OP_BUY )  
                         )
                      )
                      { double trdPrice=OrderOpenPrice();
                        double trdProfit=OrderProfit();
                              
                        
                        if(hdgDir==0)
                           {  if(trdPrice >= hdgPrice-hdgBuyRange-slip && trdPrice <= hdgPrice-hdgBuyRange+slip)
                                 {  //if(trdProfit+hdgProfit>0) 
                                      if(OrderTicket()<hdgTicket>0)  trdTicket=OrderTicket();
                                    //else continue;
                                 }
                           }      
                        if(hdgDir==1)
                           {  if(trdPrice >= hdgPrice+hdgSellRange-slip && trdPrice <= hdgPrice+hdgSellRange+slip)
                                 {  //if(trdProfit+hdgProfit>0) 
                                    if(OrderTicket()<hdgTicket>0) trdTicket=OrderTicket();
                                    //else continue;
                                 }
                           }      
                        
                        thdnnote= hdgTicket+" - "+ trdTicket + " = " + 
                                    DoubleToStr(hdgProfit,2) + " + " +
                                    DoubleToStr(trdProfit,2) + "==> " +
                                    DoubleToStr(hdgProfit+trdProfit,2); 
                        //Print(thdnnote);
                     //==========
                     if(trdTicket>0 && (trdProfit+hdgProfit>0) )
                        {  for (int cnt3 = OrdersTotal()-1 ; cnt3 >= 0; cnt3--) 
                              {  OrderSelect(cnt3,SELECT_BY_POS,MODE_TRADES); 
                                 if (  OrderSymbol() == Symbol() &&  OrderMagicNumber()==OrderMagic &&
                                       (OrderType()==OP_BUY || OrderType()==OP_SELL ) 
                                    )
                                 
                                    {  bool tBuy=false, tSell=false, bBuy=false, bSell=false;
                                       if(OrderTicket()==trdTicket || OrderTicket()==hdgTicket)
                                       {  double aask=NormalizeDouble(Ask,Digits);
                                          double bbid=NormalizeDouble(Bid,Digits);
                                          if(OrderType()==OP_BUY)
                                             {  if(!tBuy) tBuy = OrderClose(OrderTicket(),OrderLots(),bbid,999,Yellow);
                                             }   
                                          if(OrderType()==OP_SELL)
                                             {  if(!tSell) tSell = OrderClose(OrderTicket(),OrderLots(),aask,999,Yellow);
                                             }   
                                        
                                          if(tSell) Print("success closed the Sell, closeBETraderHedge");
                                          if(tBuy) Print("success closed the Buy, closeBETraderHedge");
                                       } //if(OrderTicket()==trdTicket || OrderTicket()==hdgTicket)     
                                    } //if (  OrderSymbol() == Symbol() &&  OrderMagicNumber()==OrderMagic &&
                              }//for (int cnt3 = OrdersTotal()-1 ; cnt3 >= 0; cnt3--) 
                        //return;
                        } //if(trdTicket>0)
                        
                   //   else continue;  
                        
                 }  //   if (  OrderSymbol() == Symbol() &&  OrderMagicNumber()==OrderMagic &&
             //return;
             } //for (int cnt2 = OrdersTotal()-1 ; cnt2 >= 0; cnt2--) 
             
         }//if(StringFind(OrderComment(),"Hedger")>-1) 
      
   }  //for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
 }  
//=================
/* Start of Program Loop */
int start() 
{   
    if(Hedger==true) 
      {  if(BasketBreakEven) closeBEBasket();
         if(TraderHedgerBreakEven) closeBETraderHedge();
    
         if(BEStatus=="wait") cleanHedge();
         if(jmlOrder()==0 && jmlOrderStop()==0)           
            {  BEStatus="go"; }
      }       

//============    
    if(ChartMa<60)
    {
      Alert("The only Timeframes you can use for ChartMa are Monthly (43200), "+
             "Weekly (10080),  Daily (1440), 4 Hour (240) and Hourly (60)!!!");
      return(0);
    }
    
    int nProfit;
    ddigit = MarketInfo(Symbol(), MODE_DIGITS);
    g_dbl2str_284 = DoubleToStr(g_str2dbl_244, ddigit);
    g_str2dbl_244 = StrToDouble(g_dbl2str_284);
    


//if(jmlOrder()==0) double blcStop=AccountBalance()-(AccountBalance()*EquityStopPercent/100);

if(jmlOrder()>0)
{  if(AccountEquity()<=blcStop) { CloseAllOrders();  Print("Closed by The EquityStopPercent"); }
   if(jmlOrder()==0 && jmlOrderStop()==0 && AccountEquity()<=blcStop )
      {  Print("Stoped by The EquityStopPercent");
         systemON=false;
         return(0);
      }
}      

string prop="Copyright © Forex AutoPilot: Supercharged! LLC \n All rights reserved.  \nNone of this EA may be reproduced in part or in full without the expressed written consent of Forex Autopilot:SUPERCHARGED! LLC.";

//ttt
Comment( prop+
         "\n\n" +  "   blcStop  =  " + DoubleToStr(blcStop,2)+" -  "+
         "  equity now  =  " + DoubleToStr(AccountEquity(),2) +" \n  "+
         "  ProfitTrd  =  " + DoubleToStr(jmlProfitTrade(),2) +"   "+
         "  ProfitHdg  =  " + DoubleToStr(jmlProfitHedge(),2) +"   "+
         "  ttlProfit  =  " + DoubleToStr(jmlProfitAll(),2) +" \n  "+
         
         "  OrderPending  =  " + jmlOrderPending() +"   "+
         "  OrderHedge  =  " + jmlOrderHedge() +" \n  "+
    //       thdnnote +" \n  "+
        
         
         "\n" +  "   sgn  =  " + xsgn +" \n  "+
         
               " \n  MAGator() = " + MAGator() +
         "      IsGatorActiveUp() = " + IsGatorActiveUp() +
         // "      IsGatorActiveDn() = " + IsGatorActiveDn() +
         " \n  IsFractalUpper() = " + IsFractalUpper() +
         "      IsFractalLower() = " + IsFractalLower() +

         " \n  WasDemarkerLow() = " + WasDemarkerLow() +
         "     WasDemarkerHigh() = " + WasDemarkerHigh() +
         
         " \n  WasWPROverBuy() = " + WasWPROverBuy() +
         "     WasWPROverSell() = " + WasWPROverSell() +
         

         " \n  RSIFilter() = " + RSIFilter() +
         "     RSIShort  = " + RSIShort +
         "     RSILong  = " + RSILong +
                          
         
         "\n\n" + 
   
         
  
         " \n ");

   /*double stopdollar=AccountBalance()-(AccountBalance()*EquityStopPercent/100);
   string equitystopcheck = "Waiting";
   if(AccountEquity()<=AccountBalance()-(AccountBalance()*EquityStopPercent/100))
      {
         equitystopcheck = "Close Triggered";
      }
   Comment("Account Balance:  " + DoubleToStr(AccountBalance(), 2), "\n", 
         "Account Equity:  " + DoubleToStr(AccountEquity(), 2), "\n",
         "Equity Stop %:  " + DoubleToStr(EquityStopPercent,2), "\n",
         "Equity Stop $:  " + DoubleToStr(stopdollar, 2), "\n",
         "Equity Stop Status:  " + (equitystopcheck)
         );*/

    if (!IsTradeAllowed()) return (0);
    if (!IsConnected() && !IsTesting()) return (0);
    if (IsStopped()) return (0);
    if (IsTradeContextBusy() && !IsTesting()) 
        {
        Print("Trade context is busy!");
        return (0);
        }
    if (!IsDateTimeEnabled(TimeCurrent()) && !IsTesting()) return (0);
    if (!CheckParams()) return (0);
    if (!PrepareIndicators()) return (0);
    int nOrder = CalculateCurrentOrders();
    
    if(EquityStopPercent>0.0)
      {  if(AccountEquity()<=AccountBalance()-(AccountBalance()*EquityStopPercent/100))
            CloseAllOrders();
      }
//-----------------------------   



    if (nOrder > 0) 
      { for(int TicketNumber = nOrder - 1; TicketNumber >= 0; TicketNumber--) 
           {  if(GetOrderByPos(TicketNumber)) 
                { if(OrderMagicNumber() == OrderMagic) 
                    {  if(TradeSignalCloseOrder() || TradeSignalCloseOrderOnTime(TicketNumber))  
                           {  Print("closed by  TradeSignalCloseOrder() || TradeSignalCloseOrderOnTime(TicketNumber)");
                              CloseOrder();
                           }   
                       else
                        {  if(TradeTrip == True || Hedger_TradeTrip == True)
                             {   if(TradeTrip == True && StringFind(OrderComment(),"Hedger")==-1)
                                    {  if (OrderType() == OP_BUY)       
                                             nProfit = (Bid - OrderOpenPrice()) / dblPoints;
                                       else                             
                                             nProfit = (OrderOpenPrice() - Ask) / dblPoints;
                                       if (nProfit >= TripLevel && TripLevel != 0.0)
                                          {  if (nProfit < orderHistVal[TicketNumber] && nProfit > 0.0)     
                                                CloseOrder();
                                             orderHistVal[TicketNumber]=nProfit;
                                          }
                                    }
                                 if(Hedger_TradeTrip == True && StringFind(OrderComment(),"Hedger")!=-1)
                                    {  if (OrderType() == OP_BUY)       
                                          nProfit = (Bid - OrderOpenPrice()) / dblPoints;
                                       else                             
                                          nProfit = (OrderOpenPrice() - Ask) / dblPoints;
                                       if (nProfit >= Hedger_TripLevel && Hedger_TripLevel != 0.0)
                                          {  if (nProfit < orderHistVal[TicketNumber] && nProfit > 0.0)     
                                                {  Print("closed by  nProfit < orderHistVal[TicketNumber] && nProfit > 0.0");
                                                   CloseOrder();
                                                }
                                             orderHistVal[TicketNumber]=nProfit;
                                          }
                                    }
                              }
                           else
                              {  if (OrderTakeProfit() == 0.0) 
                                    {  if (OrderType() == OP_BUY)       
                                          nProfit = (Bid - OrderOpenPrice()) / dblPoints;
                                       else                             
                                          nProfit = (OrderOpenPrice() - Ask) / dblPoints;
                                       if (nProfit >= TakeProfit && TakeProfit != 0.0)          
                                          {  Print("closed by  nProfit >= TakeProfit && TakeProfit != 0.0");
                                             CloseOrder();  return (0); }                                
                                       if (TakeProfit > MarketInfo(Symbol(), MODE_STOPLEVEL))  // ModifyOrder();
                                          {  int dir = OrderTypeDirection();
                                             double mpp=Point;
                                             if(Digits==3||Digits==5) mpp=Point*10;
                                            // double mtp = g_str2dbl_244 + TakeProfit * mpp * dir;
                                             double mtp = OrderOpenPrice() + TakeProfit * mpp * dir;
                                             mtp=NormalizeDouble(mtp,Digits);
                                             if(NormalizeDouble(OrderTakeProfit(),Digits)!=mtp)
                                             {  Print("modify TP");
                                                OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), mtp, OrderExpiration(), Red);
                                             }
                                          }   
                                    }
                                }
                           if (TrailingStop > 0.0 && TradeTrailing)                 TrailOrderStop(TrailingStep);
                           if (Hedger_TrailingStop > 0.0 && Hedger_TradeTrailing)   Hedger_TrailOrderStop(Hedger_TrailingStep);
                        }
                    }
                }//if(GetOrderByPos(TicketNumber)) 
           }//for(int TicketNumber = nOrder - 1;
       if(nOrder < MaxOrders && systemON )
         {  if ((TimeCurrent() - g_datetime_300) / 60 >= StopTime)   TrueOpen();   }      
       return (0);
      } //if (nOrder > 0) 
    if(MaxOrders == 0) return (0); 
       
    if(systemON)  TrueOpen();    
   

  
   double totalprofit=TotalProfit();
   
    
    return (0);
}/* End of Program Loop */

void CloseAllOrders()
{
    int ticket = 0;
    
    while(OrdersTotal() > 0)
    {
     OrderSelect(0,SELECT_BY_POS);
     if(OrderType() == OP_BUY) 
      {
       ticket = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),999,Yellow);
      }
     if(OrderType() == OP_SELL) 
      {
       ticket = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),999,Yellow);
      }
     if((OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP || OrderType() == OP_BUYLIMIT || OrderType() == OP_SELLLIMIT)) 
      {
       ticket = OrderDelete(OrderTicket());
      }
    }
    return(0);
   }

double TotalProfit()
{
   double profit=0;
   
   for (int l_pos_4 = 0; l_pos_4 < OrdersTotal(); l_pos_4++) 
   {
      if (OrderSelect(l_pos_4, SELECT_BY_POS, MODE_TRADES))
         if (OrderMagicNumber() == OrderMagic && OrderSymbol() == Symbol())
         {
            profit=profit+OrderProfit()+OrderCommission()+OrderSwap();
         }
   }
   
   return(profit);  

}



int CalculateCurrentOrders() 
{
   int li_ret_0;
   for (int l_pos_4 = 0; l_pos_4 < OrdersTotal(); l_pos_4++) 
   {
      if (OrderSelect(l_pos_4, SELECT_BY_POS, MODE_TRADES))
         if (OrderMagicNumber() == OrderMagic && OrderSymbol() == Symbol()) li_ret_0++;
   }
   return (li_ret_0);
}

int TrueOpen() 
{
   if (!IsTradeTime(TimeCurrent())) return (0);
   int sgn = TradeSignalOpenOrder();
   xsgn=sgn ;
   if (sgn == 0) return (0);
   double lotsCalc = CalcLotsVolume();
   if (lotsCalc == 0.0 || !CheckAccount(DirectionOrderType(sgn), lotsCalc)) return (0);

Print(" TrueOpen() " + 
      " sgn ="+ sgn +
      " lotsCalc="+DoubleToStr(lotsCalc,2)+
      " CheckAccount(DirectionOrderType(sgn), lotsCalc)="+CheckAccount(DirectionOrderType(sgn), lotsCalc) );
   
   int placeOrder = OpenOrder(sgn, lotsCalc);
   
   return (0);
}

bool CheckParams() 
{
   if (Bars < 100) 
   {
      Print("Bars less than 100");
      return (FALSE);
   }
   if (TakeProfit < 1) 
   {
      Print("TakeProfit is less than 1");
      return (FALSE);
   }
   if (Lots == 0.0 && LotsRiskReductor < 1.0) 
   {
      Print("LotsRiskReductor is less than 1");
      return (FALSE);
   }
   return (TRUE);
}

bool CheckAccount(int a_cmd_0, double ad_4) 
{
   bool li_ret_12 = TRUE;
   double ld_unused_16 = AccountFreeMarginCheck(Symbol(), a_cmd_0, ad_4);
   if (GetLastError() == 134/* NOT_ENOUGH_MONEY */) li_ret_12 = FALSE;
   if (!li_ret_12) Print("No money to open more orders.", " Lot=", ad_4, " Free Margin = ", AccountFreeMargin(), " Balance = ", AccountBalance());
   return (li_ret_12);
}

double CalcLotsVolume() 
{
   double ld_ret_0;
   double l_maxlot_8;
   double l_minlot_16;
   double l_lotstep_24;
   if (Lots > 0.0) ld_ret_0 = NormalizeLot(Lots, 0, "");
   else 
   {
      l_maxlot_8 = MarketInfo(Symbol(), MODE_MAXLOT);
      l_minlot_16 = MarketInfo(Symbol(), MODE_MINLOT);
      l_lotstep_24 = MarketInfo(Symbol(), MODE_LOTSTEP);
      ld_ret_0 = NormalizeDouble(MathFloor(AccountFreeMargin() * LotsRiskReductor / 100.0 / (MarketInfo(Symbol(), MODE_MARGINREQUIRED) * l_lotstep_24)) * l_lotstep_24, 2);
      if (ld_ret_0 < l_minlot_16) ld_ret_0 = l_minlot_16;
      if (ld_ret_0 > l_maxlot_8) ld_ret_0 = l_maxlot_8;
   }
   if (ld_ret_0 > MaxLots) ld_ret_0 = MaxLots;
   return (ld_ret_0);
}

bool PrepareIndicators() 
{
   
   //ArrayCopyRates(Day_Price,(Symbol()), 1440);
//   ArrayCopyRates(Day_Price,Symbol(), 1440);
//   YesterdayHigh  = Day_Price[1][3];
//   YesterdayLow   = Day_Price[1][2];
//   YesterdayClose = Day_Price[1][4];

   YesterdayHigh  = iHigh(Symbol(),PERIOD_D1,1);
   YesterdayLow   = iLow(Symbol(),PERIOD_D1,1);
   YesterdayClose = iClose(Symbol(),PERIOD_D1,1);

   Pivot = ((YesterdayHigh + YesterdayLow + YesterdayClose)/3);
   /*R1 = (2*Pivot)-YesterdayLow;
   S1 = (2*Pivot)-YesterdayHigh;
   R2 = Pivot+(R1-S1);
   S2 = Pivot-(R1-S1); 
   R3 = (YesterdayHigh + (2*(Pivot-YesterdayLow)));
   S3 = (YesterdayLow - (2*(YesterdayHigh-Pivot)));
   
has 6 elements:
0 - time,
1 - open,
2 - low,
3 - high,
4 - close,
5 - volume.
   */
   
//   ArrayCopyRates(Weekly_Price, Symbol(), 10080);

//   WeekHigh  = Weekly_Price[1][3];
//   WeekLow   = Weekly_Price[1][2];
//   WeekClose = Weekly_Price[1][4];

   WeekHigh  = iHigh(Symbol(),PERIOD_W1,1);
   WeekLow   = iLow(Symbol(),PERIOD_W1,1);
   WeekClose = iClose(Symbol(),PERIOD_W1,1);
   WeekPivot = ((WeekHigh + WeekLow + WeekClose)/3);

//   ArrayCopyRates(Month_Price, Symbol(), 43200);

//   MonthHigh  = Month_Price[1][3];
//   MonthLow   = Month_Price[1][2];
//   MonthClose = Month_Price[1][4];

   MonthHigh  = iHigh(Symbol(),PERIOD_MN1,1);
   MonthLow   = iLow(Symbol(),PERIOD_MN1,1);
   MonthClose = iClose(Symbol(),PERIOD_MN1,1);
   
   MonthPivot = ((MonthHigh + MonthLow + MonthClose)/3);
   MR1 = (2*MonthPivot)-MonthLow;
   MS1 = (2*MonthPivot)-MonthHigh;
//nnnrsi      
   RSI = iRSI(NULL, FilterCTF, FilterCPeriod, 0, 0);

   double nfractal;
   aligator0 = iCustom(NULL, 0, "Alligator", 13, 8, 8, 5, 5, 3, 0, 0);
//   if (IsError("Alligator Jaw")) return (FALSE);
   aligator1 = iCustom(NULL, 0, "Alligator", 13, 8, 8, 5, 5, 3, 1, 0);
//   if (IsError("Alligator Teeth")) return (FALSE);
   aligator2 = iCustom(NULL, 0, "Alligator", 13, 8, 8, 5, 5, 3, 2, 0);
//   if (IsError("Alligator Lips")) return (FALSE);
   int li_8 = 3;
   fractalLow = 0;
   fractalUp = 0;
   for (int li_4 = 0; li_4 <= li_8; li_4++) 
   {
      nfractal = iFractals(NULL, 0, MODE_LOWER, li_4);
//      if (IsError("Lower Fractals")) return (FALSE);
      if (nfractal != 0.0) fractalLow = nfractal;
      nfractal = iFractals(NULL, 0, MODE_UPPER, li_4);
//      if (IsError("Upper Fractals")) return (FALSE);
      if (nfractal != 0.0) fractalUp = nfractal;
   }
   int z = 10;
   ArrayResize(deMarker, z + 1);
   ArrayResize(wpr, z + 1);
   for (li_4 = 0; li_4 <= z; li_4++) 
   {
      deMarker[li_4] = iDeMarker(NULL, ChartDeM, FilterAPeriod, li_4);
 //     if (IsError("DeMarker")) return (FALSE);
      wpr[li_4] = (-iWPR(NULL, ChartWPR, FilterBPeriod, li_4 + 1)) / 100.0;
 //     if (IsError("WPR")) return (FALSE);
   }
idm=iDeMarker(NULL, ChartDeM, FilterAPeriod, 1);
iwpr=(-iWPR(NULL, ChartWPR, FilterBPeriod, 1)) / 100.0;
   if (UseMAControl != False) 
   {
      ma1 = iMA(NULL, ChartMa, PeriodMA, 0, TypeMA_0_3, PriceMA_0_6, 1);
      ma0 = iMA(NULL, ChartMa, PeriodMA, 0, TypeMA_0_3, PriceMA_0_6, 0);
   }
   return (TRUE);
}



int TradeSignalOpenOrder() 
{  



   if (UseMAControl == True) 
     {  
       MAGator();
       if (!MAGator()) return(0);
     }
   else
   {if (!IsGatorActiveUp()) return (0);}
           
   if (UseFilterB)
     {if (WasWPROverBuy() || WasWPROverSell()) return (0);}
  
  if (UseFilterC == True) RSIFilter();
  else 
     {
      RSILong = True;     
      RSIShort = True;
     }

   if (IsFractalLower() && WasDemarkerHigh() && RSILong) 
     {
     return(1);
     }
     
   if (IsFractalUpper() && WasDemarkerLow() && RSIShort)
     {
       return(-1);
     }
     
   return (0);
}

int TradeSignalCloseOrder() 
{
   return (!IsOrderProfitable());
}

double NormalizeLot(double ad_0, bool ai_8 = FALSE, string a_symbol_12 = "") 
{
   double ld_ret_20;
   double ld_28;
   if (a_symbol_12 == "" || a_symbol_12 == "0") a_symbol_12 = Symbol();
   double l_lotstep_36 = MarketInfo(a_symbol_12, MODE_LOTSTEP);
   double l_minlot_44 = MarketInfo(a_symbol_12, MODE_MINLOT);
   double l_maxlot_52 = MarketInfo(a_symbol_12, MODE_MAXLOT);
   if (l_minlot_44 == 0.0) l_minlot_44 = 0.1;
   if (l_maxlot_52 == 0.0) l_maxlot_52 = 100;
   if (l_lotstep_36 > 0.0) ld_28 = 1 / l_lotstep_36;
   else ld_28 = 1 / l_minlot_44;
   if (ai_8) ld_ret_20 = MathCeil(ad_0 * ld_28) / ld_28;
   else ld_ret_20 = MathFloor(ad_0 * ld_28) / ld_28;
   if (ld_ret_20 < l_minlot_44) ld_ret_20 = l_minlot_44;
   if (ld_ret_20 > l_maxlot_52) ld_ret_20 = l_maxlot_52;
   return (ld_ret_20);
}

int ModifyOrder() 
{
   int dir = OrderTypeDirection();
   Print("TakeProfit value is not set due to server connection error. Please modify the order and set it manually");
   double mpp=Point;
   if(Digits==3||Digits==5) mpp=Point*10;
   double mtp = g_str2dbl_244 + TakeProfit * mpp * dir;
   mtp=NormalizeDouble(mtp,Digits);
   
   OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), mtp, OrderExpiration(), Red);
   return (0);
}

int TradeSignalCloseOrderOnTime(int ai_unused_0) 
{
   if (CloseEndMonth == True)
   {
   if (TimeMonth(OrderOpenTime()) != TimeMonth(TimeCurrent())) return (1);
   else return (0);
   }
   return (0);
}

bool IsDateTimeEnabled(int ai_0) 
{
   int day_of_year = TimeDayOfYear(ai_0);
   int day_of_week = TimeDayOfWeek(ai_0);
   return ( day_of_week > DoWStart && 
            day_of_week < DoWEnd && 
            day_of_year > DoYStart && 
            day_of_year < DoYEnd);
}

bool MAGator()
{
    if (ma1 < ma0) 
         {
            if (!IsGatorActiveUp()) return (0);
         } 
            else 
            {
               if (ma1 > ma0) 
               {
                  if (!IsGatorActiveDown()) return (0);
               } 
                  else
                     if (!IsGatorActiveUp() && !IsGatorActiveDown()) return (0);
            } 
    return(1);
}


bool RSIFilter()
{
   RSILong = False;     
   RSIShort = False;
   if(RSI > RSIHigh) RSILong = True;
   if(RSI < RSILow) RSIShort = True;
   return;
}

bool IsGatorActiveUp() 
{
   return (aligator2 - aligator1 >= SpanGator * dblPoints && aligator1 - aligator0 >= SpanGator * dblPoints && aligator2 - aligator0 >= SpanGator * dblPoints);
}

bool IsGatorActiveDown() 
{
   return (aligator1 - aligator2 >= SpanGator * dblPoints && aligator0 - aligator1 >= SpanGator * dblPoints && aligator0 - aligator2 >= SpanGator * dblPoints);
}

int IsFractalLower() 
{
   return (fractalLow != 0.0);
}

int IsFractalUpper() 
{
   return (fractalUp != 0.0);
}

bool IsOrderProfitable() 
{
   return (TRUE);
}

int WasDemarkerLow() 
{
  if (UseFilterA)
    //{return (ArrayMinValue(deMarker) < DeMLow);}
    {return (idm < DeMLow);}
  else
    {return(1);}
}

int WasDemarkerHigh() 
{
    if (UseFilterA)
    //{return (ArrayMaxValue(deMarker) > DeMHigh);}
    {return (idm > DeMHigh);}
  else
    {return(1);}
}

int WasWPROverBuy() 
{
   //return (ArrayMinValue(wpr) <= WPRBuy);
   return (iwpr <= WPRBuy);
}

int WasWPROverSell() 
{
   //return (ArrayMaxValue(wpr) >= WPRSell);
   return (iwpr >= WPRSell);
}

int OpenOrder(int dir, double lot, string nComment = "") 
{  double nspread=Ask-Bid;
   int lawPrice;
   double xSL = 0;
   double xTP = 0;
   double xOP = NormalizeDouble(PriceOpen(dir),Digits);
   
   xTP = NormalizeDouble(xOP + TakeProfit * dblPoints * dir,Digits);
   
   if (StopLoss > 0.0) 
      xSL = NormalizeDouble(PriceClose(dir) - StopLoss * dblPoints * dir,Digits);
   else xSL = 0;
   
   Print("dir="+DirectionOrderType(dir)+
               " lots="+DoubleToStr(lot,2)+
               " prc="+DoubleToStr(xOP,Digits) );
               
   int nTicket = OrderSend(Symbol(), DirectionOrderType(dir), lot, xOP, 
         SlipPage, 0, 0, nComment, OrderMagic, 0, ColorOpen(dir));
         Print("dir="+DirectionOrderType(dir)+
               " lots="+DoubleToStr(lot,2)+
               " prc="+DoubleToStr(xOP,Digits) );
         
   Sleep(1000);
   if (nTicket > 0) 
   {  Print(" modify -->  ticket="+ nTicket+
            " SL="+DoubleToStr(xSL,Digits)+
            " TP="+DoubleToStr(xTP,Digits)+
            " prc="+DoubleToStr(xOP,Digits) );
   
   
      lawPrice = MarketInfo(Symbol(), MODE_STOPLEVEL);
//  ????      
      //if ( (TakeProfit > lawPrice || TakeProfit == 0.0) || (StopLoss > lawPrice || StopLoss == 0.0) )
      if (TakeProfit > lawPrice || TakeProfit == 0.0)
         if (StopLoss > lawPrice || StopLoss == 0.0) 
            OrderModify(nTicket, xOP, xSL, xTP, 0, Red);
   }
   
   if(Hedger==true)
   {  double pp=Point;
      if(Digits==3||Digits==5)  pp=Point*10;
      int ticket1;
      double tp,sl;
      double mylots;
      mylots=NormalizeLot(lot*Hedger_LotMultiplier, 0, "");
      if(mylots>MaxLots) mylots=MaxLots;
      
      if(DirectionOrderType(dir)==0)
      //if(DirectionOrderType(dir)==1)
      {  
      
         Print("Hedger dir="+DirectionOrderType(dir)+
               " lots="+DoubleToStr(mylots,2)+
               " prc="+DoubleToStr(xOP-(Hedger_PipsAway * pp),Digits) );
         datetime x1= TimeCurrent()+(60*Hedger_ExpiredMinutes);
         ticket1=OrderSend(Symbol(), OP_SELLSTOP, mylots, 
                     NormalizeDouble(xOP-(Hedger_PipsAway * pp),Digits), //-nspread,Digits), 
                     SlipPage, 0, 0, "Hedger", OrderMagic, 
                     x1, //TimeCurrent()+(60*Hedger_ExpiredMinutes), 
                     ColorOpen(1));
                     
         if (ticket1 > 0) 
         {
            lawPrice = MarketInfo(Symbol(), MODE_STOPLEVEL);
            if (TakeProfit > lawPrice || TakeProfit == 0.0)
               if (StopLoss > lawPrice || StopLoss == 0.0) 
               {
                  //Print(TimeToStr(OrderExpiration(),TIME_DATE|TIME_MINUTES));
                  if(TakeProfit==0) tp=0;
                  
                  if(TakeProfit>0) tp=xOP-(Hedger_PipsAway * pp)-(TakeProfit * pp);
                  if(StopLoss==0) sl=0;
                  if(StopLoss>0) sl=xOP-(Hedger_PipsAway * pp)+(StopLoss * pp);
                  OrderModify(ticket1, OrderOpenPrice(),
                  //xOP-(Hedger_PipsAway * pp), 
                  sl, tp, 
                  x1, Red);
                  //OrderExpiration(), Red);
                  //Print(TimeToStr(OrderExpiration(),TIME_DATE|TIME_MINUTES));
               }
         }
      }   
      if(DirectionOrderType(dir)==1)
      //if(DirectionOrderType(dir)==0)
      {  
         Print("Hedger dir="+DirectionOrderType(dir)+
               " lots="+DoubleToStr(mylots,2)+
               " prc="+DoubleToStr(xOP+(Hedger_PipsAway * pp)+nspread,Digits) );
        datetime x2= TimeCurrent()+(60*Hedger_ExpiredMinutes);
         ticket1=OrderSend(Symbol(), OP_BUYSTOP, mylots, 
                  NormalizeDouble(xOP+(Hedger_PipsAway * pp)+nspread,Digits), 
                                    SlipPage, 
                  //NormalizeDouble(xOP-(100 * pp),Digits), 
                  0,
                  0, "Hedger", OrderMagic,
                  x2, //TimeCurrent()+(60*Hedger_ExpiredMinutes), 
                  ColorOpen(0));
         if (ticket1 > 0) 
         {
            lawPrice = MarketInfo(Symbol(), MODE_STOPLEVEL);
            if (TakeProfit > lawPrice || TakeProfit == 0.0)
               if (StopLoss > lawPrice || StopLoss == 0.0) 
               {  //Print(TimeToStr(OrderExpiration(),TIME_DATE|TIME_MINUTES));
                  if(TakeProfit==0) tp=0;
                  if(TakeProfit>0) tp=xOP+(Hedger_PipsAway * pp)+(TakeProfit * pp);
                  if(StopLoss==0) sl=0;
                  if(StopLoss>0) sl=xOP+(Hedger_PipsAway * pp)-(StopLoss * pp);
                  OrderModify(ticket1, OrderOpenPrice(),
                  //xOP+(Hedger_PipsAway * pp),
                   sl, tp, 
                  x2, //OrderExpiration(), 
                  Red);
                 // Print(TimeToStr(OrderExpiration(),TIME_DATE|TIME_MINUTES));
               }
         }
      }   
   }
   
   g_datetime_300 = iTime(Symbol(), 0, 0);
   return (0);
}

void CloseOrder() 
{
int Ticket = OrderTicket();
switch(OrderType())
   {
   case 0: double Price_Cls = Bid;
      string Text = "Buy";
      break;
   case 1: 
      Price_Cls = Ask;
      Text = "Sell";
   }   
 while(true)
   {
      Print("Attempt to close ",Text," ",Ticket,". Awaiting response..\n");
      bool Ans=OrderClose(OrderTicket(), OrderLots(), Price_Cls, SlipPage, Red);
      if (Ans == true)
         {
         Print("Closed order ",Text," ",Ticket,"\n");
         break;
         }
      int Error = GetLastError();
      switch(Error)
      {
      case 135: Alert("The price has changed. Retrying..");
         RefreshRates();
         continue;
      case 136: Alert("No prices. Waiting for a new tick..");
         while(RefreshRates() == false)
          Sleep(1);
         continue;
      case 146: Alert("Trading subsystem is busy. Retrying..");
         Sleep(500);
         RefreshRates();
         continue;
      }
      switch(Error)
      {
      case 2: Alert("Common error.");
         break;
      case 5: Alert("Old version of the client terminal.");
         break;
      case 64: Alert("Account is blocked.");
         break;
      case 133: Alert("Trading is prohibited!");
         break;
      default: Alert("Occured error: ",Error);
      }
   break;
   }
   return;
}

bool GetOrderByPos(int a_pos_0) 
{
   return (OrderSelect(a_pos_0, SELECT_BY_POS, MODE_TRADES) && OrderType() <= OP_SELL && OrderSymbol() == Symbol());
}

void TrailOrderStop(int step) 
{
   int sgn;
   double ld_4;
   double ld_12;
   double l_price_20;
   double ld_28;
   double ld_36;
   int li_44;
   int ld_4x;
   double l_price_20x;
   if (OrderTicket() > 0 && StringFind(OrderComment(),"Hedger")==-1) 
   {
      sgn = OrderTypeDirection();
      ld_4 = NormalizeDouble(TrailingStop * dblPoints * sgn, Digits);
      ld_4x = NormalizeDouble((TrailingStop+TrailingStep) * dblPoints * sgn, Digits);
      
      ld_12 = NormalizeDouble(iif(sgn > 0 || OrderStopLoss() != 0.0, OrderStopLoss(), C'0x3F,0x42,0x0F'), Digits);
      
      l_price_20 = NormalizeDouble(PriceClose(sgn) - ld_4, Digits);
      l_price_20x = NormalizeDouble(PriceClose(sgn) - (ld_4+ld_4x), Digits);
      
      ld_28 = NormalizeDouble(l_price_20 - OrderOpenPrice(), Digits);
      
      ld_36 = NormalizeDouble(l_price_20x - ld_12, Digits);
      
      if (ld_28 * sgn > 0.0 && ld_36 * sgn >= dblPoints) 
      {
         if (OrderType() == OP_BUY)
         {
          li_44 = (Bid - l_price_20) / dblPoints;
          string Text = "Buy";
         }
         else 
         {
          li_44 = (l_price_20 - Ask) / dblPoints;
          Text = "Sell";
         }
         if (li_44 > MarketInfo(Symbol(), MODE_STOPLEVEL)) 
         {
          while(true)
          {
            Print("Modification ",Text," ",OrderTicket(),". Awaiting response..\n");
            bool Ans=OrderModify(OrderTicket(), OrderOpenPrice(), l_price_20x, OrderTakeProfit(), 0, ColorOpen(sgn));
            if (Ans == true)
            {
            Print("Order ",Text," ",OrderTicket()," is modified.\n");
            break;
            }
            int Error = GetLastError();
            switch(Error)
            {
            case 130: Alert("Wrong stops. Retrying..");
               RefreshRates();
               continue;
            case 136: Alert("No prices. Waiting for a new tick..");
               while(RefreshRates() == false)
                  Sleep(1);
               continue;
            case 146: Alert("Trading subsytem is busy. Retrying..");
               Sleep(500);
               RefreshRates();
               continue;
            case 2: Alert("Common error.");
               break;
            case 5: Alert("Old version of the client terminal.");
               break;
            case 64: Alert("Account is block.");
               break;
            case 133: Alert("Trading is prohibited.");
               break;
            default: Alert("Occurred error: ",Error);
            }
          break;
          }
            
         }
      }
   }
   return;
}

void Hedger_TrailOrderStop(int step) 
{
   int sgn;
   double ld_4;
   double ld_12;
   double l_price_20;
   double ld_28;
   double ld_36;
   int li_44;
   int ld_4x;
   double l_price_20x;
   if (OrderTicket() > 0 && StringFind(OrderComment(),"Hedger")!=-1) 
   {
      sgn = OrderTypeDirection();
      ld_4 = NormalizeDouble(TrailingStop * dblPoints * sgn, Digits);
      ld_4x = NormalizeDouble((TrailingStop+TrailingStep) * dblPoints * sgn, Digits);
      
      ld_12 = NormalizeDouble(iif(sgn > 0 || OrderStopLoss() != 0.0, OrderStopLoss(), C'0x3F,0x42,0x0F'), Digits);
      
      l_price_20 = NormalizeDouble(PriceClose(sgn) - ld_4, Digits);
      l_price_20x = NormalizeDouble(PriceClose(sgn) - (ld_4+ld_4x), Digits);
      
      ld_28 = NormalizeDouble(l_price_20 - OrderOpenPrice(), Digits);
      
      ld_36 = NormalizeDouble(l_price_20x - ld_12, Digits);
      
      if (ld_28 * sgn > 0.0 && ld_36 * sgn >= dblPoints) 
      {
         if (OrderType() == OP_BUY)
         {
          li_44 = (Bid - l_price_20) / dblPoints;
          string Text = "Buy";
         }
         else 
         {
          li_44 = (l_price_20 - Ask) / dblPoints;
          Text = "Sell";
         }
         if (li_44 > MarketInfo(Symbol(), MODE_STOPLEVEL)) 
         {
          while(true)
          {
            Print("Modification ",Text," ",OrderTicket(),". Awaiting response..\n");
            bool Ans=OrderModify(OrderTicket(), OrderOpenPrice(), l_price_20x, OrderTakeProfit(), 0, ColorOpen(sgn));
            if (Ans == true)
            {
            Print("Order ",Text," ",OrderTicket()," is modified.\n");
            break;
            }
            int Error = GetLastError();
            switch(Error)
            {
            case 130: Alert("Wrong stops. Retrying..");
               RefreshRates();
               continue;
            case 136: Alert("No prices. Waiting for a new tick..");
               while(RefreshRates() == false)
                  Sleep(1);
               continue;
            case 146: Alert("Trading subsytem is busy. Retrying..");
               Sleep(500);
               RefreshRates();
               continue;
            case 2: Alert("Common error.");
               break;
            case 5: Alert("Old version of the client terminal.");
               break;
            case 64: Alert("Account is block.");
               break;
            case 133: Alert("Trading is prohibited.");
               break;
            default: Alert("Occurred error: ",Error);
            }
          break;
          }
            
         }
      }
   }
   return;
}

int OrderTypeDirection() 
{
   int li_ret_0 = 0;
   if (OrderType() == OP_BUY) li_ret_0 = 1;
   if (OrderType() == OP_SELL) li_ret_0 = -1;
   return (li_ret_0);
}

int DirectionOrderType(int dir) 
{
   return (iif(dir > 0, 0, 1));
}

int ColorOpen(int dir) 
{
   return (iif(dir > 0, 32768, 255));
}

double PriceOpen(int dir) 
{
   return (iif(dir > 0, Ask, Bid));
}

double PriceClose(int dir) 
{
   return (iif(dir > 0, Bid, Ask));
}

double iif(bool a, double b, double c) 
{
   if (a) return (b);
   return (c);
}
/*
bool IsError(string as_0 = "Raptor V1") 
{
   int l_error_8 = GetLastError();
   bool li_ret_12 = l_error_8 > 1; // NO_RESULT 
   if (li_ret_12) Print(as_0, " error = ", l_error_8, "; desc = ", ErrorDescription(l_error_8));
   return (li_ret_12);
}

string ErrorDescription(int ai_0) 
{
   string ls_ret_4;
   switch (ai_0) 
   {
      case 0:
      case 1:
         ls_ret_4 = "no error";
         break;
      case 2:
         ls_ret_4 = "common error";
         break;
      case 3:
         ls_ret_4 = "invalid trade parameters";
         break;
      case 4:
         ls_ret_4 = "trade server is busy";
         break;
      case 5:
         ls_ret_4 = "old version of the client terminal";
         break;
      case 6:
         ls_ret_4 = "no connection with trade server";
         break;
      case 7:
         ls_ret_4 = "not enough rights";
         break;
      case 8:
         ls_ret_4 = "too frequent requests";
         break;
      case 9:
         ls_ret_4 = "malfunctional trade operation (never returned error)";
         break;
      case 64:
         ls_ret_4 = "account disabled";
         break;
      case 65:
         ls_ret_4 = "invalid account";
         break;
      case 128:
         ls_ret_4 = "trade timeout";
         break;
      case 129:
         ls_ret_4 = "invalid price";
         break;
      case 130:
         ls_ret_4 = "invalid stops";
         break;
      case 131:
         ls_ret_4 = "invalid trade volume";
         break;
      case 132:
         ls_ret_4 = "market is closed";
         break;
      case 133:
         ls_ret_4 = "trade is disabled";
         break;
      case 134:
         ls_ret_4 = "not enough money";
         break;
      case 135:
         ls_ret_4 = "price changed";
         break;
      case 136:
         ls_ret_4 = "off quotes";
         break;
      case 137:
         ls_ret_4 = "broker is busy (never returned error)";
         break;
      case 138:
         ls_ret_4 = "requote";
         break;
      case 139:
         ls_ret_4 = "order is locked";
         break;
      case 140:
         ls_ret_4 = "long positions only allowed";
         break;
      case 141:
         ls_ret_4 = "too many requests";
         break;
      case 145:
         ls_ret_4 = "modification denied because order too close to market";
         break;
      case 146:
         ls_ret_4 = "trade context is busy";
         break;
      case 147:
         ls_ret_4 = "expirations are denied by broker";
         break;
      case 148:
         ls_ret_4 = "amount of open and pending orders has reached the limit";
         break;
      case 4000:
         ls_ret_4 = "no error (never generated code)";
         break;
      case 4001:
         ls_ret_4 = "wrong function pointer";
         break;
      case 4002:
         ls_ret_4 = "array index is out of range";
         break;
      case 4003:
         ls_ret_4 = "no memory for function call stack";
         break;
      case 4004:
         ls_ret_4 = "recursive stack overflow";
         break;
      case 4005:
         ls_ret_4 = "not enough stack for parameter";
         break;
      case 4006:
         ls_ret_4 = "no memory for parameter string";
         break;
      case 4007:
         ls_ret_4 = "no memory for temp string";
         break;
      case 4008:
         ls_ret_4 = "not initialized string";
         break;
      case 4009:
         ls_ret_4 = "not initialized string in array";
         break;
      case 4010:
         ls_ret_4 = "no memory for array\' string";
         break;
      case 4011:
         ls_ret_4 = "too long string";
         break;
      case 4012:
         ls_ret_4 = "remainder from zero divide";
         break;
      case 4013:
         ls_ret_4 = "zero divide";
         break;
      case 4014:
         ls_ret_4 = "unknown command";
         break;
      case 4015:
         ls_ret_4 = "wrong jump (never generated error)";
         break;
      case 4016:
         ls_ret_4 = "not initialized array";
         break;
      case 4017:
         ls_ret_4 = "dll calls are not allowed";
         break;
      case 4018:
         ls_ret_4 = "cannot load library";
         break;
      case 4019:
         ls_ret_4 = "cannot call function";
         break;
      case 4020:
         ls_ret_4 = "expert function calls are not allowed";
         break;
      case 4021:
         ls_ret_4 = "not enough memory for temp string returned from function";
         break;
      case 4022:
         ls_ret_4 = "system is busy (never generated error)";
         break;
      case 4050:
         ls_ret_4 = "invalid function parameters count";
         break;
      case 4051:
         ls_ret_4 = "invalid function parameter value";
         break;
      case 4052:
         ls_ret_4 = "string function internal error";
         break;
      case 4053:
         ls_ret_4 = "some array error";
         break;
      case 4054:
         ls_ret_4 = "incorrect series array using";
         break;
      case 4055:
         ls_ret_4 = "custom indicator error";
         break;
      case 4056:
         ls_ret_4 = "arrays are incompatible";
         break;
      case 4057:
         ls_ret_4 = "global variables processing error";
         break;
      case 4058:
         ls_ret_4 = "global variable not found";
         break;
      case 4059:
         ls_ret_4 = "function is not allowed in testing mode";
         break;
      case 4060:
         ls_ret_4 = "function is not confirmed";
         break;
      case 4061:
         ls_ret_4 = "send mail error";
         break;
      case 4062:
         ls_ret_4 = "string parameter expected";
         break;
      case 4063:
         ls_ret_4 = "integer parameter expected";
         break;
      case 4064:
         ls_ret_4 = "double parameter expected";
         break;
      case 4065:
         ls_ret_4 = "array as parameter expected";
         break;
      case 4066:
         ls_ret_4 = "requested history data in update state";
         break;
      case 4099:
         ls_ret_4 = "end of file";
         break;
      case 4100:
         ls_ret_4 = "some file error";
         break;
      case 4101:
         ls_ret_4 = "wrong file name";
         break;
      case 4102:
         ls_ret_4 = "too many opened files";
         break;
      case 4103:
         ls_ret_4 = "cannot open file";
         break;
      case 4104:
         ls_ret_4 = "incompatible access to a file";
         break;
      case 4105:
         ls_ret_4 = "no order selected";
         break;
      case 4106:
         ls_ret_4 = "unknown symbol";
         break;
      case 4107:
         ls_ret_4 = "invalid price parameter for trade function";
         break;
      case 4108:
         ls_ret_4 = "invalid ticket";
         break;
      case 4109:
         ls_ret_4 = "trade is not allowed in the expert properties";
         break;
      case 4110:
         ls_ret_4 = "longs are not allowed in the expert properties";
         break;
      case 4111:
         ls_ret_4 = "shorts are not allowed in the expert properties";
         break;
      case 4200:
         ls_ret_4 = "object is already exist";
         break;
      case 4201:
         ls_ret_4 = "unknown object property";
         break;
      case 4202:
         ls_ret_4 = "object is not exist";
         break;
      case 4203:
         ls_ret_4 = "unknown object type";
         break;
      case 4204:
         ls_ret_4 = "no object name";
         break;
      case 4205:
         ls_ret_4 = "object coordinates error";
         break;
      case 4206:
         ls_ret_4 = "no specified subwindow";
         break;
      default:
      ls_ret_4 = "unknown error";
   }
   return (ls_ret_4);
}

double ArrayMinValue(double ada_0[]) 
{
   return (ada_0[ArrayMinimum(ada_0)]);
}

double ArrayMaxValue(double ada_0[]) 
{
   return (ada_0[ArrayMaximum(ada_0)]);
}
*/
double GetPoints()
{
   if (Digits == 3 || Digits == 5) dblPoints = Point * 10;
   else dblPoints = Point;
   return(dblPoints);
}

bool IsTradeTime(int ai_0) 
{
   int li_12;
   int li_16;
   int l_hour_4 = TimeHour(ai_0);
   int l_minute_8 = TimeMinute(ai_0);
   if (StartWorkTimeHour == EndWorkTimeHour && StartWorkTimeMin == EndWorkTimeMin) return (TRUE);
   if (EndWorkTimeMin == 0) 
   {
      if (EndWorkTimeHour == 0) li_12 = 23;
      else li_12 = EndWorkTimeHour - 1;
      li_16 = 59;
   } 
      else 
      {
         li_12 = EndWorkTimeHour;
         li_16 = EndWorkTimeMin - 1;
      }
   if (StartWorkTimeHour == li_12) 
   {
      if (StartWorkTimeMin == li_16) return (TRUE);
      if (StartWorkTimeMin < li_16) 
      {
         if (l_hour_4 != StartWorkTimeHour) return (FALSE);
         if (l_minute_8 < StartWorkTimeMin || l_minute_8 > li_16) return (FALSE);
         return (TRUE);
      }
      if (StartWorkTimeMin > li_16) 
      {
         if (l_hour_4 == StartWorkTimeHour)
            if (l_minute_8 < StartWorkTimeMin && l_minute_8 > li_16) return (FALSE);
         return (TRUE);
      }
   }
   if (StartWorkTimeHour < li_12) 
   {
      if (l_hour_4 < StartWorkTimeHour || l_hour_4 > li_12) return (FALSE);
      if (l_hour_4 == StartWorkTimeHour && l_minute_8 < StartWorkTimeMin) return (FALSE);
      if (l_hour_4 == li_12 && l_minute_8 > li_16) return (FALSE);
      return (TRUE);
   }
   if (StartWorkTimeHour > li_12) 
   {
      if (l_hour_4 < StartWorkTimeHour && l_hour_4 > li_12) return (FALSE);
      if (l_hour_4 == StartWorkTimeHour && l_minute_8 < StartWorkTimeMin) return (FALSE);
      if (l_hour_4 == li_12 && l_minute_8 > li_16) return (FALSE);
      return (TRUE);
   }
   return (TRUE);
}


int jmlOrder()
{
  int gantung;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() == Symbol()  && OrderCloseTime()==0) 
      {  if(OrderType()==OP_BUY || OrderType()==OP_SELL )
            { if(OrderMagicNumber()==OrderMagic  ) 
                  gantung++;
            }
      }
   }
 return(gantung);
 }

int jmlOrderStop()
{
  int gantung;
  for (int cnt = OrdersTotal()-1 ; cnt >= 0; cnt--) 
   { 
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); 
      if (OrderSymbol() == Symbol()  && OrderCloseTime()==0) 
      {  if(OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP ||OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT)
            { if(OrderMagicNumber()==OrderMagic  ) 
                  gantung++;
            }
      }
   }
 return(gantung);
 }

 //-----------------------------------------------


void cleanPendingOrders()
{   int ticket = 0;
    
    while(OrdersTotal() > 0)
    {
     OrderSelect(0,SELECT_BY_POS);
     
     if((OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP || OrderType() == OP_BUYLIMIT || OrderType() == OP_SELLLIMIT)) 
      {
       ticket = OrderDelete(OrderTicket());
      }
    }
    return(0);
   }