TRUE Forex

Просмотр кода форекс советника Multi-Channel RSI Scalper v1.11.mq4

//+------------------------------------------------------------------------------------------------------------------+
//|                                                                                M04.D27.Y2011_Expert_Advisor.mq4  |
//|                                                   Copyright © 2008-2011, TradingSystemForex.Com - Elite Section  |
//|                                                                              http://www.tradingsystemforex.com/  |
//+------------------------------------------------------------------------------------------------------------------+

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

#include <stderror.mqh>
#include <stdlib.mqh>

//+--------------------------------------------------------------------------------+ 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 closeall=false;                     // close all orders
bool closebuy=false;                     // only close buy orders
bool closesell=false;                    // only close 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 recoverymode=false;                 // we multiply the lots size after closed losses
double recoverymultiplier=2;             // recovery multiplier
extern bool martingale=false;                   // enable the martingale, set maxtrades to 1
extern int martingalemode=0;                    // 0=don't use percentrecovering, 1=use percentrecovering
extern double multiplier=2.0;                   // multiplier used for the martingale
double percentrecovering=50.0;           // percentage of the last losses to recover
bool fibomartingale=false;               // enable the martingale with fibonacci progression
bool alembert=false;                      // alembert's martingale
int alembertmode=0;                     // 0=increment/decrement after a loss/profit, 1=decrement/increment after a loss/profit
double increment=1;                      // prev lots+lots*increment
double decrement=1;                      // prev lots-lots*increment

extern string profitmanagement="Profit Management";

extern bool basketpercent=false;                // enable the basket percent
extern double profitpercent=0.1;                // close all orders if a profit of 0.1 percents has been reached
extern double losspercent=100;                  // close all orders if a loss of 100 percents has been reached
extern bool basketpips=false;                   // enable the basket pips
extern double profitpips=10;                    // close all orders if a profit of 10 pips has been reached
extern double losspips=10000;                   // close all orders if a loss of 10000 pips has been reached
extern bool basketdollars=false;                // enable basket dollars
extern double profitdollars=5;                  // target in dollars
extern double lossdollars=10000;                // target in dollars
extern bool baskettrailpercent=false;           // basket trail in percent
extern int trailstartpercent=1;                 // trailstart percent
extern int trailstoppctpercent=50;              // percentage of trailstartpercent for stop
extern bool baskettrailpips=false;              // basket trail in pips
extern int trailstartpips=75;                   // trailstart pips
extern int trailstoppctpips=50;                 // percentage of trailstartpips for stop
extern bool baskettraildollars=false;           // basket trail in dollars
extern int trailstartdollars=5;                 // trailstart pips
extern int trailstoppctdollars=100;             // percentage of trailstartpips for 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 ddeleteold=false;                    // ddelete old pending orders
bool oppositeddelete=false;               // ddelete 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
extern int oppositecloseminloss=0;              // min loss to consider to enable opposite close
bool partialexit=false;                  // partial exit at opposite close
extern 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=500;                // 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
extern double takeprofit2=5;                    // takeprofit 2 to close a certain percentage of lots
extern double tp2percentage=50;                 // percentage of lots to close at takeprofit 2
extern double takeprofit3=20;                   // takeprofit 3 to close a certain percentage of lots
extern double tp3percentage=25;                 // percentage of lots to close at takeprofit 3
int trailingstopmode=0;                  // 0 new sl=price-/+ts, 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
extern bool addpositions=false;                 // add positions, set tradesperbar to 100
extern bool signalfilter=false;                 // signal filter for added positions
extern int addposmode=0;                        // 0=counter, 1=follow, 2=both
extern double pipstep=20;                       // minimum difference in pips between orders
extern double pipstepfactor=1.0;                // multiply the pipstep by the number of buy/sell orders
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
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
bool autots=false;                       // auto trailing stop
int autotsmargin=2;                      // auto trailing stop margin
bool autosl=false;                       // auto stoploss
int autosltf=0;                     // stoploss tf
int autoslperiod=10;                     // stoploss based on the high/low of the x last candles
bool autotp=false;                        // auto takeprofit
int autotptf=0;                     // takeprofit tf
int autotpperiod=10;                     // takeprofit based on the high/low of the x last candles

extern string entrylogics="Entry Logics";

extern bool range1=true;
extern int rangetimeframe1=0;
extern int candles1=2;
extern int distance=6;
extern int shift1=0;
extern bool range2=true;
extern int rangetimeframe2=0;
extern int candles2=7;
extern int margin=2;
extern int shift2=1;
extern bool rsifilter=true;
extern int rsitimeframe=30;
extern int rsiperiod=14;
extern int rsiprice=0;
extern int rsilevela=66;
extern int rsilevelb=26;
extern bool reverseontrend=false;        // enter buy instead of sell, sell instead of buy on damiani trend and that depending on the ma trend
extern int trendmaperiod=14;             // trend ma period to consider for the reverseontrend
extern int damianitimeframe=0;           // damiani timeframe
extern int visatr=13;                    // damiani atr
extern int visstd=20;                    // damiani std
extern int sedatr=40;                    // damiani atr
extern int sedstd=100;                   // damiani std
extern double thresholdlevel=1.4;        // threshold
extern int damianishift=1;               // damiani shift
extern int shift3=1;                      // bar in the past to take in consideration for the signal
bool exitrule=false;
extern int shift=1;                      // bar in the past to take in consideration for the signal

//+------------------------------------------------------------------------------+ EXTERNAL INPUTS 2 +---------------+

extern string timefilter="Time Filter";

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

bool excludedays=false;
int excludeday1=3;
int excludeday2=10;

bool closetime=false;
int closehour=21;

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

extern string timeout="Time Outs and Targets";

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

//+----------------------------------------------------------------------------+ INTERNAL PARAMETERS +----------------+
bool closebasket=false,continuebuy=true,continuesell=true;
int global,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,
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,pt,mt,initialaccount,baskettrailpipsi,
basketstoppipsi,basketstopdollarsi,baskettraildollarsi,baskettrailpercenti,basketstoppercenti,prevhistoryprofit=0,
historyprofit=0,ilot1,alembertlastprofit;
string istarthour,istartminute,iendhour,iendminute,ifridayhour,ifridayminute,imondayhour,imondayminute,closestatus,
date,csvdate,csvmonth,csvday,csvhour,csvcurrency,cur1,cur2,sig="",flag="",stat="",fail="",err="",exit="",
basketpipsflag="",basketdollarsflag="",baskettrailpipsflag="",basketpercentflag="",baskettrailpercentflag="",
baskettraildollarsflag="";
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(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;
   }
   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(MarketInfo(Symbol(),MODE_MINLOT)>=1){lotsize=100000;}
      if(MarketInfo(Symbol(),MODE_MINLOT)<1){lotsize=10000;}
      if(MarketInfo(Symbol(),MODE_MINLOT)<0.1){lotsize=1000;}
      if(partialclose)lots=lotsoptimized(risk);
   }
   initialbar=Open[0];
   return(0);
}

//+----------------------------------------------------------------------------------------+ SIGNAL +----------------+
/*int signal(){
   //ma>0 && ma!=EMPTY_VALUE
   //iCustom(NULL,0,"StepMA_v7",maperiod,0,shift);

   double ma=iMA(NULL,0,maperiod,0,MODE_SMA,PRICE_CLOSE,shift);
   double maa=iMA(NULL,0,maperiod,0,MODE_SMA,PRICE_CLOSE,shift+1);
   double mab=iMA(NULL,0,maperiod,0,MODE_SMA,PRICE_CLOSE,shift+2);

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

   if(ma>maa && maa<mab)return(1);
   if(ma<maa && maa>mab)return(2);

   return(0);
}*/

int exitsignal(){
   /*double ma=iMA(NULL,0,maperiod,0,MODE_SMA,PRICE_CLOSE,shift);

   if(Close[shift]<ma)return(1);
   if(Close[shift]>ma)return(2);*/
   return(0);
}

//+------------------------------------------------------------------------------------------+ START +---------------+
int start(){

   if(closeall || (closetime && Hour()>=closehour)){close(OP_BUY);close(OP_SELL);ddelete(7);ddelete(8);return(0);}
   if(closebuy)close(OP_BUY);
   if(closesell)close(OP_SELL);

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

//+-----------------------------------------------------------------------------+ EXTRA OPTIMIZATION +---------------+
   //if(IsTesting())if(AccountEquity()<initialaccount*0.5)return(0);
   if(firstticks && iVolume(NULL,0,0)>ticks)return(0);

//+----------------------------------------------------------------------------------+ WAIT MIN DATA +---------------+
   if(Bars<100){if(useprint)Print("Bars less than 100");return(0);}

//+------------------------------------------------------------------------------------+ INITIAL BAR +---------------+
   if(ignoreinitialbar)if(initialbar==Open[0])return(0);

//+-----------------------------------------------------------------------------------+ COUNT TRADES +---------------+
   if(maxtrades<500){total=countall(0);}

   global=count(OP_BUY)+count(OP_SELL)+count(OP_BUYSTOP)+count(OP_SELLSTOP);
   if(global!=0){
//+---------------------------------------------------------------------------------+ BASKET TRADING +---------------+
      if(basketpercent){
         if(basketpercentflag=="CLOSE")if(countall(1)==0)basketpercentflag="";
         if(countprofit(1)>=nd(profitpercent*0.01*AccountBalance(),2) || countprofit(1)<=-1*nd(losspercent*0.01*AccountBalance(),2))basketpercentflag="CLOSE";
         if(basketpercentflag=="CLOSE"){close(OP_BUY);close(OP_SELL);ddelete(7);ddelete(8);}
      }
      if(basketpips){
         if(basketpipsflag=="CLOSE")if(countall(1)==0)basketpipsflag="";
         if(countprofit(0)>=profitpips || countprofit(0)<=-1*losspips)basketpipsflag="CLOSE";
         if(basketpipsflag=="CLOSE"){close(OP_BUY);close(OP_SELL);ddelete(7);ddelete(8);}
      }
      if(basketdollars){
         if(basketdollarsflag=="CLOSE")if(countall(1)==0)basketdollarsflag="";
         if(countprofit(1)>=profitdollars || countprofit(1)<=-1*lossdollars)basketdollarsflag="CLOSE";
         if(basketdollarsflag=="CLOSE"){close(OP_BUY);close(OP_SELL);ddelete(7);ddelete(8);}
      }
      if(baskettrailpercent){
         if(countall(1)==0){
            if(baskettrailpercentflag=="CLOSE")baskettrailpercentflag="";
            baskettrailpercenti=0;basketstoppercenti=0;
         }
         if(countall(1)==0!=0 && countprofit(1)>=baskettrailpercenti+nd(trailstartpercent*0.01*AccountBalance(),2)){
            baskettrailpercenti=countprofit(1);
            basketstoppercenti=NormalizeDouble(trailstoppctpercent*0.01*baskettrailpercenti,0);
         }
         if(countprofit(1)<=basketstoppercenti && basketstoppercenti!=0)baskettrailpercentflag="CLOSE";
         if(baskettrailpercentflag=="CLOSE"){close(OP_BUY);close(OP_SELL);ddelete(7);ddelete(8);}
      }
      if(baskettrailpips){
         if(baskettrailpipsflag=="CLOSE")if(countall(1)==0)baskettrailpipsflag="";
         if(countall(1)==0){baskettrailpipsi=0;basketstoppipsi=0;}
         if(countall(1)!=0 && countprofit(0)>=baskettrailpipsi+trailstartpips){
            baskettrailpipsi=countprofit(0);
            basketstoppipsi=NormalizeDouble(trailstoppctpips*0.01*baskettrailpipsi,0);
         }
         if(countprofit(0)<=basketstoppipsi && basketstoppipsi!=0)baskettrailpipsflag="CLOSE";
         if(baskettrailpipsflag=="CLOSE"){close(OP_BUY);close(OP_SELL);ddelete(7);ddelete(8);}
      }
      if(baskettraildollars){
         if(baskettraildollarsflag=="CLOSE")if(countall(1)==0)baskettraildollarsflag="";
         if(countall(1)==0){baskettraildollarsi=0;basketstopdollarsi=0;}
         if(countall(1)!=0 && countprofit(1)>=baskettraildollarsi+trailstartdollars){
            baskettraildollarsi=countprofit(1);
            basketstopdollarsi=NormalizeDouble(trailstoppctdollars*0.01*baskettraildollarsi,0);
         }
         if(countprofit(0)<=basketstopdollarsi && basketstopdollarsi!=0)baskettraildollarsflag="CLOSE";
         if(baskettraildollarsflag=="CLOSE"){close(OP_BUY);close(OP_SELL);ddelete(7);ddelete(8);}
      }
      if(basketpipsflag=="CLOSE" || basketdollarsflag=="CLOSE" || basketpercentflag=="CLOSE" || baskettrailpipsflag=="CLOSE" || baskettraildollarsflag=="CLOSE" || baskettrailpercentflag=="CLOSE")return(0);

   //+----------------------------------------------------------------------------------+ VISUAL EQUITY +---------------+
   //| You need the indicator vGrafBalance&Equity.mq4
      if(visualequity){GlobalVariableSet("vGrafBalance",AccountBalance());GlobalVariableSet("vGrafEquity",AccountEquity());}

   //+------------------------------------------------------------------------------------+ TRADES DATA +---------------+
      if(xmartingalemode==1){buyorderprofit=0;sellorderprofit=0;}
      if(oppositeclose){oldestlong=0;oldestshort=0;}
      lastbuyopenprice=0;
      lastsellopenprice=0;

      if(OrdersTotal()>0){
         for(i=0;i<OrdersTotal();i++){
            OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderCloseTime()==0){
               if(OrderType()==OP_BUY){
                  if(oppositeclose)if(oldestlong==0 || oldestlong>OrderOpenTime())oldestlong=OrderOpenTime();
                  lastbuyopentime=OrderOpenTime();
                  if(addpositions)lastbuyopenprice=OrderOpenPrice();
                  if(xmartingalemode==1)buyorderprofit=buyorderprofit+OrderProfit();
               }
               if(OrderType()==OP_SELL){
                  if(oppositeclose)if(oldestlong==0 || oldestshort>OrderOpenTime())oldestshort=OrderOpenTime();
                  lastsellopentime=OrderOpenTime();
                  if(addpositions)lastsellopenprice=OrderOpenPrice();
                  if(xmartingalemode==1)sellorderprofit=sellorderprofit+OrderProfit();
               }
            }
         }
      }
      if(xmartingalemode==1)totalprofit=buyorderprofit+sellorderprofit;
   }

//+-------------------------------------------------------------------------------------+ 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<OrdersHistoryTotal();i++){
         OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
            if(losses>=xlosses)lastorderclosetime=OrderCloseTime();
         }
      }
      if(TimeCurrent()-lastorderclosetime<sleepminutes*60)nosleep=false;
   }

//+-------------------------------------------------------------------------------------+ BAR STATUS +---------------+
   if(tradesperbar==1){
      if(lastbuyopentime<Time[0])tpb=0;else tpb=1;
      if(lastsellopentime<Time[0])tps=0;else tps=1;
   }
   if(tradesperbar!=1 && bc!=Bars){tpb=0;tps=0;bc=Bars;}

//+---------------------------------------------------------------------------------+ TRADING STATUS +---------------+
   if(autosl){
      double hsl=(iHigh(NULL,autosltf,iHighest(NULL,autosltf,MODE_HIGH,autoslperiod,shift))-Bid)/pt;
      double lsl=(Ask-iLow(NULL,autosltf,iLowest(NULL,autosltf,MODE_LOW,autoslperiod,shift)))/pt;
   }
   if(autotp){
      double htp=(iHigh(NULL,autotptf,iHighest(NULL,autotptf,MODE_HIGH,autotpperiod,shift))-Ask)/pt;
      double ltp=(Bid-iLow(NULL,autotptf,iLowest(NULL,autotptf,MODE_LOW,autotpperiod,shift)))/pt;
   }

   if(reverseontrend){
      double dafgy=iCustom(NULL,damianitimeframe,"Damiani_volatmeter v3.2",visatr,visstd,sedatr,sedstd,thresholdlevel,0,damianishift);
      double dafgn=iCustom(NULL,damianitimeframe,"Damiani_volatmeter v3.2",visatr,visstd,sedatr,sedstd,thresholdlevel,2,damianishift);
   }
   double tma1=iMA(NULL,0,trendmaperiod,0,MODE_SMA,PRICE_CLOSE,1);
   double tma2=iMA(NULL,0,trendmaperiod,0,MODE_SMA,PRICE_CLOSE,2);

   int longtrendfilter=0;
   int shorttrendfilter=0;

   if(dafgy<dafgn && tma1>tma2)longtrendfilter=1;
   if(dafgy<dafgn && tma1<tma2)shorttrendfilter=1;

   double high1=High[iHighest(NULL,rangetimeframe1,MODE_HIGH,candles1,shift1)];
   double low1=Low[iLowest(NULL,rangetimeframe1,MODE_LOW,candles1,shift1)];

   double high2=High[iHighest(NULL,rangetimeframe2,MODE_HIGH,candles2,shift2)]+pt*margin;
   double low2=Low[iLowest(NULL,rangetimeframe2,MODE_LOW,candles2,shift2)]-pt*margin;

   double rsi=iRSI(NULL,rsitimeframe,rsiperiod,rsiprice,shift3);

   int exitsignal1=0,exitsignal2=0;
   if(exitrule){
      if(exitsignal()==1)exitsignal1=1;
      if(exitsignal()==2)exitsignal2=2;
   }

   int signal1=0,signal2=0;
   if(exitsignal1!=1
   && (range1==false || (range1 && Close[0]<=low1 && (high1-low1)/pt>=distance))
      && (range2==false || (range2 && Bid<low2))
      && (rsifilter==false || (rsifilter && rsi<rsilevela && rsi>rsilevelb))
   && IsTradeContextBusy()==false){
      signal1=1;
      if(autosl){stoploss=lsl;if(stoploss<(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD)))stoploss=(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD));}
      if(autotp){takeprofit=htp;if(takeprofit<(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD)))takeprofit=(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD));}
   }
   if(exitsignal2!=2
   && (range1==false || (range1 && Close[0]>=high1 && (high1-low1)/pt>=distance))
      && (range2==false || (range2 && Bid>high2))
      && (rsifilter==false || (rsifilter && rsi<rsilevela && rsi>rsilevelb))
   && IsTradeContextBusy()==false){
      signal2=2;
      if(autosl){stoploss=hsl;if(stoploss<(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD)))stoploss=(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD));}
      if(autotp){takeprofit=ltp;if(takeprofit<(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD)))takeprofit=(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD));}
   }

   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));

//+--------------------------------------------------------------------------------------+ 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(count(OP_BUY)>0){
         buyaddstatus=false;
         if((addposmode==0 && Close[0]<=lastbuyopenprice-pipstep*pt*MathPow(pipstepfactor,count(OP_BUY)))
         || (addposmode==1 && Close[0]>=lastbuyopenprice+pipstep*pt*MathPow(pipstepfactor,count(OP_BUY)))
         || (addposmode==2 && Close[0]<=lastbuyopenprice-pipstep*pt*MathPow(pipstepfactor,count(OP_BUY))
         || Close[0]>=lastbuyopenprice+pipstep*pt*MathPow(pipstepfactor,count(OP_BUY)))
         && (signalfilter==false || (signalfilter && (reversesignals==false && signal1==1) || (reversesignals && signal2==2))))buy=true;
      }
      if(count(OP_SELL)>0){
         selladdstatus=false;
         if((addposmode==0 && Close[0]>=lastsellopenprice+pipstep*pt*MathPow(pipstepfactor,count(OP_SELL)))
         || (addposmode==1 && Close[0]<=lastsellopenprice-pipstep*pt*MathPow(pipstepfactor,count(OP_SELL)))
         || (addposmode==2 && Close[0]>=lastsellopenprice+pipstep*pt*MathPow(pipstepfactor,count(OP_SELL))
         || Close[0]<=lastsellopenprice-pipstep*pt*MathPow(pipstepfactor,count(OP_SELL)))
         && (signalfilter==false || (signalfilter && (reversesignals==false && signal2==2) || (reversesignals && signal1==1))))sell=true;
      }
   }

//+----------------------------------------------------------------------------------+ TRADING BOARD +---------------+
   bool buyside=true;bool sellside=true;
   if(onesideatatime){if(count(OP_SELL)>0)if(reversesignals)sellside=false;else buyside=false;if(count(OP_BUY)>0)if(reversesignals)buyside=false;else sellside=false;}

   if(signal1==1 && buyaddstatus && buyside && continuebuy && nosleep
   && (excludedays==false || (excludedays && Day()!=excludeday1 && Day()!=excludeday2))){
      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(timesetx<Time[0]){timeset=TimeCurrent();timesetx=Time[0];}
      }
   }
   if(signal2==2 && selladdstatus && sellside && continuesell && nosleep
   && (excludedays==false || (excludedays && Day()!=excludeday1 && Day()!=excludeday2))){
      if(reversesignals)buy=true;else sell=true;
      if(changedirection){continuebuy=true;continuesell=false;}
      if(checkclose)if(reversesignals)closestatus="LONG";else closestatus="SHORT";
      if(tradesperbar==1){
         if(reversesignals)flag="WE BUY";else flag="WE SELL";
         if(timesetx<Time[0]){timeset=TimeCurrent();timesetx=Time[0];}
      }
   }

   if(global!=0){
   //+------------------------------------------------------------------------------------+ EXIT STATUS +---------------+
      if(oppositeclose){
         if(buy){if(partialexit)partialclose(OP_SELL,1,lots*tp2percentage*0.01,0);else close(OP_SELL);}
         if(sell){if(partialexit)partialclose(OP_BUY,1,lots*tp2percentage*0.01,0);else close(OP_BUY);}
         if(checkclose){if(closestatus=="LONG")close(OP_BUY);if(closestatus=="SHORT")close(OP_SELL);}
         if(partialexit==false && oldestlong>oldestshort && oldestshort!=0)close(OP_SELL);
         if(partialexit==false && oldestshort>oldestlong && oldestlong!=0)close(OP_BUY);
      }
      if(hidetp || hidesl)hideclose();
      if(onecancelother){if(count(OP_SELL)>0)ddelete(7);if(count(OP_BUY)>0)ddelete(8);}
      if(partialclose){
         partialclose2(3,0,blots,blots*tp2percentage*0.01,takeprofit2);
         ilot1=blots-(blots*tp2percentage*0.01);
         if((blots*tp2percentage*0.01)<minlot)ilot1=blots-minlot;
         partialclose2(3,0,ilot1,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);
   
//+----------------------------------------------------------------------------+ TRADES MODIFICATION +---------------+
      if(autots){
         movetrailingstop2(Low[shift]-2*pt);
         movetrailingstop3(Low[shift]-2*pt);
         movetrailingstop4(High[shift]+2*pt);
         movetrailingstop5(High[shift]+2*pt);
      }
      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);
      if(ecn)ecnmodify(stoploss,takeprofit);
   }

   if(buy || 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<500)if((total)>=maxtrades)return(0);

   //+--------------------------------------------------------------------------------+ MARTINGALE CORE +---------------+
   //|  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) && (partialclose==false || (partialclose && countglobal()==0)))lots=lotsoptimized(risk);
      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(recoverymode){blots=recoverylots(lots);slots=recoverylots(lots);}
      if(martingale){
         if(addpositions){
            blots=lots*MathPow(multiplier,count(OP_BUY));
            slots=lots*MathPow(multiplier,count(OP_SELL));
         }
         else{blots=mlots;slots=mlots;}
      }

   //+--------------------------------------------------------------------------------+ ALEMBERT CORE +-----------------+
   if(alembert){
      alembertlastprofit=0;
      if(OrdersHistoryTotal()>0){
         for(i=OrdersHistoryTotal()-1;i>=0;i--){
            if(alembertlastprofit!=0)break;
            OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUY || OrderType()==OP_SELL){alembertlastprofit=OrderProfit();lastlot=OrderLots();}
         }
      }
      if(alembertlastprofit>0){
         if(alembertmode==0){
            blots=lastlot-lots*decrement;
            slots=lastlot-lots*decrement;
         }
         else{
            blots=lastlot+lots*increment;
            slots=lastlot+lots*increment;
         }
      }
      if(alembertlastprofit<0){
         if(alembertmode==0){
            blots=lastlot+lots*increment;
            slots=lastlot+lots*increment;
         }
         else{
            blots=lastlot-lots*decrement;
            slots=lastlot-lots*decrement;
         }
      }
   }

   //+------------------------------------------------------------------------------------+ TIME FILTER +---------------+
      bool tradetime=true;
      if(usetimefilter)if(checktime(summergmtshift,wintergmtshift,mondayfilter,mondayhour,mondayminute,weekfilter,
      starthour,startminute,endhour,endminute,tradesunday,fridayfilter,fridayhour,fridayminute))tradetime=false;
      
   //+------------------------------------------------------------------------------------+ NEWS FILTER +---------------+
      bool newsstatus=true;
      if(newsfilter)if(checknews())newsstatus=false;

   //+------------------------------------------------------------------------------------+ TICKET CORE +---------------+
      if(buy && !onlysell && tpb<tradesperbar && tradetime && newsstatus){
         if(oppositeddelete){ddelete(OP_SELLSTOP);ddelete(OP_SELLLIMIT);}
         ticket=0;number=0;expire=0;
         if(stoporders || limitorders)if(expiration>0)expire=TimeCurrent()+(expiration*60)-5;
         if(instantorders){
            if(xmartingalemode==0){
               while(ticket<=0 && number<tries){
                  while(!IsTradeAllowed())Sleep(5000);
                  RefreshRates();ticket=open(OP_BUY,blots,Ask,stoploss,takeprofit,expire,Blue);
                  if(ticket<0){if(useprint)Print("Error opening BUY order! ",ErrorDescription(GetLastError()));number++;}
               }
            }
            if(xmartingalemode==1){
               while(ticket<=0 && number<tries){
                  while(!IsTradeAllowed())Sleep(5000);
                  RefreshRates();ticket=open(OP_BUY,blots,Ask,stoploss,0,expire,Blue);
                  if(ticket<0){if(useprint)Print("Error opening BUY order! ",ErrorDescription(GetLastError()));number++;}
               }
            }
         }
         if(stoporders)if(time2!=Time[0]){if(ddeleteold){ddelete(OP_BUYSTOP);}RefreshRates();ticket=open(OP_BUYSTOP,blots,Ask+gap*pt,stoploss,takeprofit,expire,Blue);time2=Time[0];tpb++;}
         if(limitorders)if(time3!=Time[0]){if(ddeleteold){ddelete(OP_BUYLIMIT);}RefreshRates();ticket=open(OP_BUYLIMIT,blots,Bid-gap*pt,stoploss,takeprofit,expire,Blue);time3=Time[0];tpb++;}
         if(reverseatstop && time6!=Time[0]){
            if(rasoppositeclose)ddelete(OP_BUYSTOP);
            RefreshRates();ticket=open(OP_SELLSTOP,blots,Bid-stoploss*pt,rasstoploss,rastakeprofit,expire,Red);time6=Time[0];
         }
         if(instantorders)if(ticket<=0){if(useprint)Print("Error Occured : "+ErrorDescription(GetLastError()));}else tpb++;
         if(alerttime!=Time[0]){
            RefreshRates();
            if(emailalert)SendMail("[Long Trade]", "["+Symbol()+"] "+DoubleToStr(Ask,dg));
            if(popupalert)Alert(Symbol()," Long Trade @  Hour ",Hour(),"  Minute ",Minute());
            if(soundalert)PlaySound("alert.wav");
            alerttime=Time[0];
         }
      }
      if(sell && !onlybuy && tps<tradesperbar && tradetime && newsstatus){
         if(oppositeddelete){ddelete(OP_BUYSTOP);ddelete(OP_BUYLIMIT);}
         ticket=0;number=0;expire=0;
         if(stoporders || limitorders)if(expiration>0)expire=TimeCurrent()+(expiration*60)-5;
         if(instantorders){
            if(xmartingalemode==0){
               while(ticket<=0 && number<tries){
                  while(!IsTradeAllowed())Sleep(5000);
                  RefreshRates();ticket=open(OP_SELL,slots,Bid,stoploss,takeprofit,expire,Red);
                  if(ticket<0){if(useprint)Print("Error opening BUY order! ",ErrorDescription(GetLastError()));number++;}
               }
            }
            if(xmartingalemode==1){
               while(ticket<=0 && number<tries){
                  while(!IsTradeAllowed())Sleep(5000);
                  RefreshRates();ticket=open(OP_SELL,slots,Bid,stoploss,0,expire,Red);
                  if(ticket<0){if(useprint)Print("Error opening BUY order! ",ErrorDescription(GetLastError()));number++;}
               }
            }
         }
         if(stoporders)if(time4!=Time[0]){if(ddeleteold)ddelete(OP_SELLSTOP);RefreshRates();ticket=open(OP_SELLSTOP,slots,Bid-gap*pt,stoploss,takeprofit,expire,Red);time4=Time[0];tps++;}
         if(limitorders)if(time5!=Time[0]){if(ddeleteold)ddelete(OP_SELLLIMIT);RefreshRates();ticket=open(OP_SELLLIMIT,slots,Ask+gap*pt,stoploss,takeprofit,expire,Red);time5=Time[0];tps++;}
         if(reverseatstop && time7!=Time[0]){
            if(rasoppositeclose)ddelete(OP_SELLSTOP);
            RefreshRates();ticket=open(OP_BUYSTOP,blots,Ask+stoploss*pt,rasstoploss,rastakeprofit,expire,Blue);time7=Time[0];
         }
         if(instantorders)if(ticket<=0){if(useprint)Print("Error Occured : "+ErrorDescription(GetLastError()));}else tps++;
         if(alerttime!=Time[0]){
            RefreshRates();
            if(emailalert)SendMail("[Short Trade]", "["+Symbol()+"] "+DoubleToStr(Bid,dg));
            if(popupalert)Alert(Symbol()," Short Trade @  Hour ",Hour(),"  Minute ",Minute());
            if(soundalert)PlaySound("alert.wav");
            alerttime=Time[0];
         }
      }
   }
   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);
   }
}

int countglobal(){
   int cnt=0;
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         cnt++;
      }
      return(cnt);
   }
}

//+-------------------------------------------------------------------------------+ COUNTER ALL +--------------------+
int countall(int mode){
   int cnt=0;
   if(mode==0)cnt=count(OP_BUY)+count(OP_SELL);
   if(mode==1)cnt=count(OP_BUY)+count(OP_SELL)+count(OP_BUYSTOP)+count(OP_SELLSTOP)+count(OP_BUYLIMIT)+count(OP_SELLLIMIT);
   return(cnt);
}

//+-------------------------------------------------------------------------------+ COUNTER PROFIT +-----------------+
// mode 0 = pips, mode 1 = dollars
double countprofit(int mode){
   double profit=0;
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY && OrderMagicNumber()==magic){
            if(mode==0)profit=profit+(OrderClosePrice()-OrderOpenPrice())/pt;
            if(mode==1)profit=profit+OrderProfit();
         }
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL && OrderMagicNumber()==magic){
            if(mode==0)profit=profit+(OrderOpenPrice()-OrderClosePrice())/pt;
            if(mode==1)profit=profit+OrderProfit();
         }
      }
      return(profit);
   }
}

double counthistoprofit(int mode){
   double profit=0;
   if(OrdersHistoryTotal()>0){
      for(i=OrdersHistoryTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY && OrderMagicNumber()==magic){
            if(mode==2 || mode==3 && TimeDay(OrderOpenTime())!=TimeDay(Time[0]))break;
            if(mode==4 || mode==5 && TimeMonth(OrderOpenTime())!=TimeMonth(Time[0]))break;
            if(mode==0)profit=profit+(OrderClosePrice()-OrderOpenPrice())/pt;
            if(mode==1)profit=profit+OrderProfit();
            if(mode==2 && TimeDay(OrderOpenTime())==TimeDay(Time[0]))profit=profit+(OrderClosePrice()-OrderOpenPrice())/pt;
            if(mode==3 && TimeDay(OrderOpenTime())==TimeDay(Time[0]))profit=profit+OrderProfit();
            if(mode==4 && TimeMonth(OrderOpenTime())==TimeMonth(Time[0]))profit=profit+(OrderClosePrice()-OrderOpenPrice())/pt;
            if(mode==5 && TimeMonth(OrderOpenTime())==TimeMonth(Time[0]))profit=profit+OrderProfit();
         }
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL && OrderMagicNumber()==magic){
            if(mode==2 || mode==3 && TimeDay(OrderOpenTime())!=TimeDay(Time[0]))break;
            if(mode==4 || mode==5 && TimeMonth(OrderOpenTime())!=TimeMonth(Time[0]))break;
            if(mode==0)profit=profit+(OrderOpenPrice()-OrderClosePrice())/pt;
            if(mode==1)profit=profit+OrderProfit();
            if(mode==2 && TimeDay(OrderOpenTime())==TimeDay(Time[0]))profit=profit+(OrderOpenPrice()-OrderClosePrice())/pt;
            if(mode==3 && TimeDay(OrderOpenTime())==TimeDay(Time[0]))profit=profit+OrderProfit();
            if(mode==4 && TimeMonth(OrderOpenTime())==TimeMonth(Time[0]))profit=profit+(OrderOpenPrice()-OrderClosePrice())/pt;
            if(mode==5 && TimeMonth(OrderOpenTime())==TimeMonth(Time[0]))profit=profit+OrderProfit();
         }
      }
      return(profit);
   }
}

//+----------------------------------------------------------------------------------+ OPEN FUNCTION +---------------+
int open(int type,double lots,double price,double stoploss,double takeprofit,int expire,color clr){
   int ticket=0;
   if(lots<minlot)lots=minlot;
   if(lots>maxlot)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(ecn){sl=0;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;
      if(ecn){sl=0;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 risk){
   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);
}

//+------------------------------------------------------------------------------------+ RECOVERY MODE +-------------+
double recoverylots(double lots){
   historyprofit=counthistoprofit(1);
   if(prevhistoryprofit<=historyprofit)prevhistoryprofit=historyprofit;
   if(prevhistoryprofit>historyprofit)return(recoverymultiplier*lots);
   return(lots);
}

//+---------------------------------------------------------------------------------+ 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(lot<minlot)lot=minlot;
         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(lot2<minlot)lot2=minlot;
         if(type==3 || type==OP_BUY && OrderType()==OP_BUY){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderLots()==nd(lot1,lotdigits) && OrderLots()>=minlot && (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) && OrderLots()>=minlot && (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<timeout2*60) || (mode==1 && tradeprofit>=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<timeout2*60) || (mode==1 && tradeprofit>=target*pt && tradehour>timeout1*60)){
                  RefreshRates();OrderClose(OrderTicket(),OrderLots(),Ask,slippage*mt);
               }
            }
         }
      }
   }
}

//+--------------------------------------------------------------------------------+ ddelete FUNCTION +---------------+
void ddelete(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(Bid-(trailingstop+trailingstep)*pt,dg)){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(Bid-trailingstop*pt,dg),OrderTakeProfit(),0,Blue);
                     return(0);
                  }
               }
               else{
                  if(nd(Bid,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);
                  }
               }
            }
         }
      }
   }
}

void movetrailingstop2(double price){
   RefreshRates();
   if(OrdersTotal()>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(OrderStopLoss(),dg)==0 && nd(Bid,dg)>nd(price+(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD))*pt,dg)){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(price,dg),OrderTakeProfit(),0,Blue);
                     return(0);
                  }
               }
            }
      }
   }
}

void movetrailingstop3(double price){
   RefreshRates();
   if(OrdersTotal()>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(OrderStopLoss(),dg)>0 && nd(Bid,dg)>nd(price+(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD))*pt,dg) && nd(price,dg)>nd(OrderStopLoss(),dg)){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(price,dg),OrderTakeProfit(),0,Blue);
                     return(0);
                  }
               }
            }
      }
   }
}

void movetrailingstop4(double price){
   RefreshRates();
   if(OrdersTotal()>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_SELL){
               if(nd(OrderStopLoss(),dg)==0 && nd(Ask,dg)<nd(price-(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD))*pt,dg)){
                  OrderModify(OrderTicket(),OrderOpenPrice(),nd(price,dg),OrderTakeProfit(),0,Red);
                  return(0);
               }
            }
         }
      }
   }
}

void movetrailingstop5(double price){
   RefreshRates();
   if(OrdersTotal()>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_SELL){
               if(nd(OrderStopLoss(),dg)>0 && nd(Ask,dg)<nd(price-(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD))*pt,dg) && nd(price,dg)<nd(OrderStopLoss(),dg)){
                  OrderModify(OrderTicket(),OrderOpenPrice(),nd(price,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)<nd(Ask-(trailingprofit+trailingstep)*pt,dg)){
                        OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),nd(Ask-trailingprofit*pt,dg),0,Red);
                     }
                  }
               }
            }
         }
      }
   }
}

//+----------------------------------------------------------------------------+ BREAK EVEN FUNCTION +---------------+
void movebreakeven(double breakevengain,double breakeven){
   RefreshRates();
   if(OrdersTotal()>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(breakeven*pt,dg))|| OrderStopLoss()==0){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(OrderOpenPrice()+breakeven*pt,dg),OrderTakeProfit(),0,Blue);
                     return(0);
                  }
               }
            }
            else{
               if(nd((OrderOpenPrice()-Ask),dg)>=nd(breakevengain*pt,dg)){
                  if((nd((OrderOpenPrice()-OrderStopLoss()),dg)<nd(breakeven*pt,dg)) || OrderStopLoss()==0){
                     OrderModify(OrderTicket(),OrderOpenPrice(),nd(OrderOpenPrice()-breakeven*pt,dg),OrderTakeProfit(),0,Red);
                     return(0);
                  }
               }
            }
         }
      }
   }
}

//+-----------------------------------------------------------------------------------+ ECN FUNCTION +---------------+
void ecnmodify(double stoploss,double takeprofit){
   if(OrdersTotal()>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))sdlbar1=i;
      }
      int sdlbar2=0;
      for(i=0;i<=100;i++){
         if(sdlbar2!=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(stoploss<(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD)))stoploss=(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD));
      if(takeprofit<(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD)))takeprofit=(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD));
   }
}

//+----------------------------------------------------------------------------+ CHECK TIME FUNCTION +---------------+
bool checktime(int summergmtshift,int wintergmtshift,bool mondayfilter,int mondayhour,int mondayminute,bool weekfilter,
int starthour,int startminute,int endhour,int endminute,bool tradesunday,bool fridayfilter,int fridayhour,int fridayminute){
   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';
   if(TimeCurrent()<win[TimeYear(TimeCurrent())-1999]
   && TimeCurrent()>sum[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()<tstart || TimeCurrent()>tend) || (nstarthour>nendhour && TimeCurrent()<tstart && 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()<tmonday)return(true);
   return(false);
}

//+---------------------------------------------------------------------------+ NEWS FILTER FUNCTION +---------------+
//|  For Backtesting : make @BACKUP@.CSV with News v303, remove none last year data
//|  (it will be too heavy otherwise), and copy paste the file to tester/files
bool checknews(){
   if(IsTesting()){
      if(newstime!=Time[0]){

         string filename="@BACKUP@.CSV";
         handle=FileOpen(filename,FILE_READ|FILE_WRITE|FILE_CSV/*,','*/);

         if(handle>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]<minutesbefore*60)  || (Time[0]-csvdatetime>=0 && Time[0]-csvdatetime<minutesafter*60) && cur1==csvcurrency || cur2==csvcurrency)FileClose(handle);return(true);
            }
         }
         FileClose(handle);
         newstime=Time[0];
      }
   }
   if(IsTesting()==false){
      static int prevminute=-1;

      if(Minute()!=prevminute){
         prevminute=Minute();
         int minsincenews=iCustom(NULL,0,"FFCal",true,true,false,true,true,1,0);
         int mintonews=iCustom(NULL,0,"FFCal",true,true,false,true,true,1,1);
         int impactsincenews=iCustom(NULL,0,"FFCal",true,true,false,true,true,2,0);
         int impacttonews=iCustom(NULL,0,"FFCal",true,true,false,true,true,2,1);
         if(impacthigh && (mintonews<=minutesbefore &&  impacttonews==1) || (minsincenews<=minutesafter && impactsincenews==1))return(true);
         if(impactmedium && (mintonews<=minutesbefore &&  impacttonews==2) || (minsincenews<=minutesafter && impactsincenews==2))return(true);
         if(impactlow && (mintonews<=minutesbefore &&  impacttonews==3) || (minsincenews<=minutesafter && impactsincenews==3))return(true);
      }
   }
   return(false);
}

//+-----------------------------------------------------------------------------+ NORMALIZE FUNCTION +---------------+
double nd(double value,double digits){
   double val;
   val=NormalizeDouble(value,digits);
   return(val);
}

Комментарии к исходному коду форекс советника Multi-Channel RSI Scalper v1.11.mq4
В целях безопасности и борьбы со спамом в тексте комментариев запрещено размещать html-теги и ссылки. Благодарим за понимание.

  • X
  • 0% загружено
« советник Multi level v.1.0.mq4
советник Multi-Lot Scalper.mq4 »