Navigation:Home > Content >

Uposi_Tro_Rate_Zone_EA_v1.01a.mq4

Time: 2015-01-10 | Download file:Uposi_Tro_Rate_Zone_EA_v1.01a.mq4

//+------------------------------------------------------------------------------------------------------------------+
//|                                                                                M09.D03.Y2011_Expert_Advisor.mq4  |
//|                                                   Copyright © 2008-2012, TradingSystemForex.Com - Elite Section  |
//|                                                                              http://www.tradingsystemforex.com/  |
//+------------------------------------------------------------------------------------------------------------------+

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

#include 
#include 

//+--------------------------------------------------------------------------------+ EXTERNAL INPUTS +---------------+
//|  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.
//|  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 bool useMinGap = true;
extern double minGap = 4;
extern bool useTroRateZoneSL = true;
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=true;                     // 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=50;                 // 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
int martingalemode=0;                    // 0=increase after a loss, 1=increase after a profit
extern double multiplier=2.0;                   // multiplier used for the martingale
double percentrecovering=0;              // enabled if >0, percentage of the last losses to recover
bool fibomartingale=false;               // enable the martingale with fibonacci progression
int fibomartingalemode=0;                // 0=increase after a loss, 1=increase after a profit
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
int resetlevel=500;                      // enabled if <500, martingale/fibomartingale/alembert is reseted after resetlevel consecutive losses/profits

string profitmanagement="Profit Management";

bool basketpercent=false;                // enable the basket percent
double profitpercent=0.1;                // close all orders if a profit of 0.1 percents has been reached
double losspercent=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 profitdollars=5;                  // target in dollars
double lossdollars=10000;                // target in dollars
bool baskettrailpercent=false;           // basket trail in percent
double trailstartpercent=1;              // trailstart percent
double trailstoppercent=0.5;             // trailstop percent
bool baskettrailpips=false;              // basket trail in pips
double trailstartpips=75;                // trailstart pips
double trailstoppips=20;                 // trailstop pips
bool baskettraildollars=false;           // basket trail in dollars
double trailstartdollars=10;             // trailstart dollars
double trailstopdollars=5;               // trailstop dollars

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=false;          // 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
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
bool tradesperday=false;                 // maximum number of trades per day
int trades=1;                            // trades per day
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
bool partialexit=false;                  // partial exit at opposite close
bool partialtp=false;                 // partial close at takeprofit 2 and takeprofit 3
double takeprofit2=5;                    // takeprofit 2 to close a certain percentage of lots
double tp2percentage=50;                 // percentage of lots to close at takeprofit 2
double takeprofit3=20;                   // takeprofit 3 to close a certain percentage of lots
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
bool addpositions=false;                 // add positions, set tradesperbar to 100
bool signalfilter=false;                 // signal filter for added positions
int addposmode=0;                        // 0=counter, 1=follow, 2=both
double pipstep=20;                       // minimum difference in pips between orders
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

bool highlowts=false;                    // auto trailing stop
int highlowtsmargin=2;                   // auto trailing stop margin

bool rangesl=false;                      // range stoploss based highest lowest bar
int rangesltf=0;                         // range stoploss tf
int rangeslperiod=10;                    // range stoploss based on the high/low of the x last candles
bool rangetp=false;                      // range takeprofit based highest lowest bar
int rangetptf=0;                         // range takeprofit tf
int rangetpperiod=10;                    // range takeprofit based on the high/low of the x last candles

extern string entrylogics="Entry Logics";

extern int FasterMode = 1;
extern int FasterMA = 3;
extern int SlowerMode = 1;
extern int SlowerMA = 5;
extern bool exitrule=true;
extern double troratzonedistance = 0;
extern int shift=1;                      // bar in the past to take in consideration for the signal

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

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

int testhour=24;                         // individual test of hour if <24

bool monthfilter=false;
int startmonth=1;
int startday=4;
int endmonth=12;
int endday=18;

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

string timeout="Time Outs and Targets";

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

//+----------------------------------------------------------------------------+ INTERNAL PARAMETERS +---------------+
bool closebasket=false,continuebuy=true,continuesell=true,nosleep=true,buy=false,sell=false,buyaddstatus=true,
selladdstatus=true,buyside=true,sellside=true,tradetime=true,newsstatus=true;
int count,global,i,tries=100,lastorder,buyorderprofit,sellorderprofit,lotsize,losses,sleep,recovering=0,ntesthour,
mstop,nstarthour,nnewshour,nendhour,nfridayhour,nmondayhour,number,ticket,gmtshift,expire,tradehour,consloss=0,
consprofit=0,total,oldestlong,oldestshort,handle,csvdatetime,signal1=0,signal2=0,exitsignal1=0,exitsignal2=0,gap1,gap2;
double 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,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,stat="",fail="",err="",exit="",itesthour,itestminute,
basketpipsflag="",basketdollarsflag="",baskettrailpipsflag="",basketpercentflag="",baskettrailpercentflag="",
baskettraildollarsflag="";
datetime tstart,tend,tfriday,tmonday,lastbuyopentime,tnews,lastsellopentime,time,time2,time3,
time4,time5,time6,time7,lastorderclosetime,alerttime,newstime,daytime,ttesthour;

double dg,pt,mt;
double xbuy,xsell;

//+---------------------------------------------------------------------------------+ INITIALIZATION +---------------+
int init(){

   dg=Digits;
   if(dg==3 || dg==5){pt=Point*10;mt=10;}
   else{pt=Point;mt=1;}

   gap1=gap;gap2=gap;
//+--------------------------------------------------------------------------------+ INITIALBAR INIT +---------------+
   initinitialbar();
//+-----------------------------------------------------------------------+ FASTER OPTIMIZATION INIT +---------------+
   initoptimization();
//+---------------------------------------------------------------------------+ FIBO MARTINGALE INIT +---------------+
   initfibo();
//+------------------------------------------------------------------------------+ POINT DIGITS INIT +---------------+
   //point();
//+------------------------------------------------------------------------------+ POINT DIGITS INIT +---------------+
   initmm();

   return(0);
}
//+-----------------------------------------------------------------------------------+ ENTRY SIGNAL +---------------+
int signal(int mode,int pos){
   //ma>0 && ma!=EMPTY_VALUE
   //iCustom(NULL,0,"StepMA_v7",maperiod,0,pos);

   xbuy=ObjectGet("Short_sr",OBJPROP_PRICE1);
   xsell=ObjectGet("Buy_sr",OBJPROP_PRICE1);
   
   //xbuy= iLow(NULL,PERIOD_D1,0)+20*pt;
   //xsell= iHigh(NULL,PERIOD_D1,0)-20*pt;
   
   double up=iCustom(NULL,0,"UPOSI ARROWS~",FasterMode,FasterMA,SlowerMode,SlowerMA,0,pos);
   double dn=iCustom(NULL,0,"UPOSI ARROWS~",FasterMode,FasterMA,SlowerMode,SlowerMA,1,pos);
   
   
 //  extern bool useMinGap = true;
 //  extern int minGap = 20;
   bool canbuy = true, cansell = true;
   
   if (useMinGap)
   {
      if (!(Ask >= xsell + minGap*pt)) canbuy = false;
      if (!(Bid <= xbuy - minGap*pt)) cansell = false;
   }
   
   if(uptroratzonedistance*pt)
   )if(mode==0){troSL(1);return(1);}
   if(up>dn && Close[0]>xsell+MarketInfo(Symbol(),MODE_SPREAD)*pt && cansell
   && troratzonedistance==0 || (troratzonedistance!=0 && xbuy-xsell>troratzonedistance*pt)
   )if(mode==1){troSL(2);return(2);}
   //Comment("\nhau = "+DoubleToStr(hau,5),"\nhad = "+DoubleToStr(had,5));

   return(0);
}

void troSL(int mode)
{
  double tempSL;
  if (useTroRateZoneSL)
  {
  if (mode == 1)
   {
      tempSL = (Bid - xsell + 20*pt)/pt; 
      if (tempSL >2) stoploss = NormalizeDouble(tempSL,1);
      //else stoploss = 0;
      
   }
   
   else 
   {
      tempSL = ( (xbuy + 20*pt) - Ask)/pt; 
      if (tempSL >2) stoploss = NormalizeDouble(tempSL,1);
      //else stoploss = 0;
   }
   }
   
}

//+------------------------------------------------------------------------------------+ EXIT SIGNAL +---------------+
int exitsignal(int mode,int pos){

   //double tro=iCustom(NULL,0,"TRO_RAT_ZONE_NEW",false,false,50,false,false,false,true,10,80,1,"",12,false,true,true,0,pos);
   
   xbuy=ObjectGet("Short_sr",OBJPROP_PRICE1);
   xsell=ObjectGet("Buy_sr",OBJPROP_PRICE1);
   
   Comment("\nxbuy = "+DoubleToStr(xbuy,5),
   "\nxsell = "+DoubleToStr(xsell,5));

   if(Close[0]>=xbuy)if(mode==0)return(1);
   if(Close[0]<=xsell)if(mode==1)return(2);
   return(0);
}
//+-------------------------------------------------------------------------------------------+ EXIT +---------------+
void exit(){
   exitsignal1=0;
   exitsignal2=0;
   if(exitrule){
      if(exitsignal(OP_BUY,shift)==1)exitsignal1=1;
      if(exitsignal(OP_SELL,shift)==2)exitsignal2=2;
   }
}
//+------------------------------------------------------------------------------------------+ ENTRY +---------------+
void entry(){
   if(tradesperday){
      count=0;
      if(OrdersHistoryTotal()>0){
         for(i=OrdersHistoryTotal()-1;i>=0;i--){
            OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
            if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=magic)continue;
            if(OrderOpenTime()=endday)))
   && IsTradeContextBusy()==false){
      signal1=1;
   }
   if(exitsignal2!=2
   && signal(OP_SELL,shift)==2
   && (tradesperday==false || (tradesperday && count=endday)))
   && IsTradeContextBusy()==false){
      signal2=2;
   }
}
//+-----------------------------------------------------------------------------------------+ START +----------------+
int start(){


//+-------------------------------------------------------------------------------------+ CLOSE CALL +---------------+
   if(closeall || (closetime && Hour()>=closehour)){closeall();return(0);}if(closebuy)close(OP_BUY);if(closesell)close(OP_SELL);
//+--------------------------------------------------------------------------------+ DATA CONDITIONS +---------------+
   if(optimization() || initialbar() || minbars())return(0);
//+-----------------------------------------------------------------------------------+ RANDOM MAGIC +---------------+
   randommagic();
//+---------------------------------------------------------------------------------+ BASKET TRADING +---------------+
   basket();
   if(basketpipsflag=="CLOSE" || basketdollarsflag=="CLOSE" || basketpercentflag=="CLOSE" || baskettrailpipsflag=="CLOSE" || baskettraildollarsflag=="CLOSE" || baskettrailpercentflag=="CLOSE")return(0);
//+----------------------------------------------------------------------------------+ VISUAL EQUITY +---------------+
   visual();
//+------------------------------------------------------------------------------------+ TRADES DATA +---------------+
   data();
//+-------------------------------------------------------------------------------------+ SLEEP CALL +---------------+
   sleep();
//+-------------------------------------------------------------------------------------------+ EXIT +---------------+
   exit();
//+------------------------------------------------------------------------------------------+ ENTRY +---------------+
   entry();
//+--------------------------------------------------------------------------------------+ DIRECTION +---------------+
   //direction();
//+-----------------------------------------------------------------------------------+ INIT TRADING +---------------+
   inittrading();
//+----------------------------------------------------------------------------------+ ADD POSITIONS +---------------+
   addpositions();
//+----------------------------------------------------------------------------------------+ TRADING +---------------+
   trading();
//+------------------------------------------------------------------------------------+ EXIT STATUS +---------------+
   stop();
//+----------------------------------------------------------------------------+ TRADES MODIFICATION +---------------+
   modify();
//+---------------------------------------------------------------------------------------+ MAX AREA +---------------+
   if((!buy && !sell) || max())return(0);
//+---------------------------------------------------------------------------------------+ LOT CALL +---------------+
   lot();
//+--------------------------------------------------------------------------------+ MARTINGALE CALL +---------------+
   martingale();
//+----------------------------------------------------------------------------------+ ALEMBERT CALL +---------------+
   alembert();
//+---------------------------------------------------------------------------+ FIBO MARTINGALE CALL +---------------+
   fibomartingale();
//+----------------------------------------------------------------------------------+ RECOVERY CALL +---------------+
   recovery();
//+------------------------------------------------------------------------------------+ TIME FILTER +---------------+
   time();
//+------------------------------------------------------------------------------------+ NEWS FILTER +---------------+
   news();
//+-------------------------------------------------------------------------------+ TICKET GENERATOR +---------------+
   ticket();

   return(0);
}
//+-------------------------------------------------------------------------------------+ BAR STATUS +---------------+
int bar(int mode){
   int count=0;
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderCloseTime()==0){
            if(OrderOpenTime()=iTime(NULL,0,0))count++;
            }
            if(OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP && mode==OP_SELL){
               if(OrderOpenTime()>=iTime(NULL,0,0))count++;
            }
         }
      }
   }
   if(OrdersHistoryTotal()>0){
      for(i=OrdersHistoryTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
         if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=magic)continue;
         if(OrderOpenTime()=iTime(NULL,0,0))count++;
         if(OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP && mode==OP_SELL)if(OrderOpenTime()>=iTime(NULL,0,0))count++;
      }
   }
   return(count);
}
//+----------------------------------------------------------------------------------+ VISUAL EQUITY +---------------+
void visual(){
   if(visualequity){ // You need the indicator vGrafBalance&Equity.mq4
      GlobalVariableSet("vGrafBalance",AccountBalance());
      GlobalVariableSet("vGrafEquity",AccountEquity());
   }
}
//+-----------------------------------------------------------------------------------+ RANDOM MAGIC +---------------+
void randommagic(){
   if(randommagic)if(daytime!=iTime(NULL,1440,0)){
      MathSrand(TimeLocal());
      magic=MathRand();
      daytime=iTime(NULL,1440,0);
   }
}
//+----------------------------------------------------------------------------+ FASTER OPTIMIZATION +---------------+
void initoptimization(){
   initialaccount=AccountBalance();
   if(stop>0){
      stoploss=stop;
      takeprofit=stop;
   }
}
bool optimization(){
   if(firstticks)if(iVolume(NULL,0,0)>ticks)return(true);
   //if(IsTesting())if(AccountEquity()0){
      for(i=0;iOrderOpenTime())oldestlong=OrderOpenTime();
               lastbuyopentime=OrderOpenTime();
               if(addpositions)lastbuyopenprice=OrderOpenPrice();
               if(recovering==1)buyorderprofit=buyorderprofit+OrderProfit();
            }
            if(OrderType()==OP_SELL){
               if(oppositeclose)if(oldestlong==0 || oldestshort>OrderOpenTime())oldestshort=OrderOpenTime();
               lastsellopentime=OrderOpenTime();
               if(addpositions)lastsellopenprice=OrderOpenPrice();
               if(recovering==1)sellorderprofit=sellorderprofit+OrderProfit();
            }
         }
      }
   }
   if(recovering==1)totalprofit=buyorderprofit+sellorderprofit;
}
//+-----------------------------------------------------------------------------------+ TRADING CORE +--------------+
void inittrading(){
   buy=false;
   sell=false;
}
void trading(){
   buyside=true;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(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";
   }
}
//+----------------------------------------------------------------------------------+ 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(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);
}
void buy(){
   if(rangesl){stoploss=(Ask-iLow(NULL,rangesltf,iLowest(NULL,rangesltf,MODE_LOW,rangeslperiod,shift)))/pt;if(stoploss<(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD)))stoploss=(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD));}
   if(rangetp){takeprofit=(iHigh(NULL,rangetptf,iHighest(NULL,rangetptf,MODE_HIGH,rangetpperiod,shift))-Ask)/pt;if(takeprofit<(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD)))takeprofit=(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD));}
   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(recovering==0){
         while(ticket<=0 && number0)expire=TimeCurrent()+(expiration*60)-5;
   if(instantorders){
      if(recovering==0){
         while(ticket<=0 && number0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         cnt++;
      }
      return(cnt);
   }
}
//+-------------------------------------------------------------------------+ MAGIC 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);
   }
}
//+------------------------------------------------------------------------------------+ 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);
}
//+---------------------------------------------------------------------------------+ MAX CONDITIONS +---------------+
bool max(){
   if(maxspread!=0)if((Ask-Bid)>maxspread*pt)return(true);
   if(maxtrades<500)if(countall(0)>=maxtrades)return(true);
   return(false);
}
//+------------------------------------------------------------------------+ LAST HISTORY PROFIT/LOT +---------------+
double history(int mode){
   double lastprofit=0;
   double lastlot=0;
   if(OrdersHistoryTotal()>0){
      for(i=OrdersHistoryTotal()-1;i>=0;i--){
         if(lastprofit!=0)break;
         OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUY || OrderType()==OP_SELL){
            lastprofit=OrderProfit();
            lastlot=OrderLots();
         }
      }
   }
   if(mode==0)return(lastlot);
   if(mode==1)return(lastprofit);
   return(0);
}
//+------------------------------------------------------------------------------+ LAST HISTORY TYPE +---------------+
/*int type(){
   int lasttype=2;
   if(OrdersHistoryTotal()>0){
      for(i=OrdersHistoryTotal()-1;i>=0;i--){
         if(lasttype==OP_BUY || lasttype==OP_SELL)break;
         OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUY || OrderType()==OP_SELL){
            lasttype=OrderType();
         }
      }
   }
   return(lasttype);
}*/
//+--------------------------------------------------------------------------------------+ DIRECTION +---------------+
/*void direction(){
   if(changedirection){
      if(type()==OP_BUY){continuebuy=false;continuesell=true;}
      if(type()==OP_SELL){continuebuy=true;continuesell=false;}
   }
}*/
//+------------------------------------------------------------------------------+ COUNT PROFIT/LOSS +---------------+
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);
   }
}
//+----------------------------------------------------------------------+ COUNT HISTORY PROFIT/LOSS +---------------+
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);
   }
}
//+------------------------------------------------------------------------+ CONSECUTIVE PROFIT/LOSS +---------------+
int consecutive(int mode){
   int res=0;
   for(i=OrdersHistoryTotal();i>=0;i--){
      OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
         if(mode==0){
            if(OrderProfit()>0)break;
            if(OrderProfit()<0)res=res+1;
         }
         if(mode==1){
            if(OrderProfit()<0)break;
            if(OrderProfit()>0)res=res+1;
         }
      }
   }
   return(res);
}
//+-----------------------------------------------------------------------------+ GLOBAL PROFIT/LOSS +---------------+
double global(int mode){
   double res=0;
   for(i=OrdersHistoryTotal();i>=0;i--){
      OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
         if(mode==0){
            if(OrderProfit()>0)break;
            if(OrderProfit()<0)res=res+OrderProfit();
         }
         if(mode==1){
            if(OrderProfit()<0)break;
            if(OrderProfit()>0)res=res+OrderProfit();
         }
      }
   }
   return(res);
}
//+-----------------------------------------------------------------------------+ ADD POSITIONS CORE +---------------+
void addpositions(){
   buyaddstatus=true;
   selladdstatus=true;
   if(addpositions)checkaddpositions();
}
void checkaddpositions(){
   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;
   }
}
void addlots(){
   blots=lots*MathPow(multiplier,count(OP_BUY));
   slots=lots*MathPow(multiplier,count(OP_SELL));
}
//+--------------------------------------------------------------------------------------------+ LOT +---------------+
void lot(){
   if(mm)if(martingale==false || (martingale && !addpositions && lastprofit>=0) || (martingale && addpositions) && (partialtp==false || (partialtp && countglobal()==0)))lots=mm(risk);
   blots=lots;
   slots=lots;
}
//+----------------------------------------------------------------------------------------+ MM CORE +---------------+
void initmm(){
   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(partialtp)lots=mm(risk);
   }
}
double mm(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);
}
//+--------------------------------------------------------------------------------+ MARTINGALE CORE +---------------+
void martingale(){
   if(martingale){
      if(!addpositions)checkmartingale();
      if(addpositions)addlots();
   }
}
void checkmartingale(){
   recovering=0;
   globallosses=0;lossestorecover=0;
   lastlot=history(0);
   lastprofit=history(1);
   mlots=0;
   if(martingalemode==0){
      if(lastprofit<0){
         mlots=lastlot*multiplier;
         if(resetlevel<500){
            consloss=consecutive(0);
            if(consloss>=resetlevel)mlots=lots;
         }
         if(percentrecovering!=0){
            globallosses=global(0);
            recovering=1;
            lossestorecover=nd(globallosses*0.01*percentrecovering,2);
         }
      }
      else mlots=lots;
   }
   if(martingalemode==1){
      if(lastprofit>0){
         mlots=lastlot*multiplier;
         if(resetlevel<500){
            consprofit=consecutive(1);
            if(consprofit>=resetlevel)mlots=lots;
         }
      }
      else{
         mlots=lots;
         if(percentrecovering!=0){
            globallosses=global(0);
            recovering=1;
            lossestorecover=nd(globallosses*0.01*percentrecovering,2);
         }
      }
   }
   blots=mlots;
   slots=mlots;
}
//+---------------------------------------------------------------------------+ FIBO MARTINGALE CORE +---------------+
void initfibo(){
   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;
   }
}
void fibomartingale(){
   if(fibomartingale)checkfibomartingale();
}
void checkfibomartingale(){
   if(OrdersHistoryTotal()>0){
      if(fibomartingalemode==0){
         consloss=consecutive(0);
         blots=lots*fibo[consloss];
         slots=lots*fibo[consloss];
         if(resetlevel<500){
            if(consloss>=resetlevel){
               blots=lots;
               slots=lots;
            }
         }
      }
      if(fibomartingalemode==1){
         consprofit=consecutive(1);
         blots=lots*fibo[consprofit];
         slots=lots*fibo[consprofit];
         if(resetlevel<500){
            if(consprofit>=resetlevel){
               blots=lots;
               slots=lots;
            }
         }
      }
   }
}
//+----------------------------------------------------------------------------------+ ALEMBERT CORE +---------------+
void alembert(){
   if(alembert)checkalembert();
}
void checkalembert(){
   lastlot=history(0);
   alembertlastprofit=history(1);
   if(alembertlastprofit>0){
      if(alembertmode==0){
         blots=lastlot-lots*decrement;
         slots=lastlot-lots*decrement;
         if(resetlevel<500){
            consloss=consecutive(0);
            if(consloss>=resetlevel){
               blots=lots;
               slots=lots;
            }
         }
      }
      else{
         blots=lastlot+lots*increment;
         slots=lastlot+lots*increment;
      }
   }
   if(alembertlastprofit<0){
      if(alembertmode==0){
         blots=lastlot+lots*increment;
         slots=lastlot+lots*increment;
         if(resetlevel<500){
            consprofit=consecutive(1);
            if(consprofit>=resetlevel){
               blots=lots;
               slots=lots;
            }
         }
      }
      else{
         blots=lastlot-lots*decrement;
         slots=lastlot-lots*decrement;
      }
   }
}
//+------------------------------------------------------------------------------------+ RECOVERY MODE +-------------+
void recovery(){
   if(recoverymode){
      blots=recoverylots(lots);
      slots=recoverylots(lots);
   }
}
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);
            }
         }
      }
   }
}
//+----------------------------------------------------------------------------+ 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);
            }
         }
      }
   }
}
//+-------------------------------------------------------------------------+ PARTIAL CLOSE FUNCTION +---------------+
void partialtp(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=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 partialtp2(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 && (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);
            }
         }
      }
   }
}
//+----------------------------------------------------------------------------+ 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);
               }
            }
         }
      }
   }
}
//+--------------------------------------------------------------------------------+ ddelete FUNCTION +---------------+
void ddelete(int type){
   if(OrdersTotal()>0){
      for(i=OrdersTotal()-1;i>=0;i--){
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){
         if(type!=6 && type!=7 && type!=8)if(OrderType()==type)OrderDelete(OrderTicket());
         if(type==6)if(OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP || OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT)OrderDelete(OrderTicket());
         if(type==7)if(OrderType()==OP_BUYSTOP || OrderType()==OP_BUYLIMIT)OrderDelete(OrderTicket());
         if(type==8)if(OrderType()==OP_SELLSTOP || OrderType()==OP_SELLLIMIT)OrderDelete(OrderTicket());
         }
      }
   }
}
//+--------------------------------------------------------------------------------------+ CLOSE ALL +---------------+
void closeall(){
   close(OP_BUY);
   close(OP_SELL);
   ddelete(7);
   ddelete(8);
}
//+--------------------------------------------------------------------------------+ STOP CONDITIONS +---------------+
void stop(){
   if(oppositeclose){
      if(buy){if(partialexit)partialtp(OP_SELL,1,lots*tp2percentage*0.01,0);else close(OP_SELL);}
      if(sell){if(partialexit)partialtp(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(partialtp){
      partialtp2(3,0,blots,blots*tp2percentage*0.01,takeprofit2);
      ilot1=blots-(blots*tp2percentage*0.01);
      if((blots*tp2percentage*0.01)=-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);
}
//+-------------------------------------------------------------------------+ 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(OrderOpenPrice()+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(OrderOpenPrice()-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);
                  }
               }
            }
         }
      }
   }
}
//+----------------------------------------------------------------+ ADVANCED TRAILING STOP FUNCTION +---------------+
void movetrailingstop2(int mode,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()==mode){
               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);
               }
               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);
               }
            }
            if(OrderType()==mode){
               if(nd(OrderStopLoss(),dg)==0 && nd(Ask,dg)0 && nd(Ask,dg)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);
                        return(0);
                     }
                  }
               }
               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);
                  return(0);
               }
               if(OrderTakeProfit()==0 && stoploss==0 && takeprofit>0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),nd(Ask+takeprofit*pt,dg),0,Red);
                  return(0);
               }
               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);
                  return(0);
               }
            }
            if(OrderType()==OP_SELL){
               if(OrderStopLoss()==0 && stoploss>0 && takeprofit==0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),nd(Bid+stoploss*pt,dg),OrderTakeProfit(),0,Red);
                  return(0);
               }
               if(OrderTakeProfit()==0 && stoploss==0 && takeprofit>0){
                  RefreshRates();
                  OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),nd(Bid-takeprofit*pt,dg),0,Red);
                  return(0        

Recommend