Navigation:Home > Content >

FIFTY_EA.mq4

Time: 2015-08-17 | Download file:FIFTY_EA.mq4

//+------------------------------------------------------------------------------------------------------------------+
//|                                                                                Y2010.M12.D15_Expert_Advisor.mq4  |
//|                                                                   Copyright © 2008-2010, TradingSystemForex.Com  |
//|                                                                              http://www.tradingsystemforex.com/  |
//+------------------------------------------------------------------------------------------------------------------+

#property copyright "Copyright © 2008-2010, TradingSystemForex.Com"
#property link "http://www.tradingsystemforex.com/"

#include 
#include 

//+--------------------------------------------------------------------------------+ EXTERNAL INPUTS +---------------+
//  Scalping : You can use timeout and target, time filter,
//  set maxtrades=1,changedirection=true to optimize the scalping.

//--- Add "extern " before each parameter to get them in the inputs tab

string comment="EA";                     // comment to display in the order
extern int magic=1234;                   // magic number required if you use different settings on a pair, same tf
bool randommagic=false;                  // use random magic number
bool useprint=false;                     // use print
bool usecomment=false;                   // use comment
bool emailalert=false;                   // use email alert
bool popupalert=false;                   // use popup alert
bool soundalert=false;                   // use sound alert
bool onlybuy=false;                      // only enter buy orders
bool onlysell=false;                     // only enter sell orders
bool visualequity=false;                 // draw equity

extern string moneymanagement="Money Management";

extern double lots=0.1;                  // lots size
extern bool mm=false;                    // enable risk management
extern double risk=1;                    // risk in percentage of the account
extern double minlot=0.01;               // minimum lots size
extern double maxlot=100;                // maximum lots size
extern int lotdigits=2;                  // lot digits, 1=0.1, 2=0.01
bool martingale=false;                   // enable the martingale, set maxtrades to 1
bool fibomartingale=false;               // enable the martingale with fibonacci progression
int martingalemode=0;                    // 0=don't use percentrecovering, 1=use percentrecovering
double multiplier=2.0;                   // multiplier used for the martingale
double percentrecovering=50.0;           // percentage of the last losses to recover
bool addpositions=false;                 // add positions, set tradesperbar to 100
bool signalfilter=false;                  // signal filter for added positions
int addposmode=0;                        // 0=counter, 1=follow
double pipstep=20;                       // minimum difference in pips between orders
double pipstepfactor=1.0;                // multiply the pipstep by the number of buy/sell orders

string profitmanagement="Profit Management";

bool basketpercent=false;                // enable the basket percent
double profit=0.1;                       // close all orders if a profit of 0.1 percents has been reached
double loss=100;                         // close all orders if a loss of 100 percents has been reached
bool basketpips=false;                   // enable the basket pips
double profitpips=10;                    // close all orders if a profit of 10 pips has been reached
double losspips=10000;                   // close all orders if a loss of 10000 pips has been reached
bool basketdollars=false;                // enable basket dollars
double dollars=5;                        // target in dollars
bool baskettrailing=false;               // basket trailing option
double baskettrailingstart=5;            // basket trailing start in account balance percent
double baskettrailingstop=-2;            // basket trailing stop in account balance percent
double basketoptimization=0;             // parameter for optimization to find start and stop

extern string ordersmanagement="Order Management";

extern bool ecn=false;                   // make the expert compatible with ecn brokers
bool instantorders=true;                 // instant orders
bool stoporders=false;                   // stoporders
bool limitorders=false;                  // limit orders
bool onecancelother=false;               // cancel opposite pending orders when one is triggered
int gap=20;                              // gap for pending orders
bool oppositedelete=true;                // delete the pending orders on an opposite signal
extern bool oppositeclose=true;          // close the orders on an opposite signal
bool checkclose=false;                   // we check close of the orders on opposite signal
int oppositecloseminloss=0;              // min loss to consider to enable opposite close
bool partialexit=false;                  // partial exit at opposite close
bool partialclose=false;                 // partial close at takeprofit 2 and takeprofit 3
extern bool reversesignals=false;        // reverse the signals, long if short, short if long
extern int maxtrades=100;                // maximum trades allowed by the traders
extern int tradesperbar=1;               // maximum trades per bar allowed by the expert
extern bool hidesl=false;                // hide stop loss
extern bool hidetp=false;                // hide take profit
extern double stoploss=0;                // stop loss
extern double takeprofit=0;              // take profit
double takeprofit2=5;                    // takeprofit 2 to close a certain percentage of lots
double tp2percentage=25;                 // percentage of lots to close at takeprofit 2
double takeprofit3=20;                   // takeprofit 3 to close a certain percentage of lots
double tp3percentage=50;                 // percentage of lots to close at takeprofit 3
int trailingstopmode=0;                  // 0 new sl=ask+/-tst, 1 new sl=sl+/-ts or order open price/-ts if sl=0
extern double trailingstart=0;           // profit in pips required to enable the trailing stop
extern double trailingstop=0;            // trailing stop
double trailingprofit=0;                 // trailing profit
extern double trailingstep=1;            // margin allowed to the market to enable the trailing stop
extern double breakevengain=0;           // gain in pips required to enable the break even
extern double breakeven=0;               // break even
int expiration=1440;                     // expiration in minutes for pending orders
double slippage=0;                       // maximum difference in pips between signal and order
extern double maxspread=0;               // maximum spread allowed by the expert, 0=disabled

extern string adordersmanagement="Advanced Order Management";

extern bool firstticks=false;            // we enter on first ticks only
extern int ticks=4;                      // first ticks
bool ignoreinitialbar=false;             // ignore initial bar to not enter when we need to restart the platform
extern bool changedirection=false;       // only buy after a sell order, sell after a buy order
extern bool onesideatatime=false;        // enter only long or short when a long or short is already opened
extern double stop=0;                    // stop=stoploss and takeprofit
extern double trailing=0;                // trailing=trailingstart and trailingstop
bool reverseatstop=false;                // we reverse the order when the stoploss has been reached
bool rasoppositeclose=true;              // close reversed order on opposite signal
int rasstoploss=0;                       // reversed order stop loss
int rastakeprofit=0;                     // reversed order take profit
bool sleepafterxlosses=false;            // ea sleeps after x consecutive losses
int xlosses=4;                           // x consecutive losses
int sleepminutes=60;                     // sleep minutes
double slfactor=0;                       // enable dynamic stoploss if different of 0
int slmargin=0;                          // margin to add to the stoploss
double tpfactor=0;                       // enable dynamic takeprofit if different of 0
int stoplevel=15;                        // minimum value for dynamic variables
bool atrstops=false;                     // dynamic stops based on atr
int atrtimeframe=60;                     // timeframe for the atr
int atrperiod=14;                        // atr period
double tstfactor=0;                      // enable dynamic trailing start if different of 0
double tsfactor=0;                       // enable dynamic trailing stop if different of 0
double begfactor=0;                      // enable dynamic breakevengain if different of 0
double befactor=0;                       // enable dynamic breakeven if different of 0
double psfactor=0;                       // enable dynamic pipstep if different of 0
double gfactor=0;                        // enable dynamic gap if different of 0
bool highlowstops=false;                 // dynamic stops based on highest/lowest
bool highlowtrail=false;                 // trailing stop based on highest/lowest
int hltimeframe=0;                       // high low timeframe
int periods=7;                           // highest/lowest on the last x periods
bool sdlstops=false;                     // dynamic stops based on slope direction line
int sdltimeframe=0;                      // timeframe of the sdl
int sdlperiod=15;                        // period of the sdl
int sdlmethod=3;                         // method of the sdl
int sdlprice=0;                          // price of the sdl

extern string entrylogics="Entry Logics";

extern int rsiperiod=14;
extern bool envelopesfilter=true;
extern int envperiod=14;
bool exitrule=false;
extern int shift=1;                      // bar in the past to take in consideration for the signal

string timefilter="Time Filter";

bool usetimefilter=false;
int summergmtshift=0;                    // gmt offset of the broker
int wintergmtshift=0;                    // gmt offset of the broker
bool mondayfilter=false;                 // enable special time filter on friday
int mondayhour=12;                       // start to trade after this hour
int mondayminute=0;                      // minutes of the friday hour
bool weekfilter=false;                   // enable time filter
int starthour=7;                         // start hour to trade after this hour
int startminute=0;                       // minutes of the start hour
int endhour=21;                          // stop to trade after this hour
int endminute=0;                         // minutes of the start hour
bool tradesunday=true;                   // trade on sunday
bool fridayfilter=false;                 // enable special time filter on friday
int fridayhour=12;                       // stop to trade after this hour
int fridayminute=0;                      // minutes of the friday hour

string newsfilters="News Filter";

bool newsfilter=false;                   // we stop to enter trades during news
//bool backtesting=false;                // backtesting doesn't consider impact level
int minutesbefore=30;                    // minutes to consider before the news to stop trading
int minutesafter=30;                     // minutes to consider after the news to stop trading
bool impacthigh=false;                   // consider impact high
bool impactmedium=false;                 // consider impact medium
bool impactlow=false;                    // consider impact low

string timeout="Time Outs and Targets";

bool usetimeout=false;                   // we close the order if after timeout minutes we are > target pips
int timeout1=30;                         // time out 1
int target1=7;                           // target 1
int timeout2=70;                         // time out 2
int target2=5;                           // target 2
int timeout3=95;                         // time out 3
int target3=4;                           // target 3
int timeout4=120;                        // time out 4
int target4=2;                           // target 4
int timeout5=150;                        // time out 5
int target5=-5;                          // target 5
int timeout6=180;                        // time out 6
int target6=-8;                          // target 6
int timeout7=210;                        // time out 7
int target7=-15;                         // target 7

//+----------------------------------------------------------------------------+ INTERNAL PARAMETERS +----------------+

bool closebasket=false,continuebuy=true,continuesell=true;
int i,bc=-1,tpb,tps,tries=100,lastorder,buyorderprofit,sellorderprofit,lotsize,losses,sleep,xmartingalemode=0,mstop,
nstarthour,nnewshour,nendhour,nfridayhour,nmondayhour,number,ticket,gmtshift,expire,tradehour,consloss=0,total,
totalbuy,totalsell,totalstopbuy,totalstopsell,totallimitbuy,totallimitsell,oldestlong,oldestshort,handle,csvdatetime;
double dg,cb,sl,tp,blots,slots,lastbuylot,lastselllot,lastlot,lastprofit,mlots,win[14],sum[14],totalpips,totalprofit,
percentprofit,percentloss,fibo[20],lastbuyopenprice,lastsellopenprice,lastbuyprofit,lastsellprofit,tradeprofit,
buyorderpips,sellorderpips,lossestorecover=0,globallosses,initialbar=0,baskettrailstart,baskettrailstop,
ibaskettrailstart,ibaskettrailstop,pt,mt,initialaccount;
string istarthour,istartminute,iendhour,iendminute,ifridayhour,ifridayminute,imondayhour,imondayminute,closestatus,
date,csvdate,csvmonth,csvday,csvhour,csvcurrency,cur1,cur2,sig="",flag="",stat="",fail="",err="",exit="";
datetime timeset,timesetx,tstart,tend,tfriday,tmonday,lastbuyopentime,tnews,lastsellopentime,time,time2,time3,time4,
time5,time6,time7,lastorderclosetime,alerttime,newstime,daytime;

//+---------------------------------------------------------------------------------+ INITIALIZATION +----------------+

int init(){
   initialaccount=AccountBalance();
   if(baskettrailing){
      GlobalVariableSet("baskettrailstart",0);
      GlobalVariableSet("baskettrailstop",0);
      if(basketoptimization>0){
         baskettrailingstart=basketoptimization;
         baskettrailingstop=-1*basketoptimization;
      }
      if(mm==false){
         baskettrailstart=AccountBalance()*baskettrailingstart*0.01;
         baskettrailstop=AccountBalance()*baskettrailingstop*0.01;
      }      
   }
   if(fibomartingale){
      fibo[0]=1;fibo[1]=1;fibo[2]=2;fibo[3]=3;fibo[4]=5;fibo[5]=8;fibo[6]=13;fibo[7]=21;
      fibo[8]=34;fibo[9]=55;fibo[10]=89;fibo[11]=144;fibo[12]=233;fibo[13]=377;fibo[14]=610;
      fibo[15]=987;fibo[16]=1597;fibo[17]=2584;fibo[18]=4181;fibo[19]=6765;fibo[20]=10946;
   }
   if(usetimefilter){
      sum[2012-1999]=D'2012.03.28 02:00:00';win[2012-1999]=D'2012.10.31 03:00:00';
      sum[2011-1999]=D'2011.03.29 02:00:00';win[2011-1999]=D'2011.10.25 03:00:00';
      sum[2010-1999]=D'2010.03.30 02:00:00';win[2010-1999]=D'2010.10.26 03:00:00';
      sum[2009-1999]=D'2009.03.29 02:00:00';win[2009-1999]=D'2009.10.25 03:00:00';
      sum[2008-1999]=D'2008.03.30 02:00:00';win[2008-1999]=D'2008.10.26 03:00:00';
      sum[2007-1999]=D'2007.03.25 02:00:00';win[2007-1999]=D'2007.10.28 03:00:00';
      sum[2006-1999]=D'2006.03.26 02:00:00';win[2006-1999]=D'2006.10.29 03:00:00';
      sum[2005-1999]=D'2005.03.27 02:00:00';win[2005-1999]=D'2005.10.30 03:00:00';
      sum[2004-1999]=D'2004.03.28 02:00:00';win[2004-1999]=D'2004.10.31 03:00:00';
      sum[2003-1999]=D'2003.03.30 02:00:00';win[2003-1999]=D'2003.10.26 03:00:00';
      sum[2002-1999]=D'2002.03.31 02:00:00';win[2002-1999]=D'2002.10.27 03:00:00';
      sum[2001-1999]=D'2001.03.25 02:00:00';win[2001-1999]=D'2001.10.28 03:00:00';
      sum[2000-1999]=D'2000.03.26 02:00:00';win[2000-1999]=D'2000.10.29 03:00:00';
      sum[1999-1999]=D'1999.03.28 02:00:00';win[1999-1999]=D'1999.10.31 03:00:00';
   }
   dg=Digits;
   if(dg==3 || dg==5){
      pt=Point*10;
      mt=10;
   }else{
      pt=Point;
      mt=1;
   }
   if(stop>0){
      stoploss=stop;
      takeprofit=stop;
   }
   if(mm){
      if(minlot>=1){lotsize=100000;}
      if(minlot<1){lotsize=10000;}
      if(minlot<0.1){lotsize=1000;}
   }
   initialbar=Open[0];
   return(0);
}

//+------------------------------------------------------------------------------------------+ START +---------------+

int start(){

//+-----------------------------------------------------------------------------------+ RANDOM MAGIC +---------------+

   if(randommagic && daytime!=iTime(NULL,1440,0)){
      MathSrand(TimeLocal());
      magic=MathRand();
      daytime=iTime(NULL,1440,0);
   }  

//+-----------------------------------------------------------------------------+ EXTRA OPTIMIZATION +---------------+

   //if(IsTesting())
      //if(AccountEquity()ticks)return(0);

//+----------------------------------------------------------------------------------+ WAIT MIN DATA +---------------+

   if(Bars<100){
      if(useprint)Print("Bars less than 100");
      return(0);
   }

//+-----------------------------------------------------------------------------------+ BASKET TRAIL +---------------+

   if(baskettrailing){
      if(GlobalVariableGet("baskettrailstart")==0)
         GlobalVariableSet("baskettrailstart",AccountBalance()*(1+baskettrailingstart*0.01));
      if(mm==true && AccountEquity()>=GlobalVariableGet("baskettrailstart")){
         GlobalVariableSet("baskettrailstart",AccountEquity()*(1+baskettrailingstart*0.01));
         GlobalVariableSet("baskettrailstop",AccountEquity()*(1+baskettrailingstop*0.01));
      }
      if(ibaskettrailstart==0)ibaskettrailstart=AccountBalance()+baskettrailstart;
      if(mm==false && AccountEquity()>=ibaskettrailstart){
         ibaskettrailstart=AccountEquity()+baskettrailstart;
         ibaskettrailstop=AccountEquity()-baskettrailstop;
      }
      if(mm==true && AccountEquity()<=GlobalVariableGet("baskettrailstop")){
         close(3);
         idelete(6);
         GlobalVariableSet("baskettrailstop",0);
         GlobalVariableSet("baskettrailstart",AccountBalance()*(1+baskettrailingstart*0.01));
      }
      if(mm==false && AccountEquity()<=ibaskettrailstop){
         close(3);
         idelete(6);
         ibaskettrailstop=0;
         ibaskettrailstart=AccountBalance()+baskettrailstart;
      }
   }

//+------------------------------------------------------------------------------------+ INITIAL BAR +---------------+

   if(ignoreinitialbar)if(initialbar==Open[0])return(0);

//+-----------------------------------------------------------------------------------+ COUNT TRADES +---------------+

   if(closebasket || addpositions || onesideatatime || onecancelother || maxtrades<100 || martingale){
      totalbuy=count(OP_BUY);
      totalsell=count(OP_SELL);
      total=totalbuy+totalsell;
      if(closebasket){
         totalstopbuy=count(OP_BUYSTOP);
         totalstopsell=count(OP_SELLSTOP);
         totallimitbuy=count(OP_BUYLIMIT);
         totallimitsell=count(OP_SELLLIMIT);
      }
   }

//+-----------------------------------------------------------------------------------+ BASKET CLOSE +---------------+

   if(closebasket)
      if(total+totalstopbuy+totalstopsell+totallimitbuy+totallimitsell>0){
         close(3);
         idelete(6);
      }
   if(closebasket)
      if(total+totalstopbuy+totalstopsell+totallimitbuy+totallimitsell==0)closebasket=false;
   if(closebasket)return(0);

//+----------------------------------------------------------------------------------+ VISUAL EQUITY +---------------+
//| You need the indicator vGrafBalance&Equity.mq4

   if(visualequity){
      GlobalVariableSet("vGrafBalance",AccountBalance());
      GlobalVariableSet("vGrafEquity",AccountEquity());
   }

//+----------------------------------------------------------------------------+ TRADES MODIFICATION +---------------+

   if(breakevengain>0)movebreakeven(breakevengain,breakeven);
   if(trailingstop>0)movetrailingstop(trailingstopmode,trailingstart,trailingstop);
   if(trailing>0)movetrailingstop(0,trailing,trailing);
   if(trailingprofit>0)movetrailingprofit(trailingstart,trailingprofit);

//+------------------------------------------------------------------------------------+ TRADES DATA +---------------+

   if(basketpercent || basketdollars || xmartingalemode==1){
      buyorderprofit=0;
      sellorderprofit=0;
   }
   if(basketpips){
      buyorderpips=0;
      sellorderpips=0;
   }
   if(oppositeclose){
      oldestlong=0;
      oldestshort=0;
   }
   lastbuyopenprice=0;lastsellopenprice=0;

   if(OrdersTotal()>0){
      for(i=0;iOrderOpenTime())oldestlong=OrderOpenTime();
               lastbuyopentime=OrderOpenTime();
               if(addpositions)lastbuyopenprice=OrderOpenPrice();
               if(basketpercent || basketdollars || xmartingalemode==1)buyorderprofit=buyorderprofit+OrderProfit();
               if(basketpips)buyorderpips=buyorderpips+(OrderClosePrice()-OrderOpenPrice())/pt-MarketInfo(Symbol(),MODE_SPREAD);
            }
            if(OrderType()==OP_SELL){
               if(oppositeclose)if(oldestlong==0 || oldestshort>OrderOpenTime())oldestshort=OrderOpenTime();
               lastsellopentime=OrderOpenTime();
               if(addpositions)lastsellopenprice=OrderOpenPrice();
               if(basketpercent || basketdollars || xmartingalemode==1)sellorderprofit=sellorderprofit+OrderProfit();
               if(basketpips)sellorderpips=sellorderpips+(OrderOpenPrice()-OrderClosePrice())/pt-MarketInfo(Symbol(),MODE_SPREAD);
            }
         }
      }
   }
   if(basketpercent || basketdollars || xmartingalemode==1)totalprofit=buyorderprofit+sellorderprofit;
   if(basketpips)totalpips=buyorderpips+sellorderpips;

//+------------------------------------------------------------------------------------+ BASKET CORE +---------------+

   if(basketpercent){
      percentprofit=AccountBalance()*profit*0.01;
      percentloss=-1*AccountBalance()*loss*0.01;
      if((mm && totalprofit>=(AccountBalance()*profit*0.01)) || (mm==false && totalprofit>=percentprofit) || (mm && totalprofit<=(-1*AccountBalance()*loss*0.01))|| (mm==false && totalprofit<=percentloss))closebasket=true;
   }
   if(basketpips)if((totalpips>=profitpips) || (totalpips<=(-1*losspips)))closebasket=true;
   if(basketdollars)if(totalprofit>=dollars)closebasket=true;
   if(closebasket)return(0);

//+-------------------------------------------------------------------------------------+ SLEEP CORE +---------------+

   bool nosleep=true;
   if(sleepafterxlosses && OrdersHistoryTotal()>0){
      losses=0;sleep=0;
      for(i=OrdersHistoryTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
            if(OrderProfit()>=0)sleep=1;
            if(OrderProfit()<0 && sleep==0){losses++;}
         }
      }
      for(i=0;i=xlosses)lastorderclosetime=OrderCloseTime();
         }
      }
      if(TimeCurrent()-lastorderclosetimema)exitsignal=2;

      int signal1=0,signal2=0;
      if(exitsignal1!=1
      && rsi>50 && rsia<50
      && (envelopesfilter==false || (envelopesfilter && Ask>envu))
      && IsTradeContextBusy()==false){
         signal1=1;
      }
      if(exitsignal2!=2
      && rsi<50 && rsia>50
      && (envelopesfilter==false || (envelopesfilter && Bid0 && ma!=EMPTY_VALUE)signal=1;

      if(tradesperbar==1)
         if(signal1==0 && signal2==0){sig="NONE";flag="NONE";}
      if(signal1!=0)dynamics(signal1);
      if(signal2!=0)dynamics(signal2);

   //Comment("\nhau = "+DoubleToStr(hau,5),"\nhad = "+DoubleToStr(had,5));

//+------------------------------------------------------------------------------------+ TIME FILTER +---------------+

   bool tradetime=true;
   if(usetimefilter)if(checktime())tradetime=false;

//+------------------------------------------------------------------------------------+ NEWS FILTER +---------------+

   bool newsstatus=true;
   if(newsfilter)if(checknews())newsstatus=false;

//+--------------------------------------------------------------------------------------+ DIRECTION +---------------+

   if(changedirection)if(initialbar==Open[0]){
      if(OrdersHistoryTotal()>0){
         OrderSelect(OrdersHistoryTotal(),SELECT_BY_POS,MODE_HISTORY);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
            if(OrderType()==OP_BUY){
               continuebuy=false;
               continuesell=true;
            }
            if(OrderType()==OP_SELL){
               continuebuy=true;
               continuesell=false;
            }
         }
      }
   }

//+--------------------------------------------------------------------------------+ OPEN MARTINGALE +---------------+

   bool buy=false;
   bool sell=false;

   bool buyaddstatus=true;bool selladdstatus=true;
   if(addpositions){
      if(totalbuy>0)buyaddstatus=false;
      if(totalsell>0)selladdstatus=false;
      if(totalbuy>0){
         if((addposmode==0 && Ask<=lastbuyopenprice-pipstep*pt*MathPow(pipstepfactor,totalbuy)) || (addposmode==1 && Ask>=lastbuyopenprice+pipstep*pt*MathPow(pipstepfactor,totalbuy)) && (signalfilter==false || (signalfilter && signal1==1)))buy=true;
      }
      if(totalsell>0){
         if((addposmode==0 && Bid>=lastsellopenprice+pipstep*pt*MathPow(pipstepfactor,totalsell)) || (addposmode==1 && Bid<=lastsellopenprice-pipstep*pt*MathPow(pipstepfactor,totalsell)) && (signalfilter==false || (signalfilter && signal2==2)))sell=true;
      }
   }

//+----------------------------------------------------------------------------------+ TRADING BOARD +---------------+

   bool buyside=true;bool sellside=true;
   if(onesideatatime){if(totalsell>0)buyside=false;if(totalbuy>0)sellside=false;}

   if(signal1==1 && buyaddstatus && buyside && continuebuy && tradetime && newsstatus && nosleep){
      if(reversesignals)sell=true;
      else buy=true;
      if(changedirection){
         continuebuy=false;
         continuesell=true;
      }
      if(checkclose)
         if(reversesignals)closestatus="SHORT";
         else closestatus="LONG";
      if(tradesperbar==1){
         if(reversesignals)flag="WE SELL";
         else flag="WE BUY";
         if(timesetxoldestshort && oldestshort!=0)close(OP_SELL);
      if(partialexit==false && oldestshort>oldestlong && oldestlong!=0)close(OP_BUY);
   }
   if(hidetp || hidesl)hideclose();
   if(onecancelother){
      if(totalsell>0)idelete(7);
      if(totalbuy>0)idelete(8);
   }
   if(partialclose){
      partialclose2(3,0,blots,blots*tp2percentage*0.01,takeprofit2);
      partialclose2(3,0,blots-(blots*tp2percentage*0.01),blots*tp3percentage*0.01,takeprofit3);
   }
   if(xmartingalemode==1 && totalprofit>=-1*lossestorecover)close(3);
   if(usetimeout){
      closetime(0,target1,timeout1,timeout2);
      closetime(0,target2,timeout2,timeout3);
      closetime(0,target3,timeout3,timeout4);
      closetime(0,target4,timeout4,timeout5);
      closetime(0,target5,timeout5,timeout6);
      closetime(0,target6,timeout6,timeout7);
      closetime(1,target7,timeout7,0);
   }
   if(exitsignal1==1)if(reversesignals)close(OP_SELL);else close(OP_BUY);
   if(exitsignal2==2)if(reversesignals)close(OP_BUY);else close(OP_SELL);

//+------------------------------------------------------------------------------+ CLOSED MARTINGALE +---------------+

   xmartingalemode=0;
   if(martingale && !addpositions){
      globallosses=0;
      lossestorecover=0;

      if(OrdersHistoryTotal()>0){
         for(i=0;i<=OrdersHistoryTotal();i++){
            OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
               lastprofit=OrderProfit();
               lastlot=OrderLots();
            }
         }
      }
      mlots=0;
      if(lastprofit<0){
         mstop=0;
         if(OrdersHistoryTotal()>0){
            for(i=OrdersHistoryTotal();i>=0;i--){
               OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
               if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
                  if(OrderProfit()>0)mstop=1;
                  if(mstop==0)globallosses=globallosses+OrderProfit();
               }
            }
         }
         mlots=lastlot*multiplier;
         if(martingalemode==1)xmartingalemode=1;
         lossestorecover=nd(globallosses*0.01*percentrecovering,2);
      }
      else mlots=lots;
   }

//+---------------------------------------------------------------------------------------+ MAX AREA +---------------+

   if(maxspread!=0)if((Ask-Bid)>maxspread*pt)return(0);
   if(maxtrades<100)if((total)>=maxtrades)return(0);

//+--------------------------------------------------------------------------------+ MARTINGALE CORE +---------------+
//|  Martingale : You can set a closed martingale : martingale=true, maxtrades=1,basketpercent or basketpips=true.
//|  Or an open martingale : martingale=true,tradesperbar=100, basketpercent or basketpips=true, addpositions=true.

   if(mm)
      if(martingale==false || (martingale && !addpositions && lastprofit>=0) || (martingale && addpositions))lots=lotsoptimized();
   if(fibomartingale && OrdersHistoryTotal()>0){
      consloss=0;
      for(i=OrdersHistoryTotal();i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
            if(OrderProfit()>0)break;
            if(OrderProfit()<0)consloss=consloss+1;
         }
      }
      blots=lots*fibo[consloss];
      slots=lots*fibo[consloss];
   }
   else{
      blots=lots;
      slots=lots;
   }
   if(martingale){
      if(addpositions){
         blots=lots*MathPow(multiplier,totalbuy);
         slots=lots*MathPow(multiplier,totalsell);
      }
      else {blots=mlots;slots=mlots;}
   }

//+------------------------------------------------------------------------------------+ TICKET CORE +---------------+

   if(buy && !onlysell && tpb0)expire=TimeCurrent()+(expiration*60)-5;
      if(!ecn){
         if(instantorders){
            if(xmartingalemode==0){
               while(ticket<=0 && number0)expire=TimeCurrent()+(expiration*60)-5;
      if(!ecn){
         if(instantorders){
            if(xmartingalemode==0){
               while(ticket<=0 && number0 || tpb>0)stat="ORDER OPENED";
         if(tps==0 && tpb==0)stat="ORDER NOT YET OPENED";
         if(signal!=0 && tps==0 && tpb==0 && TimeCurrent()>timeset && timeset!=0)fail="OPENING FAILED";
         else fail="NONE";
         err=ErrorDescription(GetLastError());
         Comment(
            "\nsignal = "+sig,
            "\nflag = "+flag,
            "\nstatus = "+stat,
            "\nexit = "+exit,
            "\n\nfailure = "+fail,
            "\nlast error = "+err,
            "\n\ntimeset = "+timeset,
            "\ntimesetx = "+timesetx);
      }*/
   return(0);
}

//+-------------------------------------------------------------------------------+ COUNTER FUNCTION +---------------+

int count(int type){
   int cnt=0;
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()==Symbol() && OrderType()==type && OrderMagicNumber()==magic)cnt++;
      }
      return(cnt);
   }
}

//+----------------------------------------------------------------------------------+ OPEN FUNCTION +---------------+

int open(int type,double lots,double price,double stoploss,double takeprofit,int expire,color clr){
   int ticket=0;
   if(lotsmaxlot)lots=maxlot;
   if(type==OP_BUY || type==OP_BUYSTOP || type==OP_BUYLIMIT){
      if(hidesl==false && stoploss>0)sl=price-stoploss*pt;
      else sl=0;
      if(hidetp==false && takeprofit>0)tp=price+takeprofit*pt;
      else tp=0;
   }
   if(type==OP_SELL || type==OP_SELLSTOP || type==OP_SELLLIMIT){
      if(hidesl==false && stoploss>0)sl=price+stoploss*pt;
      else sl=0;
      if(hidetp==false && takeprofit>0)tp=price-takeprofit*pt;
      else tp=0;
   }
   ticket=OrderSend(Symbol(),type,nd(lots,lotdigits),nd(price,dg),slippage*mt,sl,tp,comment+" "+DoubleToStr(magic,0),magic,expire,clr);
   return(ticket);
}

//+------------------------------------------------------------------------------------+ MM FUNCTION +---------------+

double lotsoptimized(){
   double lot;
   if(stoploss>0)
      lot=AccountBalance()*(risk/100)/(stoploss*pt/MarketInfo(Symbol(),MODE_TICKSIZE)*
      MarketInfo(Symbol(),MODE_TICKVALUE));
   else lot=nd((AccountBalance()/lotsize)*0.01*risk,lotdigits);
   return(lot);
}

//+---------------------------------------------------------------------------------+ CLOSE FUNCTION +---------------+

void close(int type){
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(type==3 || type==OP_BUY && OrderType()==OP_BUY){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && (oppositecloseminloss==0 || (oppositecloseminloss>0 && (OrderClosePrice()-OrderOpenPrice())<-1*oppositecloseminloss*pt))){
               RefreshRates();
               OrderClose(OrderTicket(),OrderLots(),nd(Bid,dg),slippage*mt);
            }
         }
         if(type==3 || type==OP_SELL && OrderType()==OP_SELL){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && (oppositecloseminloss==0 || (oppositecloseminloss>0 && (OrderOpenPrice()-OrderClosePrice())<-1*oppositecloseminloss*pt))){
               RefreshRates();
               OrderClose(OrderTicket(),OrderLots(),nd(Ask,dg),slippage*mt);
            }
         }
      }
   }
}

//+-------------------------------------------------------------------------+ PARTIAL CLOSE FUNCTION +---------------+

void partialclose(int type,int mode,double lot,double takeprofit){
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(type==3 || type==OP_BUY && OrderType()==OP_BUY){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderLots()>=lot && (mode==0 && OrderClosePrice()-OrderOpenPrice()>=takeprofit*pt) || mode==1){
               RefreshRates();
               OrderClose(OrderTicket(),nd(lot,lotdigits),nd(Bid,dg),slippage*mt);
            }
         }
         if(type==3 || type==OP_SELL && OrderType()==OP_SELL){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderLots()>=lot && (mode==0 && OrderOpenPrice()-OrderClosePrice()>=takeprofit*pt) || mode==1){
               RefreshRates();
               OrderClose(OrderTicket(),nd(lot,lotdigits),nd(Ask,dg),slippage*mt);
            }
         }
      }
   }
}

//+-----------------------------------------------------------------------+ PARTIAL CLOSE FUNCTION 2 +---------------+

void partialclose2(int type,int mode,double lot1,double lot2,double takeprofit){
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(type==3 || type==OP_BUY && OrderType()==OP_BUY){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderLots()==nd(lot1,lotdigits) && (mode==0 && OrderClosePrice()-OrderOpenPrice()>=takeprofit*pt) || mode==1){
               RefreshRates();
               OrderClose(OrderTicket(),nd(lot2,lotdigits),nd(Bid,dg),slippage*mt);
            }
         }
         if(type==3 || type==OP_SELL && OrderType()==OP_SELL){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderLots()==nd(lot1,lotdigits) && (mode==0 && OrderOpenPrice()-OrderClosePrice()>=takeprofit*pt) || mode==1){
               RefreshRates();
               OrderClose(OrderTicket(),nd(lot2,lotdigits),nd(Ask,dg),slippage*mt);
            }
         }
      }
   }
}

//+----------------------------------------------------------------------------+ HIDE CLOSE FUNCTION +---------------+

void hideclose(){
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderType()==OP_BUY){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && (hidesl && stoploss>0 && nd(OrderClosePrice()-OrderOpenPrice(),dg)<=(-1)*stoploss*pt-MarketInfo(Symbol(),MODE_SPREAD)*pt) || (hidetp && takeprofit>0 && nd(OrderClosePrice()-OrderOpenPrice(),dg)>=takeprofit*pt)){
               RefreshRates();
               OrderClose(OrderTicket(),OrderLots(),Bid,slippage*mt);
            }
         }
         if(OrderType()==OP_SELL){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && (hidesl && stoploss>0 && nd(OrderOpenPrice()-OrderClosePrice(),dg)<=(-1)*stoploss*pt-MarketInfo(Symbol(),MODE_SPREAD)*pt) || (hidetp && takeprofit>0 && nd(OrderOpenPrice()-OrderClosePrice(),dg)>=takeprofit*pt)){
               RefreshRates();
               OrderClose(OrderTicket(),OrderLots(),Ask,slippage*mt);
            }
         }
      }
   }
}

//+----------------------------------------------------------------------------+ CLOSE TIME FUNCTION +---------------+

void closetime(int mode,double target,double timeout1,double timeout2){
   tradeprofit=0;
   tradehour=0;
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderType()==OP_BUY){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){ 
               tradeprofit=nd(OrderClosePrice()-OrderOpenPrice(),dg);
               tradehour=TimeCurrent()-OrderOpenTime();
               if((mode==0 && tradeprofit>=target*pt && tradehour>timeout1*60 && tradehour=target*pt && tradehour>timeout1*60)){
                  RefreshRates();OrderClose(OrderTicket(),OrderLots(),Bid,slippage*mt);
               }
            }
         }
         if(OrderType()==OP_SELL){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){ 
               tradeprofit=nd(OrderOpenPrice()-OrderClosePrice(),dg);
               tradehour=TimeCurrent()-OrderOpenTime();
               if((mode==0 && tradeprofit>=target*pt && tradehour>timeout1*60 && tradehour=target*pt && tradehour>timeout1*60)){
                  RefreshRates();OrderClose(OrderTicket(),OrderLots(),Ask,slippage*mt);
               }
            }
         }
      }
   }
}

//+--------------------------------------------------------------------------------+ DELETE FUNCTION +---------------+

void idelete(int type){
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(type!=6 && type!=7 && type!=8)
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==type)OrderDelete(OrderTicket());
         if(type==6)
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP || OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT)OrderDelete(OrderTicket());
         if(type==7)
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUYSTOP || OrderType()==OP_BUYLIMIT)OrderDelete(OrderTicket());
         if(type==8)
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_SELLSTOP || OrderType()==OP_SELLLIMIT)OrderDelete(OrderTicket());
      }
   }
}

//+-------------------------------------------------------------------------+ TRAILING STOP FUNCTION +---------------+

void movetrailingstop(int mode,double trailingstart,double trailingstop){
   RefreshRates();
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(mode==0){
            if(OrderType()<=OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
               if(OrderType()==OP_BUY){
                  if(nd(Ask,dg)>nd(OrderOpenPrice()+trailingstart*pt,dg) && nd(OrderStopLoss(),dg)(nd(Ask+(trailingstop+trailingstep)*pt,dg))) || (OrderStopLoss()==0)){                 
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(Ask+trailingstop*pt,dg),OrderTakeProfit(),0,Red);
                     return(0);
                  }
               }
            }
         }
         if(mode==1){
            if(OrderType()<=OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
               if(OrderType()==OP_BUY && OrderStopLoss()==0){
                  if(nd(Ask,dg)>=nd(OrderOpenPrice()+trailingstart*pt,dg)){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(Ask-trailingstop*pt,dg),OrderTakeProfit(),0,Blue);
                     return(0);
                  }
               }
               if(OrderType()==OP_BUY && OrderStopLoss()!=0){
                  if(nd(Ask,dg)>=nd(OrderOpenPrice()+trailingstart*pt,dg) && nd(Ask,dg)>=nd(OrderStopLoss()+trailingstart*pt,dg)){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(OrderStopLoss()+trailingstop*pt,dg),OrderTakeProfit(),0,Blue);
                     return(0);
                  }
               }
               if(OrderType()==OP_SELL && OrderStopLoss()==0){
                  if(nd(Bid,dg)<=nd(OrderOpenPrice()-trailingstart*pt,dg)){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(Bid+trailingstop*pt,dg),OrderTakeProfit(),0,Red);
                     return(0);
                  }
               }
               if(OrderType()==OP_SELL && OrderStopLoss()!=0){
                  if(nd(Bid,dg)<=nd(OrderOpenPrice()-trailingstart*pt,dg)&& nd(Bid,dg)<=nd(OrderStopLoss()-trailingstart*pt,dg)){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(OrderStopLoss()-trailingstop*pt,dg),OrderTakeProfit(),0,Red);
                     return(0);
                  }
               }
            }
         }
      }
   }
}

//+-----------------------------------------------------------------------+ TRAILING PROFIT FUNCTION +---------------+

void movetrailingprofit(double trailingstart,double trailingprofit){
   RefreshRates();
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
            if(OrderSymbol()==Symbol()&& OrderMagicNumber()==magic){
               if(OrderType()==OP_BUY){
                  if(nd(Bid-OrderOpenPrice(),dg)<=nd((-1)*trailingstart*pt,dg)){
                     if(nd(OrderTakeProfit(),dg)>nd(Bid+(trailingprofit+trailingstep)*pt,dg) || nd(OrderTakeProfit(),dg)==0){
                        OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),nd(Bid+trailingprofit*pt,dg),0,Blue);
                     }
                  }
               }
               if(OrderType()==OP_SELL){
                  if(nd(OrderOpenPrice()-Ask,dg)<=nd((-1)*trailingstart*pt,dg)){
                     if(nd(OrderTakeProfit(),dg)0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderType()<=OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
            if(OrderType()==OP_BUY){
               if(nd((Bid-OrderOpenPrice()),dg)>=nd(breakevengain*pt,dg)){
                  if((nd((OrderStopLoss()-OrderOpenPrice()),dg)=nd(breakevengain*pt,dg)){
                  if((nd((OrderOpenPrice()-OrderStopLoss()),dg)0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
            if(OrderType()==OP_BUY){
               if(OrderStopLoss()==0 && stoploss>0 && takeprofit==0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),nd(Ask-stoploss*pt,dg),OrderTakeProfit(),0,Red);
               }
               if(OrderTakeProfit()==0 && stoploss==0 && takeprofit>0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),nd(Ask+takeprofit*pt,dg),0,Red);
               }
               if(OrderTakeProfit()==0 && OrderStopLoss()==0 && stoploss>0 && takeprofit>0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),nd(Ask-stoploss*pt,dg),nd(Ask+takeprofit*pt,dg),0,Red);
               }
            }
            if(OrderType()==OP_SELL){
               if(OrderStopLoss()==0 && stoploss>0 && takeprofit==0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),nd(Bid+stoploss*pt,dg),OrderTakeProfit(),0,Red);
               }
               if(OrderTakeProfit()==0 && stoploss==0 && takeprofit>0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),nd(Bid-takeprofit*pt,dg),0,Red);
               }
               if(OrderTakeProfit()==0 && OrderStopLoss()==0 && stoploss>0 && takeprofit>0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),nd(Bid+stoploss*pt,dg),nd(Bid-takeprofit*pt,dg),0,Red);
               }
            }
         }
      }
   }
}

//+------------------------------------------------------------------------------+ DYNAMICS FUNCTION +---------------+

void dynamics(int signal){

   if(atrstops)double atr=iATR(NULL,atrtimeframe,atrperiod,shift);
   if(highlowstops || highlowtrail){
      double hlhigh=iHigh(NULL,hltimeframe,iHighest(NULL,0,MODE_HIGH,periods,1));
      double hllow=iLow(NULL,hltimeframe,iLowest(NULL,0,MODE_LOW,periods,1));
   }
   if(sdlstops){
      int sdlbar1=0;
      for(i=0;i<=100;i++){
         if(sdlbar1!=0)continue;
         if(iCustom(NULL,sdltimeframe,"Slope Direction Line",sdlperiod,sdlmethod,sdlprice,2,i)>iCustom(NULL,sdltimeframe,"Slope Direction Line",sdlperiod,sdlmethod,sdlprice,2,i+1) && iCustom(NULL,sdltimeframe,"Slope Direction Line",sdlperiod,sdlmethod,sdlprice,2,i+1)iCustom(NULL,sdltimeframe,"Slope Direction Line",sdlperiod,sdlmethod,sdlprice,2,i+2))sdlbar2=i;
      }
   }
   if(atrstops){
      if(signal!=0 && slfactor!=0)stoploss=(atr/pt)*slfactor+slmargin;
      if(signal!=0 && tpfactor!=0)takeprofit=(atr/pt)*tpfactor+slmargin;
      if(signal!=0 && tstfactor!=0)trailingstart=(atr/pt)*tstfactor;
      if(signal!=0 && tsfactor!=0)trailingstop=(atr/pt)*tsfactor;
      if(signal!=0 && begfactor!=0)breakevengain=(atr/pt)*begfactor;
      if(signal!=0 && befactor!=0)breakeven=(atr/pt)*befactor;
      if(signal!=0 && psfactor!=0)pipstep=(atr/pt)*psfactor;
      if(signal!=0 && gfactor!=0)gap=(atr/pt)*gfactor;
   }
   if(highlowstops){
      if(signal==1 && slfactor!=0)stoploss=((Ask-hllow)/pt)*slfactor+slmargin;
      if(signal==1 && tpfactor!=0)takeprofit=((hlhigh-Bid)/pt)*tpfactor;
      if(signal==2 && slfactor!=0)stoploss=((hlhigh-Bid)/pt)*slfactor+slmargin;
      if(signal==2 && tpfactor!=0)takeprofit=((Ask-hllow)/pt)*tpfactor;
   }
   if(highlowtrail){
      if(signal==1 && tstfactor!=0)trailingstart=((Ask-hllow)/pt)*tstfactor;
      if(signal==1 && tsfactor!=0)trailingstop=((Ask-hllow)/pt)*tsfactor;
      if(signal==2 && tstfactor!=0)trailingstart=((hlhigh-Bid)/pt)*tstfactor;
      if(signal==2 && tsfactor!=0)trailingstop=((hlhigh-Bid)/pt)*tsfactor;
   }
   if(sdlstops){
      if(signal==1 && slfactor!=0)stoploss=((Ask-Low[sdlbar1])/pt)*slfactor+slmargin;
      if(signal==1 && tpfactor!=0)takeprofit=((High[sdlbar2]-Bid)/pt)*tpfactor;
      if(signal==2 && slfactor!=0)stoploss=((High[sdlbar2]-Bid)/pt)*slfactor+slmargin;
      if(signal==2 && tpfactor!=0)takeprofit=((Ask-Low[sdlbar1])/pt)*tpfactor;
   }
   if(atrstops || highlowstops || sdlstops){
      if(stoplosssum[TimeYear(TimeCurrent())-1999])gmtshift=summergmtshift;
   else gmtshift=wintergmtshift;

   string svrdate=Year()+"."+Month()+"."+Day();

   if(mondayfilter){
      nmondayhour=mondayhour+(gmtshift);if(nmondayhour>23)nmondayhour=nmondayhour-24;
      if(nmondayhour<10)imondayhour="0"+nmondayhour;
      if(nmondayhour>9)imondayhour=nmondayhour;
      if(mondayminute<10)imondayminute="0"+mondayminute;
      if(mondayminute>9)imondayminute=mondayminute;
      tmonday=StrToTime(svrdate+" "+imondayhour+":"+imondayminute);
   }
   if(weekfilter){
      nstarthour=starthour+(gmtshift);if(nstarthour>23)nstarthour=nstarthour-24;
      if(nstarthour<10)istarthour="0"+nstarthour;
      if(nstarthour>9)istarthour=nstarthour;
      if(startminute<10)istartminute="0"+startminute;
      if(startminute>9)istartminute=startminute;
      tstart=StrToTime(svrdate+" "+istarthour+":"+istartminute);

      nendhour=endhour+(gmtshift);if(nendhour>23)nendhour=nendhour-24;
      if(nendhour<10)iendhour="0"+nendhour;
      if(nendhour>9)iendhour=nendhour;
      if(endminute<10)iendminute="0"+endminute;
      if(endminute>9)iendminute=endminute;
      tend=StrToTime(svrdate+" "+iendhour+":"+iendminute);
   }
   if(fridayfilter){
      nfridayhour=fridayhour+(gmtshift);if(nfridayhour>23)nfridayhour=nfridayhour-24;
      if(nfridayhour<10)ifridayhour="0"+nfridayhour;
      if(nfridayhour>9)ifridayhour=nfridayhour;
      if(fridayminute<10)ifridayminute="0"+fridayminute;
      if(fridayminute>9)ifridayminute=fridayminute;
      tfriday=StrToTime(svrdate+" "+ifridayhour+":"+ifridayminute);
   }
   if(weekfilter)if((nstarthour<=nendhour && TimeCurrent()tend) || (nstarthour>nendhour && TimeCurrent()tend))return(true);
   if(tradesunday==false)if(DayOfWeek()==0)return(true);
   if(fridayfilter)if(DayOfWeek()==5 && TimeCurrent()>tfriday)return(true);
   if(mondayfilter)if(DayOfWeek()==1 && TimeCurrent()0){
            while(FileIsEnding(handle)==false){
               if(FileIsEnding(handle))break;

               date=FileReadString(handle);
               csvdate=StringSubstr(date,1,4);
               csvmonth=StringSubstr(date,6,2);
               csvday=StringSubstr(date,9,2);
               csvhour=StringSubstr(date,14,5);
               csvcurrency=StringSubstr(date,24,3);
               csvdatetime=StrToTime(csvdate+"."+csvmonth+"."+csvday+" "+csvhour);
               cur1=StringSubstr(Symbol(),0,3);
               cur2=StringSubstr(Symbol(),3,3);

               if((csvdatetime-Time[0]>=0 && csvdatetime-Time[0]=0 && Time[0]-csvdatetime        

Recommend