#property copyright   "http://www.forexfactory.com/remon78eg"
#property link        "the_programmer_eg@yahoo.com" 
#property description " "
#property description "Accumulative Profits Grid (Version 3.00 Of, Forex 100% No-Loss Strategy)"
#property description " "
#property description "Copyright 23/03/2016"
#property description "Remon Reffat , remon78eg"
#property description "the_programmer_eg@yahoo.com"
#property description " http://www.forexfactory.com/showthread.php?t=583322"
#property strict

//#include "mq4_to_mq5.mqh"
#include "AGP.MQH"

const string PATH="::Experts\\remon78eg APG M1&M2+NoHedge\\";//search PeachPuff for colors list
//#resource "\\Experts\\RemonFMH_MultiCur\\BOLx2-V8 predict.ex4";

//#include <stderror.mqh> 
//xx #include <stdlib.mqh>

#resource "\\Experts\\remon78eg APG M1&M2+NoHedge\\coin.wav";
#resource "\\Experts\\remon78eg APG M1&M2+NoHedge\\chime.wav";
#resource "\\Experts\\remon78eg APG M1&M2+NoHedge\\error.wav";
#resource "\\Experts\\remon78eg APG M1&M2+NoHedge\\Available.wav";
#resource "\\Experts\\remon78eg APG M1&M2+NoHedge\\OUH.WAV";
#resource "\\Experts\\remon78eg APG M1&M2+NoHedge\\alert2.wav";
#resource "\\Experts\\remon78eg APG M1&M2+NoHedge\\timeout.wav";
#property icon "\\Experts\\remon78eg APG M1&M2+NoHedge\\$.ico"

extern string   WorkingDays      ="0,1,2,3,4,5,6";//Working Days (0=Su,1=Mo,2=Tu,3=We,4=Th,5=Fr,6=Sa)
extern string   TimeFrom          ="08:00";
extern string   TimeTo            ="08:00";

extern bool   ChkForHang    =true ;//Play Sound If Hang
extern bool   DEALS_SOUND   =true ;//Play Sound If Deal Open/Close
bool   PAUSE_LEVEL     =false;//Pause Every Level (Tester Only)
bool   PAUSE_PROFIT    =false;//Pause/Stop Every Profit (Tester/Pause & Life/Stop)
extern string ___________5844525="==================================================================================================";//=============================================================================================
extern int    MAGIC         =12345;//Magic
extern enMethod METHOD=Method1;//Method

extern double LevelsDistance=10.0 ;//Levels Distance Pips (1.0 = 0.00010 Or 0.010)
       //string LDISTANCE     ="10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10";//Levels Distance
extern double LOT           =0.01 ;//Lot
//extern bool   chkNoCloseOrLoserFirst      =false;//Loser1
//extern bool   chkNoCloseOrLoserFirst2     =false;//Loser2

extern int    ShareRatioHeart =00;//Heart Share (0% To 100%)
 int    ShareRatioBox   =00;//Box Ratio (0% To 100%) (def 0)
extern double ProfitLevel=5.0;//Profit To Close All ($)
//extern double ProfitAny=0.25;//Profit At Any $
extern bool     OpenPriceOnly=false;//Open Price Only
       string ___________5844526="==================================================================================================";//=============================================================================================
       bool   CalcSpreads                 =false;
       bool   chkSharedOtherProfits       =false;//[O] Shared Other Profits (Buy Profits Close Sell Loss)
       bool   chkCloseAllProfitSharedDeals=false;//[X] if Close Profits, Must Close All Profits Levels
       bool   chkCloseProfitInversed      =false;//[i] Close Min Profits Level First (inverted)
       bool   chkCloseSingleLossLevel     =false;//[L] If Single Loss Levels Found, Close It From Shared $$
       bool   chkCloseSingleWinLevel      =false;//[W] If Single Win Levels Found, Close It


int PriceMethod=2;//M1=bid, M2=(bid+ask)/2

double TimeOffset=(double)(TimeCurrent()-TimeLocal());//for hang detect
//double TicVal=100000/MarketInfo(Symbol(),MODE_LOTSIZE);
double LastEquity=AccountEquity();
bool   MQL4=StringFind(__PATH__,"\\MQL4\\")>=0;//true if MT4 , false in MT5 ,,,__PATH__ ="C:\Users\UserName\AppData\Roaming\MetaQuotes\Terminal\3580176B0D1605D0BC3BE1769B8A34B3 [[   \MQL4\  Or  \MQL5\  ]] Experts\"
double Stop=0.0;
double SPREAD=0.0;
double point_mul=1.0;
double TicVal=100000/MarketInfo(Symbol(),MODE_LOTSIZE);//100 in micro
double StopDays[];//Market Buy Sell

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+

int OnInit(){  
  if(ACCOUNT_TRADE_MODE_DEMO != AccountInfoInteger(ACCOUNT_TRADE_MODE) && !IsTesting()){Comment("Work In Demo Account Only!!","\r\n","Will Exit!!");return(INIT_FAILED);}
  
  if(ShareRatioHeart<0  ){ShareRatioHeart=0  ;}
  if(ShareRatioHeart>100){ShareRatioHeart=100;}
  if(ShareRatioBox  <0  ){ShareRatioBox  =0  ;}
  if(ShareRatioBox  >100){ShareRatioBox  =100;}
  
  DEALS1.ProfitsBoxShareRatio=ShareRatioBox;
  DEALS1.ProfitsHeartShareRatio=ShareRatioHeart;
  
  if(Digits==5 || Digits==3){point_mul=10;}
  
  SPREAD=-MarketInfo(Symbol(),MODE_SPREAD)/point_mul/TicVal/10;//2.0;//val to get 0.20 in LOT///xxxif (spread*LOT) = (real spread 0.20$)
  //SPREAD=-0.20;

  InitDeals_JustStarted(DEALS1,SPREAD);
  
  EventSetMillisecondTimer(100);

  return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
void writeBin(string bin){
   //string file = "Hello-Binary"+NUM(TimeCurrent(),0)  + ".txt";
   string file = "Hello-Binary.txt";
   int handle;
   
   if(FileIsExist(file))FileDelete(file);
   
   handle=FileOpen(file, FILE_CSV|FILE_READ|FILE_WRITE, ',');
   if(handle>0){
      FileWrite(handle, bin);
      FileClose(handle);
   }
}

//+------------------------------------------------------------------+
void OnDeinit(const int reason){
   EventKillTimer();
   
   
   
   writeBin(txtBin);
   if(IsTesting())return;
   
   
}
//+------------------------------------------------------------------+
void OnTick(){
  OnTimer();
}
//+------------------------------------------------------------------+
void OnTimer(){
  static bool ImIn=false;
  double LevelPrice;

  
  //Comment("");
  if(Stop>0.0){Comment("Last Profits= " +NUM(Stop,2)+"$ , Stopped , Please Restart EA");return;}
  
  //---play sound if hanging
  //-----------------------------------------------------------------------
  bool it=((double)TimeCurrent()-(double)TimeLocal()-TimeOffset)<-10;
  bool Holiday=(DayOfWeek()==0 || DayOfWeek()==6);
  if(it && ChkForHang==1 && !IsTesting() && !Holiday){
    Comment("Metatrader Is Hanging...!!!");
    PlaySound(PATH+"timeout.wav");Sleep(3000);
    return;
  }else{
  }
  //-----------------------------------------------------------------------


  //-----------------------------------------------------------------------
  static datetime LastTime=0;
  if(OpenPriceOnly){
    int m=TimeSeconds(TimeCurrent());
    if(m<2 && (TimeCurrent()-LastTime)>30){LastTime=TimeCurrent();}else{return;}
  }
  //-----------------------------------------------------------------------


  //-------------------------------------------------------------------------------------------------------------------------
  //-------------------------------------------------------------------------------------------------------------------------
  //-------------------------------------------------------------------------------------------------------------------------
  //-------------------------------------------------------------------------------------------------------------------------
  int Status=-1,TimeF,TimeT,x;
  string c1;
  int OrdersCount=OrdersTotals(MAGIC,"");
  
  TimeF=(int)StrToTime(TimeFrom);
  TimeT=(int)StrToTime(TimeTo  );
  if(TimeF>TimeT){TimeT+=86400;}//if from (4 to 3) so add +24 h to 3 to be (4 to 27)
  
  if(TimeF != TimeT){
    double v=(TimeT-Time[0])/60.0/60.0;
    c1="Stop after "+DoubleToStr(v,1)+" hours.";
    
    if( Time[0]<TimeF && OrdersCount==0){Comment("Start after ",DoubleToStr((double)(TimeF-Time[0])/60.0/60.0,1)," hours.");return;}
    if((Time[0]<TimeF || Time[0]>TimeT) && OrdersCount==0){return;}
  }else{
    c1="Always run";
  }

  
  //ايام لا يعمل بها الاكسبيرت
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  Split(WorkingDays,",",StopDays);
  bool dayK=false;
  for(x=0;x<ArraySize(StopDays);x++){
    if(DayOfWeek()==StopDays[x]){dayK=true;}
  }
  if(OrdersCount==0 && !dayK){Comment("This, Is Not Working Day, Will Stop: ",DayOfWeek());return;}
  //-------------------------------------------------------------------------------------------------------------------------
  //-------------------------------------------------------------------------------------------------------------------------
  //-------------------------------------------------------------------------------------------------------------------------
  //-------------------------------------------------------------------------------------------------------------------------

  double aa1=(double(Time[0])-(int)StrToTime("00:00:00"))/60.0/60.0;
  double aa2=aa1/24.0;
  double aa3=aa2*100.0;
  //DEALS1.ProfitsHeartShareRatio=int(100.0-aa3);



  if(ImIn){return;}else{ImIn=true;}
  //============================================================================
  
  
  //Comment("Profits= ",AccountProfit());
  //+++++++++++++++++++++++++++++++++++
  SPREAD=-MarketInfo(Symbol(),MODE_SPREAD)/point_mul/TicVal/10;//2.0;//val to get 0.20 in LOT///xxxif (spread*LOT) = (real spread 0.20$)
  SPREAD=-0.20;
  double AllowedMargin=0.25;//0.5;
  
  double point=MarketInfo(Symbol(),MODE_POINT);
  if(point == 0.00001 || point==0.001){point*=10;}//make pip = 0.0001 or 0.01
  
  DoOpenClose(Symbol(),LOT,DEALS1,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,-1);
  //DoOpenClose(Symbol(),LOT,DEALS1,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
  //DoOpenClose(Symbol(),LOT,DEALS1,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
  //DoOpenClose(Symbol(),LOT,DEALS1,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
  //DoOpenClose(Symbol(),LOT,DEALS1,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
  //DoOpenClose(Symbol(),LOT,DEALS1,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
  
  
  
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  
//  InitDeals_JustStarted(DEALS1,DEALS2,SPREAD);
//
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,1);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");
//  DoOpenClose(Symbol(),LOT,DEALS1,DEALS2,iif(CalcSpreads,SPREAD,0.0),SPREAD,AllowedMargin,false,0);Comment(DEALS1.CountOpen," , ",NUM(DEALS1.ClosedDealsProfitsAndSpread+DealCalcAllOpenProfits(DEALS1,"",SPREAD),2)+" $");

  //Just Draw Lines
  //--------------------------------------
  LevelPrice=(((DEALS1.CurrentLevel-1)*LevelsDistance)+(DEALS1.StartLevelPrice/point))*point;
  if(ObjectFind("Level"+string(DEALS1.CurrentLevel-1)+string(MAGIC))<0)HLine_DRAW(LevelPrice,"Level"+string(DEALS1.CurrentLevel-1),clrLightGray,STYLE_DOT,1,true,MAGIC,false);
  //----------
  LevelPrice=(((DEALS1.CurrentLevel-0)*LevelsDistance)+(DEALS1.StartLevelPrice/point))*point;
  if(ObjectFind("Level"+string(DEALS1.CurrentLevel-0)+string(MAGIC))<0)HLine_DRAW(LevelPrice,"Level"+string(DEALS1.CurrentLevel-0),clrLightGray,STYLE_DOT,1,true,MAGIC,false);
  //----------
  LevelPrice=(((DEALS1.CurrentLevel+1)*LevelsDistance)+(DEALS1.StartLevelPrice/point))*point;
  if(ObjectFind("Level"+string(DEALS1.CurrentLevel+1)+string(MAGIC))<0)HLine_DRAW(LevelPrice,"Level"+string(DEALS1.CurrentLevel+1),clrLightGray,STYLE_DOT,1,true,MAGIC,false);
  //--------------------------------------
  
  //Just Draw Price Line
  double Price=GetPrice(Symbol(),-1,PriceMethod);
  HLine_DRAW1(Price ,"Price" ,clrBlue ,STYLE_SOLID,1,true,MAGIC ,int(WindowBarsPerChart()/7.0),false,true);
  //int CurLevel;
  //CurLevel=PriceToLevel(DEALS1.StartLevelPrice/point,Bid/point,LevelsDistance,AllowedMargin);
  
  if(IsVisualMode()){
  Comment(
          "Equity: ",NUM(AccountEquity()/1,2)," $\r\n",
          "Profit/Loss: ",NUM(AccountProfit()/1,2)," $\r\n",
          "Open Orders: ",OrdersTotals(MAGIC,"")," Deal(s)","\r\n",
          c1
         );
  }
  //+++++++++++++++++++++++++++++++++++
  
  static double MaxEquity=AccountEquity();
  static string MaxDDAT;
  static double MaxDD=-0.000001;
  static double Balance=AccountBalance();
  static int    LastPercent=0;
  static datetime eLastBarTime=Time[0],ChkTime=Time[0];
  static int      BarsCount=1;
  if(AccountEquity()-MaxEquity-AccountMargin()<MaxDD){MaxDD=AccountEquity()-MaxEquity-AccountMargin();MaxDDAT=TimeToString(Time[0]);}
  if(AccountEquity()>MaxEquity){MaxEquity=AccountEquity();}
  if(Time[0] != eLastBarTime){BarsCount+=Period();eLastBarTime=Time[0];}
  double Gained=AccountBalance()-Balance;
  double RealDD=MaxDD;//*(LotBalance/Balance);
  double ePercent=((Gained/-MaxDD)*100)/4;
  double PPM=30/(BarsCount/60.0/12.0)*ePercent;
  if(LastPercent != int(PPM)){    
    //LastPercent=int(PPM);Print(" Gained= ( ",DoubleToStr(Gained,2)," / ",DoubleToStr(MaxDD,2)," , "+DoubleToStr(RealDD*4,2)+" (/4)) $","    =   ",DoubleToStr(PPM,2)," %    in 1 Mon  (Fix DD=25%) ,, Past: ",DoubleToStr(BarsCount/60.0/12.0,1)," Days Or "+DoubleToStr(BarsCount/60.0/12.0/30.0,1)+" Mon      MaxDD AT: ",MaxDDAT);
  }
  
  //============================================================================
  ImIn=false;
}
//+------------------------------------------------------------------+







//-------------------------------------------
double GetPriceFromLevel(int Level,double StartLevelPrice,double point,double eLevelsDistance){
  double Price=((Level*eLevelsDistance)+(StartLevelPrice/point))*point;
  return Price;
}
//-------------------------------------------
void InitDeals_JustStarted(t_Deals &Deals1,double spread){
  static bool ImIn=false;
  if(ImIn){return;}
  ImIn=true;
  
  DealResetAllDeals(Deals1,Deals1.ProfitsHeartShareRatio,Deals1.ProfitsBoxShareRatio,0,0);

  Deals1.StartLevel=0.0;
  //Deals1.StartLevelPrice=GetPrice(Symbol(),-1,PriceMethod);//M2=(bid+ask)/2   xx
  Deals1.CurrentLevel=0;

  if(METHOD==Method1){
    if(OrdersTotalLots(MAGIC,Symbol(),-1)==0){
      //double spread=-2.0;//val to get 0.20 in LOT///xxxif (spread*LOT) = (real spread 0.20$)
      double AllowedMargin=0.25;
      DoOpenClose(Symbol(),LOT,Deals1,iif(CalcSpreads,spread,0.0),spread,AllowedMargin,true,-1);
    }
  }
  
  VLineCreate(0,"VLine"+TimeToString(TimeCurrent()),0,TimeCurrent(),clrGreen,STYLE_SOLID,1,"back"=="no","select"=="false",false,0);
  ImIn=false;
}
//-------------------------------------------
bool TestForCloseByProfits(t_Deals &Deals1,bool AtLevel){

  
  //Profits to close all
  if(ProfitLevel>=0.0 && AccountEquity()-LastEquity>=ProfitLevel && AtLevel){//xxx Deals calc profits spread
    CloseAllDealsNow(MAGIC);//Close All Deals
    TextCreate(0,"Text"+TimeToString(TimeCurrent()),0,iTime(Symbol(),0,-10),iClose(Symbol(),0,3),NUM(AccountEquity()-LastEquity,2)+" $","Arial",20,clrGreen,0,0,false,false,false,0);
    LastEquity=AccountEquity();
    
    if(PAUSE_PROFIT && IsTesting()){PAUSE(string(__LINE__)+"Closed By Profits");}
    if(PAUSE_PROFIT && !IsTesting()){Stop=AccountEquity()-LastEquity;}
    
    InitDeals_JustStarted(Deals1,SPREAD);
    return true;
  }

  return false;
}

//-------------------------------------------



























int Fix(double num){
  string s[];
  if(StringSplit(DoubleToString(num),'.',s)<1)return int(num);
  return (int)StringToInteger(s[0]);
}
//============================================================================
string NUM(double number,int n){
  return(DoubleToStr(number,n));
}
//============================================================================
double NormalizeLot(double eLot,string sym){
  double LotNrm,MinLot,LotStp;
  
  MinLot=MarketInfo(sym,MODE_MINLOT);
  LotStp=MarketInfo(sym,MODE_LOTSTEP);
  eLot=(double)NUM(eLot,6);//convert 1.000e-18 to 0.0
  LotNrm=(double)NUM(MathFloor(eLot/LotStp)*LotStp,6);
  if(MathAbs(LotNrm)<MinLot)return 0;
  return(LotNrm);
}
//============================================================================
int Split(string str,string s,string & arr[]){//0,10,20,30 => arr[0,10,20,30]
   int x=0,i=0,len;
   string t;
   
   len=0;
   ArrayResize(arr,0);
   
   while(true){
      i=StringFind(str+s,s,x);//str+s
      if(i==-1)return len;
      t=StringSubstr(str,x,i-x);
      if(i==x)t="";
      len++;
      ArrayResize(arr,len);
      arr[len-1]=t;
      x=i+StringLen(s);
   }
   return len;
}
//============================================================================
color iif(bool con,color tr,color fl){
  if(con){return(tr);}else{return(fl);}
}
int iif(bool con,int tr,int fl){
  if(con){return(tr);}else{return(fl);}
}
double iif(bool con,double tr,double fl){
  if(con){return(tr);}else{return(fl);}
}
string iif(bool con,string tr,string fl){
  if(con){return(tr);}else{return(fl);}
}
//============================================================================
//============================================================================
//============================================================================
//============================================================================
bool OpenDealLife(int Magic,string eDEAL,string eD,double eLot,string eC,int slp,int timeOutSec){
    bool i;
    double Lots;
    if(eC=="0"){eC="1";}
    datetime t=TimeCurrent();
    
    eLot=NormalizeLot(eLot,eDEAL);
    if(eLot==0.0){ObjectSetText("L1","Lot=0.0 "+eDEAL+" : "+eD,10,"Times New Roman",Red);Sleep(500);return false;}
    if(eDEAL=="" || eDEAL==NULL){ObjectSetText("L1","DEAL=''",10,"Times New Roman",Red);Sleep(500);return false;}
    if(eD==""    || eD==NULL   ){ObjectSetText("L1","D=''",10,"Times New Roman",Red);Sleep(500);return false;}
    
    //if(DEALS_SOUND)PlaySound("+12.wav");
    Lots=OrdersTotalLots(Magic,eDEAL,-1);
    while(true){
      if(IsStopped()){return false;}
      if((IsExpertEnabled()==false || IsTradeAllowed()==false) && IsTesting()==false){PlaySound(PATH+"alert2.wav");Comment("Canot Open,Please Allow Auto");Print("Canot Open,Please Allow Auto!!");Sleep(1000);Sleep(1000);Sleep(1000);}
      ObjectSetText("L1","Open "+eDEAL+" : "+eD,14,"Times New Roman",Green);
      if(OrdersTotalLots(Magic,eDEAL,-1)!=Lots){break;}//may be open buy make a close in sell
      if(eDEAL != "" && eD=="S"){ i=OrderSend(eDEAL,OP_SELL,eLot,SymbolInfoDouble(eDEAL, SYMBOL_BID),slp,0,0,eC,Magic,0,Red ); }
      if(eDEAL != "" && eD=="B"){ i=OrderSend(eDEAL,OP_BUY ,eLot,SymbolInfoDouble(eDEAL, SYMBOL_ASK),slp,0,0,eC,Magic,0,Blue); }
      if(OrdersTotalLots(Magic,eDEAL,-1)!=Lots){break;}//may be open buy make a close in sell
      //if(i != 0){break;}
      if(TimeCurrent()-t>=timeOutSec){return false;}
      Alert("Error Open "+eDEAL+" Err="+(string)GetLastError());Sleep(1000);Sleep(1000);Sleep(1000);
      //Alert("Error Open "+eDEAL+" Err="+(string)ErrorDescription(GetLastError()));Sleep(1000);Sleep(1000);Sleep(1000);
    }
    if(DEALS_SOUND)PlaySound(PATH+"chime.wav");
    return(true);
}
//============================================================================


//============================================================================
int OrdersTotals(int Magic,string sym){
  int x=0,i;
  bool error;
  
  while(true){
    x=0;
    error=false;
    for(i=0;i<OrdersTotal();i++){
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){RefreshRates();error=true;break;}
      if((OrderMagicNumber()==Magic || Magic==-1) && (OrderType()==OP_BUY || OrderType()==OP_SELL) && (OrderSymbol()==sym || sym=="" || sym==NULL)){x++;}
    }
    if(!error){break;}
    if(IsStopped()){return -1;};
  }
  return(x);
}
//============================================================================
int OrdersTotals(int Magic,string sym,int Direction){
  int x=0,i;
  bool error;
  
  while(true){
    x=0;
    error=false;
    for(i=0;i<OrdersTotal();i++){
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){RefreshRates();error=true;break;}
      if((OrderMagicNumber()==Magic || Magic==-1) && OrderType()==Direction && (OrderSymbol()==sym || sym=="" || sym==NULL)){x++;}
    }
    if(!error){break;}
    if(IsStopped()){return -1;};
  }
  return(x);
}
//============================================================================ 
//============================================================================
//============================================================================
//============================================================================
double OrdersTotalLots(int Magic,string sym,int Direction){
  int i;
  double Lots=0.0;
  bool error;
  
  if(!MQL4){return OrdersTotalLots_MT5(sym);}
  
  while(true){
    Lots=0.0;
    error=false;
    for(i=0;i<OrdersTotal();i++){
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){RefreshRates();error=true;break;}
      if((OrderMagicNumber()==Magic || Magic==-1) && (OrderType()==Direction || Direction==-1) && (OrderSymbol()==sym || sym=="" || sym==NULL)){Lots+=OrderLots();}
    }
    if(!error){break;}
    if(IsStopped()){return 0.0;};
  }
  return(Lots);
}
//============================================================================
//============================================================================
double OrdersTotalLots_MT5(string sym){
  int i;
  double Lots=0.0;
  bool error;
  
  while(true){
    Lots=0.0;
    error=false;
    for(i=0;i<OrdersTotal();i++){//un comment if MT5
      //if(!PositionSelect(sym)){error=true;break;}
      //Lots=PositionGetDouble(POSITION_VOLUME);
      //return(Lots);
    }
    if(!error){break;}
    if(IsStopped()){return 0.0;};
  }
  return(Lots);
}
//============================================================================
//============================================================================
bool OrderSelectDateFirst(int Magic,string sym,int eType){
  int i,ticket=0;
  datetime t=TimeCurrent();
  for(i=0;i<OrdersTotal();i++){
    if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){return false;}
    if(OrderOpenTime()<=t && (OrderMagicNumber()==Magic || Magic==-1) && (OrderSymbol()==sym || sym=="" || sym==NULL) && (OrderType()==eType || eType==-1)){t=OrderOpenTime();ticket=OrderTicket();}
  }
  return OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
}

bool CloseDealsLifeDateFirst(int Magic,string sym,int eType,double Lot){
   double lot=0.0;
   bool r=false;
   
   if(!MQL4)return CloseDealsLifeDateFirst_MT5(Magic,sym,eType,Lot);
   
   if(DEALS_SOUND)PlaySound(PATH+"OUH.WAV");//eoo.wav
   RefreshRates();
   
   while(OrdersTotals(Magic,sym,eType)>0 && !IsStopped()){
   //while(OrdersTotalLots(Magic,sym,eType)>0.0){
      //Print("Lot=",Lot);
      //Print(OrdersTotals(Magic,sym,eType));
      //Print(-10);
      if(NormalizeLot(val(Lot),sym)<MarketInfo(sym,MODE_MINLOT)){Print("**********  Lot<MinLot, Lot=",Lot,"  ***********");return true;}
   //while(OrdersTotalLots(Magic,sym,eType)>0.0){
      if(OrderSelectDateFirst(Magic,sym,eType)){
        if(IsStopped()){return false;}
        if((IsExpertEnabled()==false || IsTradeAllowed()==false)&& !IsTesting()){PlaySound(PATH+"alert2.wav");Comment("Canot Close,Please Allow Auto");Print("Canot Close,Please Allow Auto!!");Sleep(1000);Sleep(1000);Sleep(1000);}

        if(SymbolInfoDouble(OrderSymbol(), SYMBOL_BID)==0 || SymbolInfoDouble(OrderSymbol(), SYMBOL_ASK)==0){PlaySound(PATH+"error.wav");Print("Deal #"+IntegerToString(OrderTicket())+" canot be closed due no prices for "+OrderSymbol());}
        //---------------------------------------------------
        if(OrderLots()>=Lot){lot=NormalizeLot(Lot,sym);}
        if(OrderLots()< Lot){lot=OrderLots();}
        
        if(OrderType()==OP_BUY ){r=OrderClose(OrderTicket(),lot,SymbolInfoDouble(OrderSymbol(), SYMBOL_BID),3000,clrLightGreen);}
        if(OrderType()==OP_SELL){r=OrderClose(OrderTicket(),lot,SymbolInfoDouble(OrderSymbol(), SYMBOL_ASK),3000,clrLightPink );}
        if(!r){PlaySound(PATH+"error.wav");Print("Canot Close "+OrderSymbol());RefreshRates();break;}
        Lot-=lot;
        if(NormalizeLot(Lot,sym)<=0.0)return true;
        //---------------------------------------------------
      }else{RefreshRates();}
   }

   
   return(true);
}
bool CloseDealsLifeDateFirst_MT5(int Magic,string sym,int eType,double Lot){//mt5 close by open
   double lot=0.0;
   bool r=false;
   
   if(DEALS_SOUND)PlaySound(PATH+"OUH.WAV");//eoo.wav
   //RefreshRates();
   
   //while(OrdersTotals(Magic,sym,eType)>0){
   //while(OrdersTotalLots(Magic,sym,eType)>0.0){
      if(Lot<=0.0)return true;
      //if(OrderSelectDateFirst(Magic,sym,eType)){
        if(IsStopped()){return false;}
        if((IsExpertEnabled()==false || IsTradeAllowed()==false) && !IsTesting()){PlaySound(PATH+"alert2.wav");Comment("Canot Close,Please Allow Auto");Print("Canot Close,Please Allow Auto!!");Sleep(1000);Sleep(1000);Sleep(1000);}

        if(SymbolInfoDouble(OrderSymbol(), SYMBOL_BID)==0 || SymbolInfoDouble(OrderSymbol(), SYMBOL_ASK)==0){PlaySound(PATH+"error.wav");Print("Deal #"+IntegerToString(OrderTicket())+" canot be closed due no prices for "+OrderSymbol());}
        //---------------------------------------------------
        //if(OrderLots()>=Lot){lot=Lot;}
        //if(OrderLots()< Lot){lot=OrderLots();}
        
        //if(OrderType()==OP_BUY ){r=OrderClose(OrderTicket(),lot,SymbolInfoDouble(OrderSymbol(), SYMBOL_BID),3000,clrLightGreen);}
        //if(OrderType()==OP_SELL){r=OrderClose(OrderTicket(),lot,SymbolInfoDouble(OrderSymbol(), SYMBOL_ASK),3000,clrLightPink );}
        
        if(eType==OP_BUY ){r=OpenDealLife(MAGIC,sym,"S",lot,"",5,3);}
        if(eType==OP_SELL){r=OpenDealLife(MAGIC,sym,"B",lot,"",5,3);}
        //if(!r){PlaySound(PATH+"error.wav");Print("Canot Close "+OrderSymbol());RefreshRates();break;}
        //Lot-=lot;
        //if(Lot<=0.0)return true;
        //---------------------------------------------------
      //}else{RefreshRates();}
   //}

   
   return(true);
}


//*******************************************************************************************
bool CloseAllDealsNow(int Magic){
  if(DEALS_SOUND)PlaySound("OUH.WAV");//eoo.wav
  
  if(!MQL4){
    double Lots=OrdersTotalLots_MT5(Symbol());
    CloseDealsLifeDateFirst(MAGIC,Symbol(),OP_BUY ,Lots);
    CloseDealsLifeDateFirst(MAGIC,Symbol(),OP_SELL,Lots);
    return true;
  }

  while((IsExpertEnabled()==false || IsTradeAllowed()==false) && !IsTesting()){
    if(IsStopped()){return false;}
    if(OrdersTotals(Magic,Symbol())==0){return true;}
    Comment("Canot Close,Please Allow Auto");
    //PlaySound("alert2");
    //Print("Canot Close,Please Allow Auto!!");
    Sleep(1000);Sleep(1000);Sleep(1000);
  }
  
  if(OrdersTotals(Magic,Symbol())>0){TryCloseAllBy(true,Magic);}
  CloseAllDealsBigFirst(Magic);
  if(OrdersTotals(Magic,Symbol())==0){return true;}
  return false;
}
//*******************************************************************************************
//*******************************************************************************************
bool CloseAllDealsBigFirst(int Magic){
   double B,Lots=0;
   datetime t=TimeCurrent();
   B=AccountBalance()+AccountCredit();
   int OT=OrdersTotals(Magic,Symbol());
   
   //if(DEALS_SOUND)PlaySound("OUH.WAV");//eoo.wav
   RefreshRates();
   
   while(OrdersTotals(Magic,Symbol())>0){
      if(OrderSelectBigFirst(Magic)){
        if(IsStopped()){return false;}
        if((IsExpertEnabled()==false || IsTradeAllowed()==false) && !IsTesting()){PlaySound("alert2");Comment("Canot Close,Please Allow Auto");Print("Canot Close,Please Allow Auto!!");Sleep(1000);Sleep(1000);Sleep(1000);}

        if(SymbolInfoDouble(OrderSymbol(), SYMBOL_BID)==0 || SymbolInfoDouble(OrderSymbol(), SYMBOL_ASK)==0){PlaySound("error");Print("Deal #"+IntegerToString(OrderTicket())+" canot be closed due no prices for "+OrderSymbol());}
        //---------------------------------------------------
        Lots+=OrderLots();
        if(OrderType()==OP_BUY  && (OrderMagicNumber()==Magic || Magic==-1)){if(!OrderClose(OrderTicket(),OrderLots(),SymbolInfoDouble(OrderSymbol(), SYMBOL_BID),3000,clrLightGreen)){PlaySound("error");Print("Canot Close "+OrderSymbol());RefreshRates();}else{Print("Close Done: "+OrderSymbol());if(DEALS_SOUND){PlaySound("coin");}}}
        if(OrderType()==OP_SELL && (OrderMagicNumber()==Magic || Magic==-1)){if(!OrderClose(OrderTicket(),OrderLots(),SymbolInfoDouble(OrderSymbol(), SYMBOL_ASK),3000,clrLightPink )){PlaySound("error");Print("Canot Close "+OrderSymbol());RefreshRates();}else{Print("Close Done: "+OrderSymbol());if(DEALS_SOUND){PlaySound("coin");}}}
        //---------------------------------------------------
      }else{RefreshRates();}
   }

   ChartRedraw();
   return(true);
}
//*******************************************************************************************
//*******************************************************************************************
bool OrderSelectBigFirst(int Magic){
  int i,ticket=0;
  double max=0;
  //RefreshRates();
  for(i=0;i<OrdersTotal();i++){
    if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){return false;}
    if(OrderLots()>max && (OrderMagicNumber()==Magic || Magic==-1)){max=OrderLots();ticket=OrderTicket();}
  }
  return OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
}
//*******************************************************************************************
//---------------------------------------------------------------------
void TryCloseAllBy(bool exit_if_error,int Magic){
  while(!CloseAllOrdersBy(exit_if_error,Magic)){}
}
//---------------------------------------------------------------------
bool CloseAllOrdersBy(bool exit_if_error,int Magic){//false==error, true=fin ok
  string Syms="";
  if(OrdersTotal()==0){return true;}
  RefreshRates();
  for(int i=OrdersTotal()-1;i>=0;i--){
    if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){RefreshRates();return false;}
    if(StringFind(Syms,OrderSymbol())<0 && (OrderType()==OP_SELL || OrderType()==OP_BUY) && (OrderMagicNumber()==Magic || Magic==-1)){Syms+=OrderSymbol()+"|";}
  }
  
  string S[];
  int k=StringSplit(Syms,'|',S);
  for(int i=0;i<k-1;i++){
    while(CloseBySym(S[i],exit_if_error,Magic)){}
  }

  return true;
}
//---------------------------------------------------------------------
bool CloseBySym(string sym,bool exit_if_error,int Magic=0){//false == fin, true==not yet
  int t1=0,t2=0,check;
  bool r;
  
  for(int i=OrdersTotal()-1;i>=0;i--){
    if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){RefreshRates();return true;}
    if(OrderSymbol()==sym && OrderType()==OP_BUY  && t1==0 && (OrderMagicNumber()==Magic || Magic==-1)){t1=OrderTicket();}
    if(OrderSymbol()==sym && OrderType()==OP_SELL && t2==0 && (OrderMagicNumber()==Magic || Magic==-1)){t2=OrderTicket();}

    if(t1>0 && t2>0){
      r=OrderCloseBy(t1,t2);
      //if(DEALS_SOUND)PlaySound("coin");//eoo.wav
      check=GetLastError(); 
      if(check!=ERR_NO_ERROR){Print("OrderCloseBy() Error: ",string(check));if(exit_if_error){return false;}}
      return true;
    }
  }
  return false;
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------














//=========================================================================================================
void Arrow(string name,long code,datetime time,double price,color col,bool back){
  if(IsTesting() && !IsVisualMode())return;
  if(ObjectFind(0,name)>-1){ObjectDelete(0,name);}
  ObjectCreate(0,name,OBJ_ARROW,0,0,0,0,0);          // Create an arrow 
  ObjectSetInteger(0,name,OBJPROP_ARROWCODE,code);    // Set the arrow code 
  ObjectSetInteger(0,name,OBJPROP_TIME,time);        // Set time 
  ObjectSetInteger(0,name,OBJPROP_COLOR,col);        // Set time 
  ObjectSetDouble(0,name,OBJPROP_PRICE,price);// Set price 
  ObjectSetInteger(0,name,OBJPROP_BACK,back); 
  ChartRedraw(0);                                        
}

//+------------------------------------------------------------------+
void HLine_DRAW(double Level,string Name,color col,int style,int width,bool show,int eMagic,bool back){//name=zigzaghi
  if(IsTesting() && !IsVisualMode())return;
  if(ObjectFind(Name+(string)eMagic)>-1)ObjectDelete(Name+(string)eMagic);
  if(!show){return;}
  
  ObjectCreate(Name+(string)eMagic, OBJ_HLINE, 0, 0,Level);
  ObjectSet   (Name+(string)eMagic, OBJPROP_COLOR, col);
  ObjectSet   (Name+(string)eMagic, OBJPROP_STYLE, style);
  ObjectSet   (Name+(string)eMagic, OBJPROP_WIDTH, width);
  ObjectSetInteger(0,Name+(string)eMagic,OBJPROP_BACK,back); 
  ChartRedraw();
}
//+------------------------------------------------------------------+
void HLine_DRAW1(double Price,string Name,color col,int style,int width,bool show,int eMagic,int WidthInBars,bool back,bool show_price){
  if(IsTesting() && !IsVisualMode())return;
  if(ObjectFind(Name+(string)eMagic)>-1)ObjectDelete(Name+(string)eMagic);
  if(!show){return;}
  TrendCreate(0,Name+(string)eMagic,0,iTime(Symbol(),0,0),Price,iTime(Symbol(),0,WidthInBars),Price,col,(ENUM_LINE_STYLE) style,width,back,false,false,false,0);
  
  if(!show_price){ChartRedraw(); return;}
  
  if(ObjectFind("Price."+Name+(string)eMagic)>-1)ObjectDelete("Price."+Name+(string)eMagic);
   ObjectCreate("Price."+Name+(string)eMagic, OBJ_ARROW, 0,iTime(Symbol(),0,0), Price);
   ObjectSet   ("Price."+Name+(string)eMagic, OBJPROP_ARROWCODE, SYMBOL_RIGHTPRICE);
   ObjectSet   ("Price."+Name+(string)eMagic, OBJPROP_COLOR, col);
   //ObjectSetInteger(0,"Price."+Name+(string)eMagic,OBJPROP_ZORDER,0);

}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
void TREND_DRAW(datetime Time1,double Price1,datetime Time2,double Price2,string Name,color col,int style,int width,bool show,int eMagic,bool back){
  if(IsTesting() && !IsVisualMode())return;
  if(ObjectFind(Name+(string)eMagic)>-1)ObjectDelete(Name+(string)eMagic);
  if(!show){return;}
  TrendCreate(0,Name+(string)eMagic,0,Time1,Price1,Time2,Price2,col,(ENUM_LINE_STYLE) style,width,back,false,false,false,0);
  ChartRedraw();
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+ 
//| Create a trend line by the given coordinates                     | 
//+------------------------------------------------------------------+ 
bool TrendCreate(const long            chart_ID=0,        // chart's ID 
                 const string          name="TrendLine",  // line name 
                 const int             sub_window=0,      // subwindow index 
                 datetime              time1=0,           // first point time 
                 double                price1=0,          // first point price 
                 datetime              time2=0,           // second point time 
                 double                price2=0,          // second point price 
                 const color           clr=clrRed,        // line color 
                 const ENUM_LINE_STYLE style=STYLE_SOLID, // line style 
                 const int             width=1,           // line width 
                 const bool            back=false,        // in the background 
                 const bool            selection=true,    // highlight to move 
                 const bool            ray_right=false,   // line's continuation to the right 
                 const bool            hidden=true,       // hidden in the object list 
                 const long            z_order=0)         // priority for mouse click 
  { 
//--- set anchor points' coordinates if they are not set 
  if(IsTesting() && !IsVisualMode())return false;
   ChangeTrendEmptyPoints(time1,price1,time2,price2); 
//--- reset the error value 
   ResetLastError(); 
//--- create a trend line by the given coordinates 
  if(ObjectFind(name)>-1)ObjectDelete(name);

   if(!ObjectCreate(chart_ID,name,OBJ_TREND,sub_window,time1,price1,time2,price2)) 
     { 
      Print(__FUNCTION__, 
            ": failed to create a trend line! Error code = ",GetLastError()); 
      return(false); 
     } 
//--- set line color 
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr); 
//--- set line display style 
   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style); 
//--- set line width 
   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width); 
//--- display in the foreground (false) or background (true) 
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back); 
//--- enable (true) or disable (false) the mode of moving the line by mouse 
//--- when creating a graphical object using ObjectCreate function, the object cannot be 
//--- highlighted and moved by default. Inside this method, selection parameter 
//--- is true by default making it possible to highlight and move the object 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection); 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection); 
//--- enable (true) or disable (false) the mode of continuation of the line's display to the right 
   ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right); 
//--- hide (true) or display (false) graphical object name in the object list 
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden); 
//--- set the priority for receiving the event of a mouse click in the chart 
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order); 
//--- successful execution 
   return(true); 
  } 
//+------------------------------------------------------------------+ 
//+------------------------------------------------------------------+ 
//| Check the values of trend line's anchor points and set default   | 
//| values for empty ones                                            | 
//+------------------------------------------------------------------+ 
void ChangeTrendEmptyPoints(datetime &time1,double &price1, 
                            datetime &time2,double &price2) 
  { 
//--- if the first point's time is not set, it will be on the current bar 
   if(!time1) 
      time1=TimeCurrent(); 
//--- if the first point's price is not set, it will have Bid value 
   if(!price1) 
      price1=SymbolInfoDouble(Symbol(),SYMBOL_BID); 
//--- if the second point's time is not set, it is located 9 bars left from the second one 
   if(!time2) 
     { 
      //--- array for receiving the open time of the last 10 bars 
      datetime temp[10]; 
      CopyTime(Symbol(),Period(),time1,10,temp); 
      //--- set the second point 9 bars left from the first one 
      time2=temp[0]; 
     } 
//--- if the second point's price is not set, it is equal to the first point's one 
   if(!price2) 
      price2=price1; 
  } 

bool VLineCreate(const long            chart_ID=0,        // chart's ID 
                 const string          name="VLine",      // line name 
                 const int             sub_window=0,      // subwindow index 
                 datetime              time=0,            // line time 
                 const color           clr=clrRed,        // line color 
                 const ENUM_LINE_STYLE style=STYLE_SOLID, // line style 
                 const int             width=1,           // line width 
                 const bool            back=false,        // in the background 
                 const bool            selection=true,    // highlight to move 
                 const bool            hidden=true,       // hidden in the object list 
                 const long            z_order=0)         // priority for mouse click 
  { 
  if(IsTesting() && !IsVisualMode())return false;
//--- if the line time is not set, draw it via the last bar 
   if(!time) 
      time=TimeCurrent(); 
//--- reset the error value 
   ResetLastError(); 
//--- create a vertical line 
  if(ObjectFind(name)>-1)ObjectDelete(name);

   if(!ObjectCreate(chart_ID,name,OBJ_VLINE,sub_window,time,0)) 
     { 
      Print(__FUNCTION__, 
            ": failed to create a vertical line! Error code = ",GetLastError()); 
      return(false); 
     } 
//--- set line color 
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr); 
//--- set line display style 
   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style); 
//--- set line width 
   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width); 
//--- display in the foreground (false) or background (true) 
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back); 
//--- enable (true) or disable (false) the mode of moving the line by mouse 
//--- when creating a graphical object using ObjectCreate function, the object cannot be 
//--- highlighted and moved by default. Inside this method, selection parameter 
//--- is true by default making it possible to highlight and move the object 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection); 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection); 
//--- hide (true) or display (false) graphical object name in the object list 
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden); 
//--- set the priority for receiving the event of a mouse click in the chart 
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order); 
//--- successful execution 
   return(true); 
  } 
//+------------------------------------------------------------------+ 
//| Move the vertical line                                           | 
//+------------------------------------------------------------------+ 
bool VLineMove(const long   chart_ID=0,   // chart's ID 
               const string name="VLine", // line name 
               datetime     time=0)       // line time 
  { 
//--- if line time is not set, move the line to the last bar 
   if(!time) 
      time=TimeCurrent(); 
//--- reset the error value 
   ResetLastError(); 
//--- move the vertical line 
   if(!ObjectMove(chart_ID,name,0,time,0)) 
     { 
      Print(__FUNCTION__, 
            ": failed to move the vertical line! Error code = ",GetLastError()); 
      return(false); 
     } 
//--- successful execution 
   return(true); 
  } 
//+------------------------------------------------------------------+ 
//| Delete the vertical line                                         | 
//+------------------------------------------------------------------+ 
bool VLineDelete(const long   chart_ID=0,   // chart's ID 
                 const string name="VLine") // line name 
  { 
//--- reset the error value 
   ResetLastError(); 
//--- delete the vertical line 
  if(ObjectFind(name)>-1)ObjectDelete(name);

//--- successful execution 
   return(true); 
  } 
//=========================================================================================================
//=========================================================================================================
//+------------------------------------------------------------------+ 
//| Creating Text object                                             | 
//+------------------------------------------------------------------+ 
bool TextCreate(const long              chart_ID=0,               // chart's ID 
                const string            name="Text",              // object name 
                const int               sub_window=0,             // subwindow index 
                datetime                time=0,                   // anchor point time 
                double                  price=0,                  // anchor point price 
                const string            text="Text",              // the text itself 
                const string            font="Arial",             // font 
                const int               font_size=10,             // font size 
                const color             clr=clrRed,               // color 
                const double            angle=0.0,                // text slope 
                const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type 
                const bool              back=false,               // in the background 
                const bool              selection=false,          // highlight to move 
                const bool              hidden=true,              // hidden in the object list 
                const long              z_order=0)                // priority for mouse click 
  { 
//--- set anchor point coordinates if they are not set 
   ChangeTextEmptyPoint(time,price); 
//--- reset the error value 
   ResetLastError(); 
//--- create Text object 
  if(ObjectFind(name)>-1)ObjectDelete(name);

   if(!ObjectCreate(chart_ID,name,OBJ_TEXT,sub_window,time,price)) 
     { 
      Print(__FUNCTION__, 
            ": failed to create \"Text\" object! Error code = ",GetLastError()); 
      return(false); 
     } 
//--- set the text 
   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text); 
//--- set text font 
   ObjectSetString(chart_ID,name,OBJPROP_FONT,font); 
//--- set font size 
   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size); 
//--- set the slope angle of the text 
   ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle); 
//--- set anchor type 
   ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor); 
//--- set color 
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr); 
//--- display in the foreground (false) or background (true) 
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back); 
//--- enable (true) or disable (false) the mode of moving the object by mouse 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection); 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection); 
//--- hide (true) or display (false) graphical object name in the object list 
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden); 
//--- set the priority for receiving the event of a mouse click in the chart 
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order); 
//--- successful execution 
   return(true); 
  } 
//+------------------------------------------------------------------+ 
//| Move the anchor point                                            | 
//+------------------------------------------------------------------+ 
bool TextMove(const long   chart_ID=0,  // chart's ID 
              const string name="Text", // object name 
              datetime     time=0,      // anchor point time coordinate 
              double       price=0)     // anchor point price coordinate 
  { 
//--- if point position is not set, move it to the current bar having Bid price 
   if(!time) 
      time=TimeCurrent(); 
   if(!price) 
      price=SymbolInfoDouble(Symbol(),SYMBOL_BID); 
//--- reset the error value 
   ResetLastError(); 
//--- move the anchor point 
   if(!ObjectMove(chart_ID,name,0,time,price)) 
     { 
      Print(__FUNCTION__, 
            ": failed to move the anchor point! Error code = ",GetLastError()); 
      return(false); 
     } 
//--- successful execution 
   return(true); 
  } 
//+------------------------------------------------------------------+ 
//| Change the object text                                           | 
//+------------------------------------------------------------------+ 
bool TextChange(const long   chart_ID=0,  // chart's ID 
                const string name="Text", // object name 
                const string text="Text") // text 
  { 
//--- reset the error value 
   ResetLastError(); 
//--- change object text 
   if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text)) 
     { 
      Print(__FUNCTION__, 
            ": failed to change the text! Error code = ",GetLastError()); 
      return(false); 
     } 
//--- successful execution 
   return(true); 
  } 
//+------------------------------------------------------------------+ 
//| Delete Text object                                               | 
//+------------------------------------------------------------------+ 
bool TextDelete(const long   chart_ID=0,  // chart's ID 
                const string name="Text") // object name 
  { 
//--- reset the error value 
   ResetLastError(); 
//--- delete the object

   if(!ObjectDelete(chart_ID,name)) 
     { 
      Print(__FUNCTION__, 
            ": failed to delete \"Text\" object! Error code = ",GetLastError()); 
      return(false); 
     } 
//--- successful execution 
   return(true); 
  } 
//+------------------------------------------------------------------+ 
//| Check anchor point values and set default values                 | 
//| for empty ones                                                   | 
//+------------------------------------------------------------------+ 
void ChangeTextEmptyPoint(datetime &time,double &price) 
  { 
//--- if the point's time is not set, it will be on the current bar 
   if(!time) 
      time=TimeCurrent(); 
//--- if the point's price is not set, it will have Bid value 
   if(!price) 
      price=SymbolInfoDouble(Symbol(),SYMBOL_BID); 
  } 
//=========================================================================================================
//=========================================================================================================
void Split(string str,string s,double & arr[]){//0,10,20,30 => arr[0,10,20,30]
   int x=0,i,len;
   string t;
   
   len=0;
   ArrayResize(arr,0);
   
   while(true){
      i=StringFind(str+s,s,x);
      if(i==-1)return;
      t=StringSubstr(str,x,i-x);
      len++;
      ArrayResize(arr,len);
      arr[len-1]=StrToDouble(t);
      x=i+1;
   }
   return;
}
//+------------------------------------------------------------------+


#include <WinUser32.mqh>
#define pause PAUSE()
void PAUSE(string ln=""){ // pauses visual mode during testing needs #include <WinUser32.mqh>
  if(!IsVisualMode()){return;}
  if(!IsDllsAllowed()){Print("IsDllsAllowed=",IsDllsAllowed());return;}
  keybd_event(19,0,0,0);//Print("1");
  keybd_event(19,0,2,0);Print("Auto Pause Pressed At Line:   ",ln);
  //----crunch some numbers as sleep
  int a=100000000*1,b=0;
  while(a>b)b++;//delay 1 sec in my 2.0 GHz CPU
}
//------------------------------------------------------------------------------------


