Why Fully Automated Trading on MT4 is not a Viable Thing

I have the intention of scaring you off from even considering to run a fully automated trading routine on MT4.

Let’s just skip the obvious part that every broker have different spreads and different data throws off everything. Let’s not mention that even those brokers with spreads normally around 0.2 pips (for EurUSD) crank it up at times (but for a Sunday open for sure) above and beyond 10 pips, so scalping is sort of out of the question.

I decided to implement a maximum loss cropper function in my Wishing On A Star Evo6. Basically this was to serve as a maximum 4.5% draw down hard exit, whilst most of the winning trades should be scoring 4% net. I wanted to make even the hedge positions become a subject of the max draw-down crops.

Fired up the back test, and then there was a way larger than 4.5% stop out.

So, I had to investigate what happened.

The 25th order was opened at midnight and got closed down in the same second by the cropper: the 30+ pips spread. This looks more like a glitch for the broker won’t even be open for trading for another 5 minutes (and all brokers are different, so again, forget trade copying), and frankly, the spread is 3x larger than any print I have seen from this broker.

Yes, it is an option to delete all pending orders before the daily close, but I let you do that part. I am done tempering with back testing with the junk data provided and playing Russian Roulette with hoping for a non-agressive Market Maker behind the lever of the current spread.

Now you get to see how complex a routine can get with parallel, multi position number hedging in a mere 2400 lines long code.

From here on I’ll just stick to my Trail Stops, Croppers, Hedgers and Target Adjusters.

// Wishing on a Star EVO 6 GREEN 5 EA w/ new trail by Macdulio in 2020
// from ForexFore.blog

#include <stdlib.mqh>
extern bool Equity_Based_Hedge = false;
extern int magic_number = 901;
extern int magic_number2 = 902;
extern int magic_number3 = 903;
extern int magic_number4 = 904;
extern int magic_number5 = 54;
extern int magic_number6 = 55;
extern int magic_number7 = 56;
extern int magic_number8 = 57;
extern int magic_number9 = 58;
extern int magic_number10 = 59;
extern int magic_number11 = 60;
extern int magic_number12 = 61;
extern int magic_number13 = 62;
extern int magic_number14 = 63;
extern int magic_number15 = 64;
extern int magic_number16 = 65;


extern double Ratio = .8;
extern double MarginCallPercentage = 100;
extern bool rope_trade_allowed = false;
extern bool overhedging_allowed = false;
extern int ClosePendingInSeconds = 14100;
//---- input parameters for regular doji
extern int       MinLengthOfUpTail=5; //candle with upper tail equal or more than this will show up
extern int       MinLengthOfLoTail=6; //candle with lower tail equal or more than this will show up
extern int    MaxLengthOfBody=16; //candle with body less or equal with this will show up
     
//---- input parameters for dragonfly doji
extern int       MaxLengthOfUpTail1=10; //candle with upper tail equal or more than this will show up
extern int       MinLengthOfLoTail1=13; //candle with lower tail equal or more than this will show up
extern int    MaxLengthOfBody1=11; //candle with body less or equal with this will show up

//---- input parameters for gravestone doji
extern int       MinLengthOfUpTail2=13; //candle with upper tail equal or more than this will show up
extern int       MaxLengthOfLoTail2=10; //candle with lower tail equal or more than this will show up
extern int    MaxLengthOfBody2=11; //candle with body less or equal with this will show up
double pt=0.00001;
int no50b, no50s, no51b, no51s, no52b, no52s, no53b, no53s;
int profits;
double Lots;
  double nakedshorts[];
  double nakedlongs[];
  double stoch[],RSI2[], RSI[], RSI8[], wop[], sup[], sdn[], stoch2[];
  extern int SLoss = 25;
extern double Leverage = 1.5;
extern double AF=1.3;
extern double LT=333;
  double open_price;
  double stop_loss_price;
  double take_profit_price;
  double open_price2;
  double stop_loss_price2;
  double take_profit_price2;  
  double open_price3;
  double stop_loss_price3;
  double take_profit_price3;
  double open_price4;
  double stop_loss_price4;
  double take_profit_price4;    
  double open_price5;
  double stop_loss_price5;
  double take_profit_price5;
  double open_price6;
  double stop_loss_price6;
  double take_profit_price6;    
   

  double open_price9;
  double stop_loss_price9;
  double take_profit_price9;    
  double open_price10;
  double stop_loss_price10;
  double take_profit_price10;    
  double open_price11;
  double stop_loss_price11;
  double take_profit_price11;      
  double open_price12;
  double stop_loss_price12;
  double take_profit_price12;    

  double open_price13;
  double stop_loss_price13;
  double take_profit_price13;
  double open_price14;
  double stop_loss_price14;
  double take_profit_price14;   

    
 int positive[], negative[], bigpicture[];
    double buy[],sell[], minus[], plus[];
     extern int lowrsi = 17;
extern double highrsi = 77.7;
extern double FSize=32;
double FMax = FSize*6/5;
extern double divider=4.0;
double Target = FMax;
int StopLoss = FMax*10+10;
 int lastdir[], currdir[];
   double ExtUpFractalsBuffer[];
double ExtDownFractalsBuffer[];
   double OrderOpenPrice;
 double OrderProfit;
  string symbol = Symbol();  
int    K_Period  = 25;
int    K_Period2  = 60;
int    K_Period3  = 100;
int    D_Period  = 3;
int    Slowing  = 3;
int    TopBorder=90;
int    BotBorder=10;
int    BotBorder2=5;
int    BotBorder3=3;
string TypeMA    = "SMA=0, EMA=1, SMMA=2, LWMA=3";
int    MAType    =  0;
//extern int    MAShift   =  0;
string TypePrice = "0 - Low/High, 1 - Close/Close";
int    PriceType =  0;
double ExtMapBuffer[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];  
double bpu[],bpd[];
int omega[], omegam[], omegaf[];
bool ddid[], ddiu[], ddidm[], ddium[];
double eight[], nineh[], ninel[], ODU[], ODD[];
double red[],blue[],yellow[],green[],white[],magenta[];
int trending[];
double tup[];
double tdn[];
double dt14, db14, pacing;
 double arrowup[],arrowdn[], doji[];
 bool trianglelow[], trianglehigh[],peaktrending[];
extern int exempt_magic_number = 0;
int init() {
   return(0);
}

int deinit() {
  return(0);
}

int start() {
 ArrayResize(eight, Bars);
   ArrayInitialize(eight, EMPTY_VALUE);
      ArrayResize(nineh, Bars);
   ArrayInitialize(nineh, 0);
       ArrayResize(ninel, Bars);
   ArrayInitialize(ninel, 0);
      ArrayResize(ODU, Bars);
ArrayInitialize(ODU, EMPTY_VALUE);
 ArrayResize(ODD, Bars);
ArrayInitialize(ODD, EMPTY_VALUE);
 ArrayResize(RSI8, 900);   
 ArrayInitialize(RSI8, 0);  
 ArrayResize(stoch2, 1100);
ArrayInitialize(stoch2, 0);

int order_type;
  ArrayResize(stoch, 206);
  ArrayInitialize(stoch, 0);   
   ArrayResize(RSI, 300);   
 ArrayInitialize(RSI, 0);
 ArrayResize(RSI2, 300);   
 ArrayInitialize(RSI2, 0);
  ArrayResize(stoch, 300);   
 ArrayInitialize(stoch, 0); 
   ArrayResize(wop, Bars);
 ArrayInitialize(wop, 0); 
   ArrayResize(sup, 100);   
 ArrayInitialize(sup, 0); 
ArrayResize(sdn, 100);   
 ArrayInitialize(sdn, 0);    
    ArrayResize(bigpicture, 340);
ArrayInitialize(bigpicture, 0);
     ArrayResize(minus, 350);   
 ArrayInitialize(minus, EMPTY_VALUE); 
  ArrayResize(plus, 350);   
 ArrayInitialize(plus, EMPTY_VALUE); 
    ArrayResize(positive, 1100);
ArrayInitialize(positive, EMPTY_VALUE);
    ArrayResize(negative, 1100);
ArrayInitialize(negative, EMPTY_VALUE);
     ArrayResize(buy, 1100);
ArrayInitialize(buy, EMPTY_VALUE);
    ArrayResize(sell, 1100);
ArrayInitialize(sell, EMPTY_VALUE);
    ArrayResize(ExtMapBuffer2, 1100);
ArrayInitialize(ExtMapBuffer2, EMPTY_VALUE);
  ArrayResize(ExtMapBuffer3, 1100);
ArrayInitialize(ExtMapBuffer3, EMPTY_VALUE);
   ArrayResize(lastdir, 1100);
ArrayInitialize(lastdir, 0);
 ArrayResize(currdir, 1100);
ArrayInitialize(currdir, 0);
  ArrayResize(bpu, 250);
  ArrayResize(bpd, 250);
  ArrayInitialize(bpu, EMPTY_VALUE);
  ArrayInitialize(bpd, EMPTY_VALUE); 
    ArrayResize(tup, 650);
  ArrayResize(tdn, 650);
  ArrayInitialize(tup, EMPTY_VALUE);
  ArrayInitialize(tdn, EMPTY_VALUE);  

    ArrayResize(arrowup, 650);
  ArrayResize(arrowdn, 650);
  ArrayInitialize(arrowup, EMPTY_VALUE);
  ArrayInitialize(arrowdn, EMPTY_VALUE); 
   ArrayResize(doji, 300);  
  ArrayInitialize(doji, 0);
ArrayResize(ddid, 350);
  ArrayResize(ddiu, 350);
  ArrayInitialize(ddid, false);
  ArrayInitialize(ddiu, false); 
    ArrayResize(ddidm, 350);
  ArrayResize(ddium, 350);
  ArrayInitialize(ddidm, false);
  ArrayInitialize(ddium, false);   
    ArrayResize(omega, 550);
  ArrayInitialize(omega, 0); 
    ArrayResize(omegam, 550);
    ArrayInitialize(omegam, 0); 
    ArrayResize(omegaf,550);
    ArrayInitialize(omegaf,0);
     ArrayResize(peaktrending, 1100);   
 ArrayInitialize(peaktrending, False);  
   ArrayResize(ExtUpFractalsBuffer, Bars);   
 ArrayInitialize(ExtUpFractalsBuffer, EMPTY_VALUE);  
  ArrayResize(ExtDownFractalsBuffer, Bars);   
 ArrayInitialize(ExtDownFractalsBuffer, EMPTY_VALUE);  
 
int i,i2,j,j2,k, counter, bar;
int counted_bars=IndicatorCounted();

double longaveragebuffer=0;
double shortaveragebuffer=0;
int longcount=0;
int shortcount=0;
double nlongs=0;
double nshorts=0;
double difference;
double buylevel=0;
double sellevel=0;
double orderstoploss = OrderStopLoss();

 for (i=80; i>=1; i--) 
    {
 
           doji[i]=EMPTY_VALUE;
       
       if(High[i]-Close[i]>=MinLengthOfUpTail*pt && Close[i]-Low[i]>=MinLengthOfLoTail*pt  && MathAbs(Close[i]-Open[i])<=MaxLengthOfBody*pt && doji[i+1]==EMPTY_VALUE) doji[i]=(Open[i]+Close[i])/2+.000042;
       if(High[i]-Close[i]<=MaxLengthOfUpTail1*pt && Close[i]-Low[i]>=MinLengthOfLoTail1*pt  && MathAbs(Close[i]-Open[i])<=MaxLengthOfBody1*pt && doji[i+1]==EMPTY_VALUE) doji[i]=(Open[i]+Close[i])/2+.000042;
       if(High[i]-Close[i]>=MinLengthOfUpTail2*pt && Close[i]-Low[i]<=MaxLengthOfLoTail2*pt  && MathAbs(Close[i]-Open[i])<=MaxLengthOfBody2*pt && doji[i+1]==EMPTY_VALUE) doji[i]=(Open[i]+Close[i])/2+.000042;
               
               }

profits = 0;
 int hstTotal=OrdersHistoryTotal();

 counter = 0;
int overdrivecounter =0;

int no56b=0;
int no57s=0; 

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
             if (OrderType() == OP_BUY && OrderMagicNumber()!=magic_number) 
             {
               if (OrderMagicNumber()==53 ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
               else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL && OrderMagicNumber()!=magic_number2 )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
               else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==56) no56b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==57) no57s++;
                      
   }
   
//  Print("Nlongs: ",nlongs); 
//  Print("NShorts: ",nshorts); 
   
dt14 = iHigh(symbol,240,iHighest(symbol,240,MODE_HIGH,1590));
db14 = iLow(symbol,240,iLowest(symbol,240,MODE_LOW,1590));
pacing = (dt14-db14)*.1;

bool embeddedoversold = (iClose(symbol,1440,1)<db14+2*pacing && iClose(symbol,1440,2)<db14+2*pacing && iClose(symbol,1440,3)<db14+2*pacing);
bool embeddedoverbought = (iClose(symbol,1440,1)>dt14-2*pacing && iClose(symbol,1440,2)>dt14-2*pacing && iClose(symbol,1440,3)>dt14-2*pacing);  

   double comparison = AccountEquity()/AccountBalance(); 

double VolLowest,Range,Value2,Value3,HiValue2,HiValue3,LoValue3,tempv2,tempv3,tempv;

for(i=0; i<200; i++)   
      {
         red[i] = 0; blue[i] = 0; yellow[i] = 0; green[i] = 0; white[i] = 0; magenta[i] = 0;
         Value2=0;Value3=0;HiValue2=0;HiValue3=0;LoValue3=99999999;tempv2=0;tempv3=0;tempv=0;
         
         VolLowest = Volume[iLowest(NULL,0,MODE_VOLUME,20,i)];
         Range = (High[i]-Low[i])/Point;
         Value2 = Volume[i]*Range;
         
         if (  Range != 0 )
            Value3 = Volume[i]/Range;
            
         for ( int n=i;n<i+20;n++)
            {
               tempv2 = Volume[n]*((High[n]-Low[n])/Point); 
               if ( tempv2 > HiValue2 )
                  HiValue2 = tempv2;
                  
               
               if ( Volume[n]*((High[n]-Low[n])/Point) != 0 )
                  {
                     tempv3 = Volume[n] / ((High[n]-Low[n])/Point);
                     if ( tempv3 > HiValue3 ) 
                        HiValue3 = tempv3;
                     if ( tempv3 <  LoValue3 )
                        LoValue3 = tempv3;
                  }         
            }
          if ( Value3 == HiValue3 )
            {
               red[i] = High[i]+.0005;                
               blue[i] =Low[i]-.0005;
           }

      }


   
int    nCountedBars;
   bool   bFound;
   double dCurrent;
   nCountedBars=IndicatorCounted();
//---- last counted bar will be recounted    
   if(nCountedBars<=2)
      i=Bars-nCountedBars-3;
   if(nCountedBars>2)
     {
      nCountedBars--;
      i=500;
     }
//----Up and Down Fractals
   while(i>=2)
     {
      //----Fractals up
      bFound=false;
      dCurrent=High[i];
      if(dCurrent>High[i+1]  && dCurrent>High[i-1] && dCurrent>High[i-2])
       //&& dCurrent>High[i+2]
        {
         bFound=true;
         ExtUpFractalsBuffer[i]=dCurrent;
        }
      //----6 bars Fractal
      if(!bFound && (Bars-i-1)>=3)
        {
         if(dCurrent==High[i+1] && dCurrent>High[i+2]  
         //&& dCurrent>High[i+3]
            && dCurrent>High[i-1] && dCurrent>High[i-2])
           {
            bFound=true;
            ExtUpFractalsBuffer[i]=dCurrent;
           }
        }        
      //----7 bars Fractal
      if(!bFound && (Bars-i-1)>=4)
        {  
         if(dCurrent>=High[i+1]  && dCurrent>High[i+3] && dCurrent>High[i+4] &&  dCurrent==High[i+2]
            && dCurrent>High[i-1] && dCurrent>High[i-2])
           {
            bFound=true;
            ExtUpFractalsBuffer[i]=dCurrent;
           }
        }  
      //----8 bars Fractal                          
      if(!bFound && (Bars-i-1)>=5)
        {  
         if(dCurrent>=High[i+1] && dCurrent==High[i+2] && dCurrent==High[i+3] && dCurrent>High[i+4]  &&
         
        //&& dCurrent>High[i+5]
            dCurrent>High[i-1] && dCurrent>High[i-2])
           {
            bFound=true;
            ExtUpFractalsBuffer[i]=dCurrent;
           }
        }
      //----9 bars Fractal                                        
      if(!bFound && (Bars-i-1)>=6)
        {  
         if(dCurrent>=High[i+1] && dCurrent==High[i+2] && dCurrent>=High[i+3] && dCurrent==High[i+4] && dCurrent>High[i+5]  && dCurrent>High[i-1] && dCurrent>High[i-2])
           //&&             dCurrent>High[i+6]
           {
            bFound=true;
            ExtUpFractalsBuffer[i]=dCurrent;
           }
        }                                    
      //----Fractals down
      bFound=false;
      dCurrent=Low[i];
      if(dCurrent<Low[i+1]  && dCurrent<Low[i-1] && dCurrent<Low[i-2])
        //&& dCurrent<Low[i+2]
        {
         bFound=true;
         ExtDownFractalsBuffer[i]=dCurrent;
        }
      //----6 bars Fractal
      if(!bFound && (Bars-i-1)>=3)
        {
         if(dCurrent==Low[i+1] && dCurrent<Low[i+2]  &&
            dCurrent<Low[i-1] && dCurrent<Low[i-2])
           //&& dCurrent<Low[i+3]
           {
            bFound=true;
            ExtDownFractalsBuffer[i]=dCurrent;
           }                      
        }        
      //----7 bars Fractal
      if(!bFound && (Bars-i-1)>=4)
        {  
         if(dCurrent<=Low[i+1] && dCurrent==Low[i+2] && dCurrent<Low[i+3]  &&
            dCurrent<Low[i-1] && dCurrent<Low[i-2])
          //&& dCurrent<Low[i+4]  
           {
            bFound=true;
            ExtDownFractalsBuffer[i]=dCurrent;
           }                      
        }  
      //----8 bars Fractal                          
      if(!bFound && (Bars-i-1)>=5)
        {  
         if(dCurrent<=Low[i+1] && dCurrent==Low[i+2] && dCurrent==Low[i+3] && dCurrent<Low[i+4]  &&
            dCurrent<Low[i-1] && dCurrent<Low[i-2])
           //&& dCurrent<Low[i+5] 
           {
            bFound=true;
            ExtDownFractalsBuffer[i]=dCurrent;
           }                      
        }
      //----9 bars Fractal                                        
      if(!bFound && (Bars-i-1)>=6)
        {  
         if(dCurrent<=Low[i+1] && dCurrent==Low[i+2] && dCurrent<=Low[i+3] && dCurrent==Low[i+4] && dCurrent<Low[i+5]  && dCurrent<Low[i-1] && dCurrent<Low[i-2])
           //&&             dCurrent<Low[i+6]
           {
            bFound=true;
            ExtDownFractalsBuffer[i]=dCurrent;
           }                      
        }                                    
      i--;
     }   
   
   
for (i = 150 ; i >= 0; i--){ 
   eight[i]=EMPTY_VALUE;
   nineh[i]=0;
   ninel[i]=0;
   RSI2[i]=iRSI(symbol,0,2,PRICE_MEDIAN,i);
   RSI[i]=iRSI(symbol,0,8,PRICE_MEDIAN,i);
   stoch[i]=iStochastic(symbol,0,8,3,3,MODE_SMA,1,MODE_SIGNAL,i);
   stoch2[i]=iStochastic(Symbol(),0,20,3,3,MODE_SMA,1 ,MODE_MAIN,i);
}



bool R2Buy = false;
bool R2Sell = false;     
     
  
///find last fractal low within 11

j2=1;
   while (j2<500 ){
    j=j2+2; 
      if (ExtDownFractalsBuffer[j2]!=EMPTY_VALUE) 
         while (j<j2+26){
               if (RSI2[j2]>RSI2[j] && ExtDownFractalsBuffer[j]!=EMPTY_VALUE && Low[j2]<=Low[j]+10*Point ) break;
            
         j++;}
    if (ExtDownFractalsBuffer[j]!=EMPTY_VALUE && ExtDownFractalsBuffer[j2]!=EMPTY_VALUE && RSI2[j2]>RSI2[j]  && Low[j2]<=Low[j]+10*Point ) break;
        
          j2++;} 

if (j2==1 && j<13) R2Buy = True;



i2=1;
   while (i2<500){
      i=i2+2;
      if (ExtUpFractalsBuffer[i2]!=EMPTY_VALUE)     
      while (i<i2+26 ){
            if ( RSI2[i2]<RSI2[i] && iFractals(Symbol(),0,MODE_UPPER,i) && High[i2]>=High[i]-10*Point ) break;
            
        i++;}
      if (ExtUpFractalsBuffer[i]!=EMPTY_VALUE  && ExtUpFractalsBuffer[i2]!=EMPTY_VALUE && RSI2[i2]<RSI2[i] && High[i2]>=High[i]-10*Point ) break;
               i2++;}    

if (i2==1 && i<13) R2Sell = True;
 
    
 for (i=140; i>=1; i--){


//  
 
if(stoch[i+1]<23 && RSI2[i+1]<16  && RSI2[i+3]>5 && !(stoch[i]<5 && RSI2[i]<5)&& 
ExtDownFractalsBuffer[i+1]!=EMPTY_VALUE
//iFractals(Symbol(),0,MODE_LOWER,i+1)
)
    sdn[i+1]=iLow(symbol,30,i+1); 
if(stoch[i+1]<23 && RSI2[i+1]<16  && !(stoch[i]<5 && RSI2[i]<5)&& 
ExtDownFractalsBuffer[i+1]!=EMPTY_VALUE
//iFractals(Symbol(),0,MODE_LOWER,i+1)
)
    sdn[i+1]=iLow(symbol,30,i+1); 
if(stoch[i+1]<44 && stoch[i+1]>5 && RSI2[i+1]>5 && !(stoch[i]>15 && RSI2[i]>15) && 
ExtDownFractalsBuffer[i+1]!=EMPTY_VALUE
//iFractals(Symbol(),0,MODE_LOWER,i+1)
)        
   sdn[i+1]=iLow(symbol,30,i+1);
if(stoch[i+1]<5 && RSI2[i+1]<5 && !(stoch[i]>15 && RSI2[i]>15) && 
ExtDownFractalsBuffer[i+1]!=EMPTY_VALUE
//iFractals(Symbol(),0,MODE_LOWER,i+1)
)        
    sdn[i+1]=iLow(symbol,30,i+1);

if( ((stoch[i+1]>64 && stoch[i]<85 && RSI2[i+2]>85  ) ||  (stoch[i+1]>72 && stoch[i+1]<75 )  ||  (stoch[i]>44 && stoch[i+1]<35 && stoch[i-1]<44  && RSI2[i+1]>85 )) && RSI2[i+1]>70 && !(stoch[i-1]>95 && RSI2[i-1]>95) && 
ExtUpFractalsBuffer[i+1]!=EMPTY_VALUE
//(  iFractals(Symbol(),0,MODE_UPPER,i+1)  )  
&& !sup[i+2]   )        
    sup[i+1]=iHigh(symbol,30,i+1);
if(stoch[i+1]>64 && stoch[i+2]<64 && RSI2[i+1]>85 && !(stoch[i]>70 && RSI2[i]>95) && 
ExtUpFractalsBuffer[i+2]!=EMPTY_VALUE
//( iFractals(Symbol(),0,MODE_UPPER,i+2) )  
&& !sup[i+2] )        
    sup[i+1]=iHigh(symbol,30,i+1);
if(stoch[i+1]>85 && RSI2[i+1]>85 && !(stoch[i]>85 && RSI2[i]>95) &&  
ExtUpFractalsBuffer[i+1]!=EMPTY_VALUE
//iFractals(Symbol(),0,MODE_UPPER,i+1) 
  && !sup[i+2] )        
    sup[i+1]=iHigh(symbol,30,i+1);
        
        
      minus[i]=minus[i+1];
     plus[i]=plus[i+1];     

     if (sdn[i+1]!=0) minus[i]=Low[i+1]-110*Point+FSize/2*10*Point;
     if (sup[i+1]!=0) plus[i]=High[i+1]+100*Point-FSize/2*10*Point; 
 }


for (bar=0; bar<=140; bar++) 
    {
     if (sup[bar]) {ODU[bar]=High[bar];  }
   if (sdn[bar]) {ODD[bar]=Low[bar]; }
   
  if (bar>1 && ODU[bar-1]==EMPTY_VALUE && ODU[bar]!=EMPTY_VALUE ) eight[bar]=High[bar];
  if (bar>1 && ODD[bar-1]==EMPTY_VALUE && ODD[bar]!=EMPTY_VALUE ) eight[bar]=Low[bar]; 
  
 
   if (eight[bar]==EMPTY_VALUE && iFractals(symbol,0,MODE_UPPER,bar) && RSI[bar]>75 && ! (RSI2[bar+1]>95 && RSI2[bar+2]>95)) nineh[bar]=High[bar];
 if (eight[bar]==EMPTY_VALUE && iFractals(symbol,0,MODE_LOWER,bar) && RSI[bar]<25 && ! (RSI2[bar+1]<5 && RSI2[bar+2]<5)) ninel[bar]=Low[bar];
    }




//Find last SDN

i=5;
while (i<=90 && sdn[i]==0)  i++;
  
k=i+5;
while (k<=90 && sdn[k]==0)  k++;

buylevel=(Low[i]+Low[k])/2; 

//Find last SDU
   
i=5;
while (i<=90 && sup[i]==0)  i++;

k=i+5;
while (k<=90 && sup[k]==0)  k++;

sellevel=(High[i]+High[k])/2;     




   for(i = 150; i >= 0; i--)
   {  
      ddid[i]=false;
      ddiu[i]=false;
      double St=iStochastic(NULL,0,K_Period,D_Period,Slowing,MAType,PriceType,MODE_MAIN,i);
      double St2=iStochastic(NULL,0,K_Period2,D_Period,Slowing,MAType,PriceType,MODE_MAIN,i);
      double St3=iStochastic(NULL,0,K_Period3,D_Period,Slowing,MAType,PriceType,MODE_MAIN,i);
      ExtMapBuffer2[i] = EMPTY_VALUE;
      ExtMapBuffer3[i] = EMPTY_VALUE;
         if (St2<BotBorder2 && (St<BotBorder || St3<BotBorder3)) ExtMapBuffer2[i] = 15;
          if (St>TopBorder && !((High[i]-iMA(symbol,30,414,0,MODE_EMA, PRICE_HIGH,i))<FSize*10*Point && embeddedoversold)) ExtMapBuffer3[i] = 85;
   }
  
  
   for (i = 140 ; i >= 0; i--) {           
    positive[i]=positive[i+1];
      negative[i]=negative[i+1];
      bigpicture[i]=bigpicture[i+1];
      
          
      if (Open[i+3]>plus[i+3] && Open[i+2]>plus[i+2] && Open[i+1]>plus[i+1] && buy[i+1]!=EMPTY_VALUE) positive[i]=50;
       if (Open[i+3]>plus[i+3] && Open[i+2]>plus[i+2] && Open[i+1]>plus[i+1] && sell[i+1]!=EMPTY_VALUE) negative[i]=50;
     
       
      if (Open[i+3]<minus[i+3] && Open[i+2]<minus[i+2] && Open[i+1]<minus[i+1] && sell[i+1]!=EMPTY_VALUE) negative[i]=50;
      if (Open[i+3]<minus[i+3] && Open[i+2]<minus[i+2] && Open[i+1]<minus[i+1] && buy[i+1]!=EMPTY_VALUE) positive[i]=50;
    
       if (High[i+1]>plus[i+1] && High[i]<plus[i]) {positive[i]=EMPTY_VALUE; negative[i]=EMPTY_VALUE;}
       if (Low[i+1]<minus[i+1] && Low[i]>minus[i]) {negative[i]=EMPTY_VALUE; positive[i]=EMPTY_VALUE;}   
    
     
      
      if (positive[i+1]==50 && positive[i+2]==50 && positive[i+3]==50 && positive[i+4]==50) bigpicture[i]=1;
      if (negative[i+1]==50 && negative[i+2]==50 && negative[i+3]==50 && negative[i+4]==50) bigpicture[i]=-1;
      
      
      if (positive[i]!=EMPTY_VALUE) trending[i]=1;
      if (negative[i]!=EMPTY_VALUE) trending[i]=1;
      
     if (stoch2[i]<20 && Period()==30){   
        for (j=i+1; j<=i+11; j++)         
         if ( iHigh(symbol,30,iHighest(symbol,30,MODE_HIGH,j-i,i))-Low[i]<FSize*1.5*10*Point && stoch2[j]>80)
               trianglelow[i]=True;}
    
    if (stoch2[i]>80 && Period()==30){  
    for (j=i+1; j<=i+11; j++)         
         if ( High[i]-iLow(symbol,30,iLowest(symbol,30,MODE_LOW,j-i,i))<FSize*1.5*10*Point && stoch2[j]<20)
                 trianglehigh[i]=True;}
     } 
      

 
    
//////////omega insert from d-day hedger    
    
for (i = 100 ; i >= 0; i--) {
     
   ddiu[i]=false;
    ddid[i]=false;
     omega[i]=omega[i+1];
     
       ddium[i]=false;
    ddidm[i]=false;
     omegam[i]=omegam[i+1];
    
      
  ///ddi     
    if (RSI2[i]>5 && RSI2[i+1]<2 && RSI2[i+2]<2 && RSI2[i+3]<2 && RSI2[i+4]>2 && ExtMapBuffer2[i+1]==15 && !(ExtMapBuffer2[i+1]==15 && ExtMapBuffer2[i+2]==15 && ExtMapBuffer2[i+3]==15)) {
    ddid[i]=True; ddidm[i]=True;
  }
     
 
   //ddit
    if (RSI2[i+6]>5 && RSI2[i+7]<2 && RSI2[i+8]<2 && RSI2[i+9]<2 && RSI2[i+10]<2 && (ExtMapBuffer2[i+7]==15 || RSI2[i+11]<5) ){ 
     ddid[i+1]=True; ddidm[i+1]=True;
     ddid[i]=True;ddidm[i]=True;}
     
   //d
   if (RSI2[i]>5 && RSI2[i+1]<5 && RSI2[i+2]<2 && RSI2[i+3]<2 && ExtMapBuffer2[i+1]==EMPTY_VALUE && RSI2[i+5]>5 ) {
     ddid[i]=True; ddidm[i]=True;}
     
   //sdd
   if (RSI2[i]>5 && RSI2[i+2]<8 && RSI2[i+3]<16.2 && RSI2[i+1]<5  && RSI2[i+3]>2  ) 
   if (Close[i]<iMA(NULL,0,414,0,MODE_EMA, PRICE_HIGH,i)+FMax*10*Point) {ddid[i]=True;  ddid[i]=True;}

//////////////////DBD

if (RSI2[i]>5 && RSI2[i+2]<8 && RSI2[i+3]>15 && RSI2[i+1]<5 && RSI2[i+4]<30  ){ ddid[i]=True; ddidm[i]=True;}


/////////////upside

   
   //ddi
   if (RSI2[i]<95 && RSI2[i+1]>98 && RSI2[i+2]>98 && RSI2[i+3]>98 && RSI2[i+4]<98 && ExtMapBuffer3[i+1]==85 && !(ExtMapBuffer3[i+1]==85 && ExtMapBuffer3[i+2]==85 && ExtMapBuffer3[i+3]==85)) {
      ddiu[i]=True; ddium[i]=True;
     }

   //ddit
   if (RSI2[i+6] && RSI2[i+7]>98 && RSI2[i+8]>98 && RSI2[i+9]>98 && RSI2[i+10]>98 && (ExtMapBuffer3[i+7]==85 || RSI2[i+11]>95)){
     ddiu[i+1]=True; ddium[i+1]=True;
     ddiu[i]=True; ddium[i]=True;
     }
   
   //d
    if (RSI2[i]<95 && RSI2[i+1]>96 && RSI2[i+2]>96 && RSI2[i+3]>95 && ExtMapBuffer3[i+1]==EMPTY_VALUE && RSI2[i+5]<95  ) {
      ddiu[i]=True; ddium[i]=True;}
   
   //sdu
    if (RSI2[i]<92 && RSI2[i+1]>92 && RSI2[i+2]>92 && RSI2[i+3]>88 && RSI2[i+3]<94 ) 
    if (Close[i]>iMA(NULL,0,414,0,MODE_EMA, PRICE_LOW,i)-FMax*10*Point) {ddiu[i]=True; ddium[i]=True;}
   
 //////////////////DBU

if (RSI2[i]<95 && RSI2[i+1]>95 && RSI2[i+2]>88 && RSI2[i+3]<85 && RSI2[i+4]>70 )   {  ddiu[i]=True; ddium[i]=True;}  

 if (ddiu[i+2] && !ddiu[i+1] && !ddiu[i+3]) omega[i]=-1;
    if (ddiu[i+14] && ddiu[i+13] && !ddiu[i+12]) omega[i]=-1;
    
    if (ddid[i+2] && !ddid[i+1] && !ddid[i+3]) omega[i]=1;
   if (ddid[i+14] && ddid[i+13] && !ddid[i+12]) omega[i]=1;
 
 if (ddium[i+2] && !ddium[i+1] && !ddium[i+3]) omegam[i]=-1;
    if (ddium[i+14] && ddium[i+13] && !ddium[i+12]) omegam[i]=-1;
    
    if (ddidm[i+2] && !ddidm[i+1] && !ddidm[i+3]) omegam[i]=1;
   if (ddidm[i+14] && ddidm[i+13] && !ddidm[i+12]) omegam[i]=1;




 if (RSI2[i+4]<15 && RSI2[i+5]>23 && RSI2[i+6]<5 && RSI2[i+7]<5)omega[i]=1;

  if (RSI2[i+4]>85 && RSI2[i+5]<77 && RSI2[i+6]>95 && RSI2[i+7]>95)omega[i]=-1;
 
 
  if (RSI2[i+7]>23 && RSI2[i+6]<23 && RSI2[i+4]>RSI2[i+6] && stoch[i+6]>77 && RSI2[i+2]>30 ) {omega[i]=-1;}
  //negated
  if (RSI2[i+7]>23 && RSI2[i+6]<23 && RSI2[i+4]>RSI2[i+6] && stoch[i+6]>77 && RSI2[i+2]<30 ) {omega[i]=1;}
             
  
    
    if (RSI2[i+7]<77 && RSI2[i+6]>77 && RSI2[i+6]>RSI2[i+4] && RSI2[i+4]<RSI2[i+6] && stoch[i+6]<30 && RSI2[i+2]<70 ) { omega[i]=1; }
  //negated
    if (RSI2[i+7]<77 && RSI2[i+6]>77 && RSI2[i+6]>RSI2[i+4] && RSI2[i+4]<RSI2[i+6] && stoch[i+6]<30 && RSI2[i+2]>70 ) { omega[i]=-1; }

   
    }     
    
    
  
int countback=4;
int countup=4;

 for(i = 188; i >= 0; i--){
      if (trianglehigh[i] && ExtMapBuffer3[i]!=85 && ExtMapBuffer3[i+1]!=85 && ExtMapBuffer3[i+2]!=85) countback = 1;  
      if (ExtMapBuffer3[i]==85) countback = 4; 
      if (tup[i]!=EMPTY_VALUE) countback = 4;
      if (trianglelow[i] && ExtMapBuffer2[i]!=15 && ExtMapBuffer2[i+1]!=15 && ExtMapBuffer2[i+2]!=15) countup = 3;  
      if (ExtMapBuffer2[i]==15) countup = 4; 
      if (tdn[i]!=EMPTY_VALUE) countup = 4;
       if (RSI2[i]<92 && RSI2[i+1]>94) {
           if (countup==1) {
                 countup=countup-1;}
      else if (countup==2) {
                 countup=countup-1;}
      else if (countup==3) {
                 countup=countup-1;}             
      else if (countup==4) {
                 countup=countup-1;}        
      else if (countup==5) {
                 countup=countup-1;}    
      }
      if (RSI2[i]>8 && RSI2[i+1]<7) {
           if (countback==1) {
                 countback=countback-1;}
      else if (countback==2) {
                countback=countback-1;}
      else if (countback==3) {
                countback=countback-1;}             
      else if (countback==4) {
                countback=countback-1;}        
      else if (countback==5) {
                countback=countback-1;}                         
   }
}
  
    
 
   difference =  MathAbs(MathAbs(nlongs)-MathAbs(nshorts));    
   
  
   double  account = AccountEquity(); 
     
        
   double MaxLots = NormalizeDouble(LT/3000000*account*AF*Leverage/SLoss*260/2,2);     

   double longsz;
   
   if (NormalizeDouble((nshorts-nlongs),2)>MaxLots) longsz = NormalizeDouble((nshorts-nlongs),2);
   else longsz = NormalizeDouble(MaxLots/1.5,2);
    
   if (longsz>MarketInfo(Symbol(),MODE_MAXLOT)) longsz=MarketInfo(Symbol(),MODE_MAXLOT);     
          
     double shortsz;
 
 
   if (NormalizeDouble((nlongs-nshorts),2)>MaxLots) shortsz = NormalizeDouble((nlongs-nshorts),2);
   else shortsz = NormalizeDouble(MaxLots/1.5,2);        
   
   if (shortsz>MarketInfo(Symbol(),MODE_MAXLOT)) shortsz=MarketInfo(Symbol(),MODE_MAXLOT);       
          
//Print("LastRSI2: ", RSI2[1]);          

int lastflow = 500;
int lastfhigh = 500;


for (i = OrdersTotal() - 1; i >= 0; i--)
  if( OrderSelect(i,SELECT_BY_POS) ) {


///find last fractal low within 11

j=3; 
if (Low[0]<Low[1]){ 
  while (j<11){
       if (RSI2[0]>RSI2[j] && ExtDownFractalsBuffer[j]!=EMPTY_VALUE && Low[0]<=Low[j]+10*Point ) break;
      j++;}          
    if (j>=11) lastflow=500; 
     else lastflow = j;}
           
///find last fractal high within 11
k=3;
if (High[0]>High[1]){
   while (k<11){
       if (RSI2[0]<RSI2[k] && ExtUpFractalsBuffer[k]!=EMPTY_VALUE && High[0]>=High[k]-10*Point ) break;
      k++;}
    if (k>=11) lastfhigh=500;
      else lastfhigh = k;  } 



////Stop Loss Long (Sharpie Up)
   
 if (OrderLots()>.01){  
    if( OrderType()==OP_BUY && OrderMagicNumber()!=48 && OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=56 && OrderMagicNumber()!=0 && OrderProfit()>0 &&
     Close[1]>OrderOpenPrice() &&
      ((RSI[1]>RSI[2]+4.5 && RSI[1]>RSI[0]+4.5 && RSI[1]>44)
      || (stoch[0]>stoch[1] && RSI2[0]<=RSI2[1] && RSI2[1]>=stoch[1] && stoch[1]>59 && High[0]-iLow(Symbol(),30,iLowest(Symbol(),30,MODE_LOW,10,0))>FMax*10*Point))     
       && OrderStopLoss()<Close[1]
       && NormalizeDouble(Close[1],4)>OrderStopLoss()
       ) 
        {OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(Close[1],4), OrderTakeProfit(), OrderExpiration());
            Print("Sharpie LONG Stop Loss Set @ "+NormalizeDouble(Close[1],4));}

////Exit Long (RSI2 Divergence on the upside)
     else 
     
    if( OrderType()==OP_BUY && OrderMagicNumber()!=48 && OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=54 && OrderMagicNumber()!=0 && OrderProfit()>0 && 
   lastfhigh!=500 && Bid>OrderOpenPrice()+50*Point) 
        {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
            Print("RSI2 Cropper Closed LONG @ "+MarketInfo(OrderSymbol(), MODE_BID)+" for ", OrderProfit());}   


////Exit Long (Overdrive Up)
     else 
     
    if( OrderType()==OP_BUY && OrderMagicNumber()!=48 && OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=54 && OrderMagicNumber()!=0 && OrderProfit()>0 && 
    ExtMapBuffer3[0]==EMPTY_VALUE && ExtMapBuffer3[1]==85 ) 
        {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
            Print("Star Cropper Closed LONG @ "+MarketInfo(OrderSymbol(), MODE_BID)+" for ", OrderProfit());}       


////Exit Long (Golfer On Top)
     else 
     
    if( OrderType()==OP_BUY && OrderMagicNumber()!=48 && OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=54 && OrderProfit()>0 &&
    //Bid>OrderOpenPrice+10*Point &&
    omegam[0]<0 && RSI2[0]<60 && RSI2[1]>75 && RSI2[2]<75  ) 
        {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
            Print("Golfer Cropper Closed LONG @ "+MarketInfo(OrderSymbol(), MODE_BID)+" for ", OrderProfit());}       
      
    
////Stop Loss Short (Sharpie Down)
    
    else if( OrderType()==OP_SELL && OrderMagicNumber()!=48 && OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=57 && OrderMagicNumber()!=0  && OrderProfit()>0 && 
    Close[1]<OrderOpenPrice() &&
    ((RSI[1]<RSI[2]-4 && RSI[1]<RSI[0]-4 && RSI[1]<30) || (stoch[0]<stoch[1] && RSI2[0]>=RSI2[1] && RSI2[1]<=stoch[1] && stoch[1]<35 && RSI2[1]>RSI2[0]-25))    
    && OrderStopLoss()>Close[1]
    && NormalizeDouble(Close[1],4)<OrderStopLoss()
    ) 
           {OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(Close[1],4), OrderTakeProfit(), OrderExpiration());
            Print("Sharpie Short Stop Loss @ "+NormalizeDouble(Close[1],4));}
            
            
///Exit Short (RSI2 divergence down)    
    else if( OrderType()==OP_SELL && OrderMagicNumber()!=48 && OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=55 && OrderProfit()>0 && 
    lastflow !=500 && Ask<OrderOpenPrice()-50*Point ) 
           {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Yellow );
            Print("RSI2 Cropper Closed Short @ "+MarketInfo(OrderSymbol(), MODE_ASK)+"  for  ", OrderProfit());}    
            

////Exit Short (Overdrive Down)    
    else if( OrderType()==OP_SELL && OrderMagicNumber()!=48 && OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=55 && OrderProfit()>0 && 
    ExtMapBuffer2[0]==EMPTY_VALUE && ExtMapBuffer2[1]==15 && ExtMapBuffer2[2]==EMPTY_VALUE) 
           {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Yellow );
            Print("Star Cropper Closed Short @ "+MarketInfo(OrderSymbol(), MODE_ASK)+"  for  ", OrderProfit());}     
            
////Exit Short (Golfer On Bottom)    
    else if( OrderType()==OP_SELL && OrderMagicNumber()!=48 && OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=55 && OrderMagicNumber()!=0 && OrderProfit()>0 && 
    omegam[0]>0 && RSI2[0]>44 && RSI2[1]<25 && RSI2[2]>40
   // && Ask<OrderOpenPrice-10*Point 
    ) 
           {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Yellow );
            Print("Golfer Cropper Closed Short @ "+MarketInfo(OrderSymbol(), MODE_ASK)+"  for  ", OrderProfit());}                   


/////////4% cropper

   if   (OrderType()==OP_SELL && Close[0]>minus[0] &&  OrderProfit()>AccountBalance()*.045 && omega[0]>0 && OrderMagicNumber()!=0 && OrderMagicNumber()!=96 && OrderMagicNumber()!=93 && OrderMagicNumber()!=196 &&  OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=55 && OrderMagicNumber()!=55 && OrderMagicNumber()!=56 && OrderMagicNumber()!=0 ) 
         {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Yellow );
            Print("4% Cropper Closed Trade @ "+MarketInfo(OrderSymbol(), Close[0])+"  for  ", OrderProfit());}   


     if   (OrderType()==OP_BUY && Close[0]<plus[0] && OrderProfit()>AccountBalance()*.045 && omega[0]>0 && OrderMagicNumber()!=0 && OrderMagicNumber()!=96 && OrderMagicNumber()!=93 && OrderMagicNumber()!=196 &&  OrderMagicNumber()!=50 && OrderMagicNumber()!=51 && OrderMagicNumber()!=52 && OrderMagicNumber()!=53 && OrderMagicNumber()!=55 && OrderMagicNumber()!=55 && OrderMagicNumber()!=56 && OrderMagicNumber()!=0 ) 
          {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Yellow );
           Print("4% Cropper Closed Trade @ "+MarketInfo(OrderSymbol(), Close[0])+"  for  ", OrderProfit());}  

   
     
/////////-4.5% cropper     
     
        if   (OrderType()==OP_SELL && OrderProfit()*-1>AccountBalance()*.045  ) 
       //&& OrderOpenPrice()>Close[0]+80*Point  
         
         {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Yellow );
            Print("-4.5% Cropper Closed Trade @ "+MarketInfo(OrderSymbol(), Close[0])+"  for  ", OrderProfit());}   


     if   (OrderType()==OP_BUY && OrderProfit()*-1>AccountBalance()*.045  ) 
      
      //&& OrderOpenPrice()<Close[0]-80*Point
          {OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Yellow );
           Print("-4.5% Cropper Closed Trade @ "+MarketInfo(OrderSymbol(), Close[0])+"  for  ", OrderProfit());}  

     }
     
     
     
}




//////////////////Smart Trail Stop

for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
        
 
     




///lock in 1.5 pip after 4 in gains

        
// if (OrderType() == OP_BUY && OrderMagicNumber() !=50 && OrderMagicNumber() !=66 && OrderStopLoss()!=0  &&  OrderStopLoss()!=0.3 && OrderStopLoss()!=0.5 && OrderStopLoss()!=0.6 && OrderStopLoss()!=0.7 && OrderStopLoss()!=0.01
//  ) 
//     if (Bid>OrderOpenPrice()+40*Point && OrderOpenPrice()+40*Point>OrderStopLoss() && OrderOpenPrice()+30*Point>OrderStopLoss()){
  //               Print("bUY sTOP lOSS ATTEMPT ", OrderTicket());
//              if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()+15*Point,6), OrderTakeProfit(), Red))
//          Print("Error setting Buy trailing stop: ", GetLastError());
//      }
       
// if (OrderType() == OP_SELL && OrderStopLoss()!=0 && OrderMagicNumber() !=52 && OrderMagicNumber() !=66 && OrderStopLoss()!=5 && OrderStopLoss()!=6 && OrderStopLoss()!=7 && OrderStopLoss()!=10
//       && OrderStopLoss()!=3 
//    )
//     if  (Ask<OrderOpenPrice()-40*Point && OrderOpenPrice()-40*Point<OrderStopLoss() && OrderOpenPrice()-30*Point<OrderStopLoss()
//       ) {
  
 //    Print("sELL sTOP lOSS ATTEMPT ", OrderTicket());
//      if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()-15*Point,6), OrderTakeProfit(), Red)) 
//         Print("Error setting Sell trailing stop: ", GetLastError());
//  }



///lock in 3 pips after 8 in gains

        
 if (OrderType() == OP_BUY && OrderMagicNumber() !=50 && OrderMagicNumber() !=66 && OrderStopLoss()!=0  &&  OrderStopLoss()!=0.3 && OrderStopLoss()!=0.5 && OrderStopLoss()!=0.6 && OrderStopLoss()!=0.7 && OrderStopLoss()!=0.01
  ) 
     if (Bid>OrderOpenPrice()+80*Point && OrderOpenPrice()+80*Point>OrderStopLoss()  && OrderOpenPrice()+10*Point>OrderStopLoss()){
      //           Print("bUY sTOP lOSS ATTEMPT ", OrderTicket());
              if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()+30*Point,6), OrderTakeProfit(), Red))
          Print("Error setting Buy trailing stop: ", GetLastError());
      }
       
 if (OrderType() == OP_SELL && OrderStopLoss()!=0 && OrderMagicNumber() !=52 && OrderMagicNumber() !=66 && OrderStopLoss()!=5 && OrderStopLoss()!=6 && OrderStopLoss()!=7 && OrderStopLoss()!=10
       && OrderStopLoss()!=3 
    )
     if  (Ask<OrderOpenPrice()-80*Point && OrderOpenPrice()-80*Point<OrderStopLoss() && OrderOpenPrice()-30*Point<OrderStopLoss()
       ) {
  
    // Print("sELL sTOP lOSS ATTEMPT ", OrderTicket());
      if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()-30*Point,6), OrderTakeProfit(), Red)) 
         Print("Error setting Sell trailing stop: ", GetLastError());
  }
  
  

         

///lock in 3 pips after ? 
        
///        if (OrderType() == OP_BUY &&  OrderMagicNumber() !=50 && OrderStopLoss()!=0 && OrderMagicNumber() !=66 && OrderStopLoss()!=0.2)
///     if (OrderStopLoss()!=NormalizeDouble(OrderOpenPrice()+20*Point,6) && (iHigh(symbol,5,0)-FSize/4*10*Point> orderstoploss  || (iHigh(symbol,5,0)-FSize/4*10*Point> OrderOpenPrice() &&  orderstoploss==0) || ( iHigh(symbol,5,0)-20*Point> OrderOpenPrice() && TimeCurrent()-OrderOpenTime()>=18000)) && (iHigh(symbol,5,0)-FSize/4*10*Point< OrderOpenPrice() && iHigh(symbol,5,0)-FSize/3*10*Point> OrderOpenPrice() )
///     && OrderStopLoss()<NormalizeDouble(OrderOpenPrice()+30*Point,6) 
///     ){
///                 Print("bUY sTOP lOSS ATTEMPT ", OrderTicket());
///              if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()+30*Point,6), OrderTakeProfit(), Red))
///          Print("Error setting Buy trailing stop: ", GetLastError());
///      }
///       if (OrderType() == OP_SELL &&  OrderMagicNumber() !=52 && OrderStopLoss()!=0 && OrderMagicNumber() !=66 && OrderStopLoss()!=2)
///       if (OrderStopLoss()!=NormalizeDouble(OrderOpenPrice()-20*Point,6) &&(iLow(symbol,5,0)+FSize/4*10*Point < orderstoploss || (iLow(symbol,5,0)+FSize/4*10*Point<OrderOpenPrice() && orderstoploss==0)  || (iLow(symbol,5,0)+20*Point<OrderOpenPrice() && TimeCurrent()-OrderOpenTime()>=18000)) && (iLow(symbol,5,0)+FSize/4*10*Point>OrderOpenPrice() && iLow(symbol,5,0)+FSize/3*10*Point < OrderOpenPrice()) 
///       && OrderStopLoss()>NormalizeDouble(OrderOpenPrice()-30*Point,6) ) {
  //
///     Print("sELL sTOP lOSS ATTEMPT ", OrderTicket());
///      if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()-30*Point,6), OrderTakeProfit(), Red)) 
///         Print("Error setting Sell trailing stop: ", GetLastError());
//  }
        

/////////3 & 0.3  lock in 64 pips after 64+ in gains

       if (OrderType() == OP_BUY && OrderMagicNumber() !=50 && OrderMagicNumber() !=66 && OrderStopLoss()==0.3 && OrderStopLoss()!=0.5 && OrderStopLoss()!=0.6 && OrderStopLoss()!=0.7 && OrderStopLoss()!=0.01)
     if (OrderStopLoss()!=NormalizeDouble(OrderOpenPrice()+20*Point,6) && (iHigh(symbol,5,0)-FSize/3*10*Point> orderstoploss  || (iHigh(symbol,5,0)-FSize/2*10*Point> OrderOpenPrice() &&  orderstoploss==0) || ( iHigh(symbol,5,0)-40*Point> OrderOpenPrice() && TimeCurrent()-OrderOpenTime()>=18000)) && (iHigh(symbol,5,0)-FSize/2*10*Point< OrderOpenPrice() && iHigh(symbol,5,0)-FSize/3*10*Point> OrderOpenPrice() )
     && OrderStopLoss()<NormalizeDouble(OrderOpenPrice()+640*Point,6) 
     ){
        //         Print("bUY sTOP lOSS ATTEMPT ", OrderTicket());
              if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()+640*Point,6), OrderTakeProfit(), Red))
          Print("Error setting Buy trailing stop: ", GetLastError());
      }
       if (OrderType() == OP_SELL && OrderMagicNumber() !=52 && OrderMagicNumber() !=66 && OrderStopLoss()==3 && OrderStopLoss()!=5  && OrderStopLoss()!=6 && OrderStopLoss()!=7 && OrderStopLoss()!=10)
       if (OrderStopLoss()!=NormalizeDouble(OrderOpenPrice()-20*Point,6) &&(iLow(symbol,5,0)+FSize/3*10*Point < orderstoploss || (iLow(symbol,5,0)+FSize/2*10*Point<OrderOpenPrice() && orderstoploss==0)  || (iLow(symbol,5,0)+40*Point<OrderOpenPrice() && TimeCurrent()-OrderOpenTime()>=18000)) && (iLow(symbol,5,0)+FSize/2*10*Point>OrderOpenPrice() && iLow(symbol,5,0)+FSize/3*10*Point < OrderOpenPrice()) 
       &&  OrderStopLoss()>NormalizeDouble(OrderOpenPrice()-640*Point,6) 
       ) {
  //
   //  Print("sELL sTOP lOSS ATTEMPT ", OrderTicket());
      if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()-640*Point,6), OrderTakeProfit(), Red)) 
         Print("Error setting Sell trailing stop: ", GetLastError());
  }
        

////trail 16 pips behind
        
        
       if ((OrderType() == OP_BUY  && OrderMagicNumber() != magic_number && OrderMagicNumber() != magic_number2  &&  OrderMagicNumber() != magic_number3 && OrderStopLoss()!=0 && OrderStopLoss()!=0.5 && OrderStopLoss()!=0.6 && OrderStopLoss()!=0.7 && OrderStopLoss()!=0.01
     &&  OrderMagicNumber() != magic_number4 &&  OrderMagicNumber() != magic_number5   && OrderMagicNumber()!=92 && OrderMagicNumber()!=93       // &&  OrderMagicNumber() != 301 
     && OrderMagicNumber() !=303 
     &&  OrderMagicNumber() != 101 && OrderMagicNumber() !=103 && OrderMagicNumber() !=104 
     && !(OrderMagicNumber()==exempt_magic_number && AccountBalance()/AccountEquity()>.9)) && (iHigh(symbol,5,0)-FSize/4*10*Point > OrderStopLoss() && (iHigh(symbol,5,0)-200*Point > OrderOpenPrice() ||  (iHigh(symbol,5,0)-200*Point > OrderOpenPrice() && OrderStopLoss()==0)) ) 
     &&  OrderStopLoss()<NormalizeDouble(iHigh(symbol,5,0)-FSize/4*10*Point,6)
     )
      {
   //    Print("bUY sTOP lOSS aTTEMPT ", OrderTicket());
              if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(iHigh(symbol,5,0)-FSize/4*10*Point,6), OrderTakeProfit(), Red))
          Print("Error setting Buy trailing stop: ", GetLastError());
      }
       if ((OrderType() == OP_SELL  && OrderMagicNumber() != magic_number && OrderMagicNumber() != magic_number2  &&  OrderMagicNumber() != magic_number3 && OrderStopLoss()!=0 && OrderStopLoss()!=5 && OrderStopLoss()!=6 && OrderStopLoss()!=7 && OrderStopLoss()!=10
       &&  OrderMagicNumber() != magic_number4 &&  OrderMagicNumber() != magic_number5   && OrderMagicNumber()!=92 && OrderMagicNumber()!=93
       &&  OrderMagicNumber() != 302 
       && iLow(symbol,5,0)+FSize/4*10*Point < OrderOpenPrice()
       && OrderMagicNumber() !=304 
       &&  OrderMagicNumber() != 101 && OrderMagicNumber() !=103 && OrderMagicNumber() !=104 
        &&  OrderMagicNumber() !=51 &&  OrderMagicNumber() !=52
       && !(OrderMagicNumber()==exempt_magic_number && AccountBalance()/AccountEquity()>.9) ) && (iLow(symbol,5,0)+FSize/4*10*Point < OrderStopLoss() && (iLow(symbol,5,0)+200*Point < OrderOpenPrice() || (iLow(symbol,5,0)+200*Point <OrderOpenPrice() &&  OrderStopLoss()==0))  ) 
       
       && OrderStopLoss()>NormalizeDouble(iLow(symbol,5,0)+FSize/4*10*Point,6)
        )
    {
//     Print("sELL sTOP lOSS aTTEMPT ", OrderTicket());
      if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(iLow(symbol,5,0)+FSize/4*10*Point,6), OrderTakeProfit(), Red)) 
         Print("Error setting Sell trailing stop: ", GetLastError());
  }     
      
}



        
///////////////////////// D-Day Hedger

nlongs=GetNlongSize();
nshorts=GetNshortSize();
 if (nlongs<nshorts && !(omegam[1]<0 && omegam[0]>0) && omega[1]<0 && omega[0]>0 && (nshorts-nlongs)/2>0
   && !((Low[1]< iMA(symbol,0,414,0,MODE_EMA, PRICE_HIGH,1)+FMax*10*Point || Low[2]< iMA(symbol,0,414,0,MODE_EMA, PRICE_HIGH,2)+FMax*10*Point || Low[3]< iMA(symbol,0,414,0,MODE_EMA, PRICE_HIGH,3)+FMax*10*Point) && Close[0]> iMA(symbol,0,414,0,MODE_EMA, PRICE_HIGH,0)+FMax*10*Point)
 
 ) {
  //|| (RSI2[8]<77 && RSI2[7]<77 && RSI2[6]>77 && RSI2[4]<RSI2[6] && stoch[6]<30 && stoch[7]<30))
  
    open_price9 = NormalizeDouble(Ask, Digits);
    stop_loss_price9 = NormalizeDouble(0.1,Digits);
    take_profit_price9 = NormalizeDouble(0,Digits);

 for (i = OrdersTotal() - 1; i >= 0; i--)

      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number9) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_BUY)
            break;
        }
    if (i < 0)
      if (OrderSend(symbol, OP_BUY,  NormalizeDouble((nshorts-nlongs)/2,2), open_price9, 3, stop_loss_price9, take_profit_price9, "D-DAY HEDGER BUY 0/0",  magic_number9) < 0)
        
               Print("Error: ", ErrorDescription(_LastError));
  }
      
              


 // Both OmegaM and Omega Full Hedge for shorts  
 nlongs=GetNlongSize();
nshorts=GetNshortSize();
             
 if (nlongs<nshorts && omegam[1]<0 && omegam[0]>0 && omega[1]<0 && omega[0]>0 && (nshorts-nlongs)/2>0
 
  && !((Low[1]< iMA(symbol,0,414,0,MODE_EMA, PRICE_HIGH,1)+FMax*10*Point || Low[2]< iMA(symbol,0,414,0,MODE_EMA, PRICE_HIGH,2)+FMax*10*Point || Low[3]< iMA(symbol,0,414,0,MODE_EMA, PRICE_HIGH,3)+FMax*10*Point) && Close[0]> iMA(symbol,0,414,0,MODE_EMA, PRICE_HIGH,0)+FMax*10*Point)
  
   ) {
  //|| (RSI2[8]<77 && RSI2[7]<77 && RSI2[6]>77 && RSI2[4]<RSI2[6] && stoch[6]<30 && stoch[7]<30))
    open_price10 = NormalizeDouble(Ask, Digits);
    stop_loss_price10 = NormalizeDouble(0.2,Digits);
    take_profit_price10 = NormalizeDouble(0,Digits);

 for (i = OrdersTotal() - 1; i >= 0; i--)

      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number10) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_BUY) 
            break;
        }
    if (i < 0)
      if (OrderSend(symbol, OP_BUY,  NormalizeDouble((nshorts-nlongs)/2,2), open_price10, 3, stop_loss_price10, take_profit_price10, "D-DAY HEDGER BUY 0/0",  magic_number10) < 0)
        
               Print("Error: ", ErrorDescription(_LastError));
  }
                 
                    
              
 
              
              
// Not OmegaM only Omega Full Hedge For Longs or cross down
nlongs=GetNlongSize();
nshorts=GetNshortSize();

 if (nshorts<nlongs && (nlongs-nshorts)/2>0 && (( R2Sell) || (
 
 ( (!(omegam[1]>0 && omegam[0]<0) && omega[1]>0 && omega[0]<0) 
 || (High[9]>plus[9] && High[8]>plus[8] && High[7]>plus[7] && High[6]>plus[6] && High[5]>plus[5] && High[4]>plus[4] && High[3]>plus[3] && iHigh(symbol,30,2)<plus[2] && iHigh(symbol,30,3)>plus[3])))
 || (Low[10]<minus[10] && Low[9]<minus[9] && Low[8]<minus[8] && Low[7]<minus[7] && Low[6]<minus[6] && Low[5]<minus[5] && Low[4]<plus[4]  && Low[3]<plus[3] && iLow(symbol,30,2)>minus[2] && iLow(symbol,30,3)<minus[3]) 
 
 && !((High[1]> iMA(symbol,0,414,0,MODE_EMA, PRICE_LOW,1)-FMax*10*Point || High[2]> iMA(symbol,0,414,0,MODE_EMA, PRICE_LOW,2)-FMax*10*Point || High[3]> iMA(symbol,0,414,0,MODE_EMA, PRICE_LOW,3)-FMax*10*Point) && Close[0]< iMA(symbol,0,414,0,MODE_EMA, PRICE_LOW,0)-FMax*10*Point)
 )) {
  //|| (RSI2[8]>23 && RSI2[7]>23 && RSI2[6]<23 && RSI2[4]>RSI2[6] && stoch[6]>77 && stoch[7]>77))
    open_price11 = NormalizeDouble(Bid, Digits);
    stop_loss_price11 = NormalizeDouble(2,Digits);
    take_profit_price11 = NormalizeDouble(0,Digits);
    for (i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number11) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_SELL)
            break;
        }
    if (i < 0){
    if (iHigh(symbol,30,2)<plus[2] && iHigh(symbol,30,3)>plus[3])   if (OrderSend(symbol, OP_SELL, NormalizeDouble((nlongs-nshorts)/2,2), open_price11, 3, stop_loss_price11, take_profit_price11, "X-DAY HEDGER SELL 0/0", magic_number11) < 0)
        Print("Error: ", ErrorDescription(_LastError));
    
    else  if (OrderSend(symbol, OP_SELL, NormalizeDouble((nlongs-nshorts)/2,2), open_price11, 3, stop_loss_price11, take_profit_price11, "X-DAY HEDGER SELL 0/0", magic_number11) < 0)
        Print("Error: ", ErrorDescription(_LastError));
  }}
      
                   
 
 // Both OmegaM and Omega Full Hedge For Longs or cross up
 nlongs=GetNlongSize();
nshorts=GetNshortSize();
 
 if ((nshorts<nlongs && omegam[1]>0 && omegam[0]<0 && omega[1]>0 && omega[0]<0)
 || (Low[10]<minus[10] && Low[9]<minus[9] && Low[8]<minus[8] && Low[7]<minus[7] && Low[6]<minus[6] && Low[5]<minus[5] && Low[4]<plus[4]  && Low[3]<plus[3] && iLow(symbol,30,2)>minus[2] && iLow(symbol,30,3)<minus[3]) 
 && !((High[1]> iMA(symbol,0,414,0,MODE_EMA, PRICE_LOW,1)-FMax*10*Point || High[2]> iMA(symbol,0,414,0,MODE_EMA, PRICE_LOW,2)-FMax*10*Point || High[3]> iMA(symbol,0,414,0,MODE_EMA, PRICE_LOW,3)-FMax*10*Point) && Close[0]< iMA(symbol,0,414,0,MODE_EMA, PRICE_LOW,0)-FMax*10*Point)
 ) {
  
  //|| (RSI2[8]>23 && RSI2[7]>23 && RSI2[6]<23 && RSI2[4]>RSI2[6] && stoch[6]>77 && stoch[7]>77))
  
    open_price12 = NormalizeDouble(Bid, Digits);
    stop_loss_price12 = NormalizeDouble(3,Digits);
    take_profit_price12 = NormalizeDouble(0,Digits);
    for (i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number12) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_SELL)
            break;
        }
    if (i < 0){
      if (iLow(symbol,30,2)>minus[2] && iLow(symbol,30,3)<minus[3]) if (OrderSend(symbol, OP_SELL, NormalizeDouble((nlongs-nshorts)/2,2), open_price12, 3, stop_loss_price12, take_profit_price12, "X-DAY HEDGER SELL 0/0", magic_number12) < 0)
        Print("Error: ", ErrorDescription(_LastError));
      
      else if (OrderSend(symbol, OP_SELL, NormalizeDouble((nlongs-nshorts)/2,2), open_price12, 3, stop_loss_price12, take_profit_price12, "X-DAY HEDGER SELL 0/0", magic_number12) < 0)
        Print("Error: ", ErrorDescription(_LastError));}
  }
   


if (Equity_Based_Hedge) {


////////////////////////////////////////////////////
nlongs=0;
nshorts=0;

 counter = 0;
 no50b=0;
 no50s=0;
 no51b=0;
 no51s=0;
 no52b=0;
 no52s=0;
 no53b=0;
 no53s=0; 

overdrivecounter =0;

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
          // if ( Symbol()=="EURUSD" && OrderStopLoss()==0 ) {
          // Print("OderProfit: ", OrderProfit());
          
          //Print("AB:",AccountBalance()*-1*.025);
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==53 ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==50) no50b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==50) no50s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==51) no51b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==51) no51s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==52) no52b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==52) no52s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==53) no53b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==53) no53s++;
             
             
       //      Print("OrderLots()*8:", OrderLots()*.8);
       //      Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
         // }
   }
   
   
  
//  Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
  
  
if (rope_trade_allowed && no50b==0 && iRSI(symbol,1440,2,PRICE_MEDIAN,1)<92) {

    if (nlongs<nshorts && ((comparison<Ratio+.05 && comparison>Ratio)  || (AccountMargin()>0 && AccountEquity()/AccountBalance()<1 && AccountEquity() / AccountMargin() * 100<MarginCallPercentage*2) ) ) {
    open_price = NormalizeDouble(Ask, Digits);
    stop_loss_price = NormalizeDouble(0.1,Digits);
    take_profit_price = NormalizeDouble(0,Digits);

 for (i = OrdersTotal() - 1; i >= 0; i--)

      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == 50) {
          order_type = OrderType();
         if (order_type == ORDER_TYPE_BUY)
            break;
        }
    if (i < 0)
      if (OrderSend(symbol, OP_BUY,  NormalizeDouble((nshorts-nlongs)/3,2), open_price, 3, stop_loss_price, take_profit_price, 50+" RATIO HEDGER ROPE BUY 0/0",  50,1) < 0)
        
               Print("Error - Buy - Rope Trade: ", ErrorDescription(_LastError));
  }

   Sleep(1800);
   }

nlongs=0;
nshorts=0;

 counter = 0;
 no50b=0;
 no50s=0;
 no51b=0;
 no51s=0;
 no52b=0;
 no52s=0;
 no53b=0;
 no53s=0; 
   
 overdrivecounter =0;

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
          // if ( Symbol()=="EURUSD" && OrderStopLoss()==0 ) {
          // Print("OderProfit: ", OrderProfit());
          
          //Print("AB:",AccountBalance()*-1*.025);
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==53 ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==50) no50b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==50) no50s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==51) no51b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==51) no51s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==52) no52b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==52) no52s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==53) no53b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==53) no53s++;
             
             
       //      Print("OrderLots()*8:", OrderLots()*.8);
       //      Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
         // }
   } 
   
  // Half Hedge for shorts
  if (nlongs<nshorts && ((comparison<Ratio && comparison>Ratio-.05))  && no51b==0 && NormalizeDouble((nshorts-nlongs)/2,2)>.01 && iRSI(symbol,1440,2,PRICE_MEDIAN,1)<92) {
  
 // RemoveStopsandTargets();
    open_price = NormalizeDouble(Ask, Digits);
    stop_loss_price = NormalizeDouble(0.2,Digits);
    take_profit_price = NormalizeDouble(0,Digits);

 for (i = OrdersTotal() - 1; i >= 0; i--)

      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == 51) {
          order_type = OrderType();
         if (order_type == ORDER_TYPE_BUY)
            break;
        }
    if (i < 0)
      if (OrderSend(symbol, OP_BUY,  NormalizeDouble((nshorts-nlongs)/2,2), open_price, 3, stop_loss_price, take_profit_price, 51+" RATIO HEDGER HALF BUY 0/0",  51,1) < 0)
        
               Print("Error - Buy - Half Hedge: ", ErrorDescription(_LastError));
  }

   Sleep(1800);           
              
nlongs=0;
nshorts=0;

 counter = 0;
 no50b=0;
 no50s=0;
 no51b=0;
 no51s=0;
 no52b=0;
 no52s=0;
 no53b=0;
 no53s=0; 
overdrivecounter =0;

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
          // if ( Symbol()=="EURUSD" && OrderStopLoss()==0 ) {
          // Print("OderProfit: ", OrderProfit());
          
          //Print("AB:",AccountBalance()*-1*.025);
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==53 ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==50) no50b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==50) no50s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==51) no51b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==51) no51s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==52) no52b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==52) no52s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==53) no53b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==53) no53s++;
             
             
       //      Print("OrderLots()*8:", OrderLots()*.8);
       //      Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
         // }
   }
 
double overhedge_long = (nshorts-nlongs)*1.25;
if (embeddedoversold)   overhedge_long = (nshorts-nlongs)*0.75;
   
    if (overhedging_allowed &&  Close[0]>iMA(symbol,30,135,0,MODE_EMA, PRICE_HIGH,0) && overdrivecounter<1 && no53b==0 && iRSI(symbol,1440,2,PRICE_MEDIAN,1)<92) {
    if (nlongs<nshorts && ((comparison<Ratio-.05 && comparison>Ratio-.1)  || (AccountMargin()!=0 && AccountEquity() / AccountMargin() * 100<MarginCallPercentage*1.5))  && iLow(symbol,30,iLowest(symbol,30,MODE_LOW,4,1))+FSize*10*Point>Ask+100*Point) {
  
    open_price = NormalizeDouble(Ask, Digits);
    stop_loss_price = NormalizeDouble(0.1,Digits);
    take_profit_price = NormalizeDouble(0,Digits);

 for (i = OrdersTotal() - 1; i >= 0; i--)

      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == 53) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_BUY)
            break;
        }
        
        if (i < 0)
        
      if (OrderSend(symbol, OP_BUY,  NormalizeDouble(overhedge_long,2), open_price, 3, stop_loss_price, take_profit_price,  53+" RATIO HEDGER OVERDRIVE BUY 0/0",  53,1) < 0)
        
               Print("Error - Buy - Over Hedge: ", ErrorDescription(_LastError));
  }
 
  Sleep(1800);
  }


nlongs=0;
nshorts=0;

 counter = 0;
 no50b=0;
 no50s=0;
 no51b=0;
 no51s=0;
 no52b=0;
 no52s=0;
 no53b=0;
 no53s=0; 
overdrivecounter =0;

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
          // if ( Symbol()=="EURUSD" && OrderStopLoss()==0 ) {
          // Print("OderProfit: ", OrderProfit());
          
          //Print("AB:",AccountBalance()*-1*.025);
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==53 ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==50) no50b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==50) no50s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==51) no51b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==51) no51s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==52) no52b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==52) no52s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==53) no53b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==53) no53s++;
             
             
       //      Print("OrderLots()*8:", OrderLots()*.8);
       //      Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
         // }
   }

//Print("comparison<(Ratio-.1): ", comparison<(Ratio-.1));
//Print("nlongs<nshorts: ", nlongs<nshorts);     
              
double fullhedge_long = nshorts-nlongs;

//Print("fullhedge_long: ", fullhedge_long);    

if (embeddedoversold && !peaktrending[0]) fullhedge_long=(nshorts-nlongs)/2;

  // Full Hedge for shorts
  if ((nlongs<nshorts && comparison<(Ratio-.1))  || (ExtMapBuffer3[1]==EMPTY_VALUE && ExtMapBuffer3[1]!=EMPTY_VALUE && doji[1]!=EMPTY_VALUE) ) {
  
 if (comparison<(Ratio-.1) && comparison>(Ratio-.15) ) RemoveStopsandTargets();
    open_price = NormalizeDouble(Ask, Digits);
    stop_loss_price = NormalizeDouble(0.0,Digits);
    take_profit_price = NormalizeDouble(0,Digits);

 for (i = OrdersTotal() - 1; i >= 0; i--)

      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == 52) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_BUY)
            break;
        }
    if (i < 0)
      if (OrderSend(symbol, OP_BUY,  NormalizeDouble(fullhedge_long,2), open_price, 3, stop_loss_price, take_profit_price, 52+" RATIO HEDGER BUY 0/0",  52,1) < 0)
        
               Print("Error - Buy - Full Hedge: ", ErrorDescription(_LastError));
  }
   
   Sleep(1800);   
                   
              
 bool found52L=False;
 for(i=OrdersTotal()-1; i>=0 ; i--)
 {                 
  if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==52 && nlongs!=nshorts && Ask<OrderOpenPrice()-300*Point) found52L=True;
              }
}

  
   nlongs=0;
nshorts=0;
           
 counter = 0;
 no50b=0;
 no50s=0;
 no51b=0;
 no51s=0;
 no52b=0;
 no52s=0;
 no53b=0;
 no53s=0;               
overdrivecounter =0;

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
          // if ( Symbol()=="EURUSD" && OrderStopLoss()==0 ) {
          // Print("OderProfit: ", OrderProfit());
          
          //Print("AB:",AccountBalance()*-1*.025);
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==53 ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==50) no50b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==50) no50s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==51) no51b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==51) no51s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==52) no52b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==52) no52s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==53) no53b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==53) no53s++;
             
             
       //      Print("OrderLots()*8:", OrderLots()*.8);
       //      Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
         // }
   }
                
              
 //if (AccountMargin()!=0) Print("AccountEquity() / AccountMargin()) * 100 = "+AccountEquity() / AccountMargin() * 100); 
 // Print("MCPCR: "+MarginCallPercentage*2);      
 
 if (rope_trade_allowed && no50s==0) {              
              if (nshorts<nlongs && ((comparison<Ratio+.05 && comparison>Ratio)  
              || (AccountMargin()>0 && AccountEquity()/AccountBalance()<1 && AccountEquity() / AccountMargin() * 100 <MarginCallPercentage*1.5) ) ) {
  
     open_price = NormalizeDouble(Bid, Digits);
    stop_loss_price = NormalizeDouble(2,Digits);
    take_profit_price = NormalizeDouble(0,Digits);
    for (i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == 50) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_SELL)
            break;
        }
    if (i < 0)
      if (OrderSend(symbol, OP_SELL, NormalizeDouble((nlongs-nshorts)/3,2), open_price, 3, stop_loss_price, take_profit_price, 50+" RATIO HEDGER ROPE SELL 0/0", 50,1) < 0)
        Print("Error: ", ErrorDescription(_LastError));
  }
 
 
   Sleep(1800);
}              
 nlongs=0;
nshorts=0;

 counter = 0;
 no50b=0;
 no50s=0;
 no51b=0;
 no51s=0;
 no52b=0;
 no52s=0;
 no53b=0;
 no53s=0;  
overdrivecounter =0;

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
          // if ( Symbol()=="EURUSD" && OrderStopLoss()==0 ) {
          // Print("OderProfit: ", OrderProfit());
          
          //Print("AB:",AccountBalance()*-1*.025);
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==53 ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==50) no50b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==50) no50s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==51) no51b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==51) no51s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==52) no52b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==52) no52s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==53) no53b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==53) no53s++;
             
             
       //      Print("OrderLots()*8:", OrderLots()*.8);
       //      Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
         // }
   }   
 
 
  // Half Hedge For Longs
  if (nshorts<nlongs && ((comparison<Ratio && comparison>Ratio-.05)) && no51s==0 && NormalizeDouble((nlongs-nshorts)/2,2)>.01) {
  
  RemoveStopsandTargets();
    open_price = NormalizeDouble(Bid, Digits);
    stop_loss_price = NormalizeDouble(3,Digits);
    take_profit_price = NormalizeDouble(0,Digits);
    for (i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == 51) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_SELL) 
             break;
        }
    if (i < 0)
      if (OrderSend(symbol, OP_SELL, NormalizeDouble((nlongs-nshorts)/2,2), open_price, 3, stop_loss_price, take_profit_price, 51+" RATIO HEDGER HALF SELL 0/0", 51,1) < 0)
        Print("Error: ", ErrorDescription(_LastError));
  }
    Sleep(1800);

nlongs=0;
nshorts=0;

 counter = 0;
 no50b=0;
 no50s=0;
 no51b=0;
 no51s=0;
 no52b=0;
 no52s=0;
 no53b=0;
 no53s=0; 
overdrivecounter =0;

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
          // if ( Symbol()=="EURUSD" && OrderStopLoss()==0 ) {
          // Print("OderProfit: ", OrderProfit());
          
          //Print("AB:",AccountBalance()*-1*.025);
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==53 ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==50) no50b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==50) no50s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==51) no51b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==51) no51s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==52) no52b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==52) no52s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==53) no53b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==53) no53s++;
             
             
       //      Print("OrderLots()*8:", OrderLots()*.8);
       //      Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
         // }
   }           

 
if (overhedging_allowed &&  Close[0]<iMA(symbol,30,135,0,MODE_EMA, PRICE_LOW,0)&& overdrivecounter<1 && no53s==0) {              
   if (nshorts<nlongs && ((comparison<Ratio-.05 && comparison>Ratio-.1) || (AccountMargin()!=0 && AccountEquity() / AccountMargin() * 100<MarginCallPercentage*1.5))  && iHigh(symbol,30,iHighest(symbol,30,MODE_HIGH,4,1))-FSize*10*Point<Bid-100*Point) {
  
     open_price = NormalizeDouble(Bid, Digits);
    stop_loss_price = NormalizeDouble(0,Digits);
    take_profit_price = NormalizeDouble(0,Digits);
    for (i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == 53) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_SELL)
            break;}
       
    if (i < 0)
      if (OrderSend(symbol, OP_SELL, NormalizeDouble((nlongs-nshorts)*1.25,2), open_price, 3, stop_loss_price, take_profit_price, 53+" RATIO HEDGER OVERDRIVE 0/0", 53,1) < 0)
        Print("Error: ", ErrorDescription(_LastError));
  }
    Sleep(1800);
}              

 nlongs=0;
nshorts=0;

 counter = 0;
 no50b=0;
 no50s=0;
 no51b=0;
 no51s=0;
 no52b=0;
 no52s=0;
 no53b=0;
 no53s=0;  
overdrivecounter =0;

 for(i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
          // if ( Symbol()=="EURUSD" && OrderStopLoss()==0 ) {
          // Print("OderProfit: ", OrderProfit());
          
          //Print("AB:",AccountBalance()*-1*.025);
             if (OrderType() == OP_BUY) 
             {
               if (OrderMagicNumber()==53  ) { nlongs = nlongs+OrderLots()*.8; overdrivecounter=overdrivecounter+1;}
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nlongs = nlongs+OrderLots();
               longcount = longcount+1;
               longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots()); 
                  
             }  
               
             if (OrderType() == OP_SELL )
             {
               if (OrderMagicNumber()==53 ) { nshorts = nshorts+OrderLots()*.8; overdrivecounter=overdrivecounter+1;} 
                 else if (OrderMagicNumber()==105) overdrivecounter=overdrivecounter+1;  
               else nshorts = nshorts+OrderLots(); 
               shortcount = shortcount+1;         
               shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots()); 
             }
             if (OrderType() == OP_BUY && OrderMagicNumber()==50) no50b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==50) no50s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==51) no51b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==51) no51s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==52) no52b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==52) no52s++;
             if (OrderType() == OP_BUY && OrderMagicNumber()==53) no53b++;
             if (OrderType() == OP_SELL && OrderMagicNumber()==53) no53s++;
             
             
       //      Print("OrderLots()*8:", OrderLots()*.8);
       //      Print("NormalizeDouble((nshorts-nlongs)/2,2):", NormalizeDouble((nshorts-nlongs)/2,2));
         // }
   }  


double fullhedge_shorts = nlongs-nshorts;

//Print("fullhedge_long: ", fullhedge_long);    

if (embeddedoverbought && !peaktrending[0]) fullhedge_shorts=(nlongs-nshorts)/2;
              
              
// Full Hedge For Longs
 if ((nshorts<nlongs && comparison<(Ratio-.1)) || (ExtMapBuffer2[3]==EMPTY_VALUE && ExtMapBuffer2[1]!=EMPTY_VALUE && doji[1]!=EMPTY_VALUE) ) {
  
  if (comparison<(Ratio-.1) && comparison>(Ratio-.15) ) RemoveStopsandTargets();
    open_price = NormalizeDouble(Bid, Digits);
    stop_loss_price = NormalizeDouble(3,Digits);
    take_profit_price = NormalizeDouble(0,Digits);
    for (i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == 52) {
          order_type = OrderType();
         if (order_type == ORDER_TYPE_SELL)
            break;}
    if (i < 0)
      if (OrderSend(symbol, OP_SELL, NormalizeDouble(fullhedge_shorts,2), open_price, 3, stop_loss_price, take_profit_price, 52+" RATIO HEDGER SELL 0/0", 52,1) < 0)
        Print("Error: ", ErrorDescription(_LastError));
  }
               
 Sleep(1800);


}


/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
///opening longs

nlongs=GetNlongSize();
nshorts=GetNshortSize();
if (NormalizeDouble((nshorts-nlongs),2)>MaxLots) longsz = NormalizeDouble((nshorts-nlongs),2);
else longsz = NormalizeDouble(MaxLots/1.5,2);
if (longsz>MarketInfo(Symbol(),MODE_MAXLOT)) longsz=MarketInfo(Symbol(),MODE_MAXLOT); 

 
if ((nshorts>nlongs || nlongs==0 )  && longsz>0  && nlongs<MaxLots && iRSI(symbol,1440,2,PRICE_MEDIAN,1)>7  &&  iRSI(symbol,1440,2,PRICE_MEDIAN,0)>7  && iRSI(symbol,240,2,PRICE_MEDIAN,2)>7 && iRSI(symbol,240,2,PRICE_MEDIAN,1)>7 &&
     !(iRSI(symbol,1440,2,PRICE_MEDIAN,2)> 95 && iStochastic(symbol,1440,8,3,3,MODE_SMA,0,MODE_MAIN,2)>75) &&
     ((countback==0 && Close[1]-iLow(symbol,30,iLowest(symbol,30,MODE_LOW,26,1)<FSize/3*10*Point && countup>1)
         || ((Close[0]<iMA(symbol,30,414,0,MODE_EMA, PRICE_HIGH,0) && Close[0]>iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,0) ))  
         || ((Close[0]<iMA(symbol,30,135,0,MODE_EMA, PRICE_HIGH,0) && Close[0]>iMA(symbol,30,135,0,MODE_EMA, PRICE_LOW,0) && Close[0]>Open[1] ))

////golf buy at purple haze                

         || (embeddedoversold && RSI2[0]<60 && RSI2[1]>75 && RSI2[2]<75 && Close[0]<iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,i)-FMax*3*10*Point) 
         || (ExtMapBuffer2[2]==15 && ExtMapBuffer2[1]!=15)
         || lastflow !=500
                             ) 
                           
      )
      && !(RSI2[0]<60 && RSI2[1]>75 && RSI2[2]<75 && embeddedoversold && !Close[0]<iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,i)-FMax*3*10*Point)
&& !(High[0]>iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,0)-FMax*10*Point && iLow(Symbol(),30,iLowest(Symbol(),30,MODE_LOW,3,0))-40*Point<iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,0)-FMax*10*Point)
   && !(iLow(symbol,1440,0)<db14+2*pacing && (iHigh(symbol,1440,2)>db14+2*pacing   || iHigh(symbol,1440,3)>db14+2*pacing || iHigh(symbol,1440,4)>db14+2*pacing || iHigh(symbol,1440,5)>db14+2*pacing)) 
 && iHigh(symbol,30,iHighest(symbol,30,MODE_HIGH,26,1))-Close[0]>FSize/2*10*Point
 )
  {
  
   // if (RSI2[0]<60 && RSI2[1]>75 && RSI2[2]<75 && Close[0]<iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,i)-FMax*3*10*Point) open_price13 = NormalizeDouble(Ask,Digits);
   // else
    
     open_price13 = NormalizeDouble(iLow(Symbol(),30,iLowest(Symbol(),30,MODE_LOW,3,0))-40*Point,Digits);
//Print("db14+pacing: ", db14+pacing," Low[1]=",Low[1] );
 
 

 
 // Print("longsize: ", longsz); 
     if ( RSI2[0]<60 && RSI2[1]>75 && RSI2[2]<75) stop_loss_price13 = NormalizeDouble(0.1,Digits);
    else stop_loss_price13 = NormalizeDouble(0.2,Digits);
    take_profit_price13 = NormalizeDouble(0,Digits);
 for (i = OrdersTotal() - 1; i >= 0; i--)

      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number13) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_BUY_LIMIT) {
            if ((NormalizeDouble(OrderOpenPrice(), Digits) != open_price13) || (NormalizeDouble(OrderStopLoss(), Digits) != stop_loss_price13) || (NormalizeDouble(OrderTakeProfit(), Digits) != take_profit_price13)) {
              if (!OrderModify(OrderTicket(), open_price13, stop_loss_price13, take_profit_price13, OrderExpiration()))
                Print("Error: ", ErrorDescription(_LastError));
            }
            break;
          }
          else if (order_type == ORDER_TYPE_BUY)
            break;
        }
    if (i < 0){
    RemoveStopsandTargets();
    Print("longsize: ", longsz); 
      if (OrderSend(symbol, OP_BUYLIMIT,  longsz, open_price13, 3, stop_loss_price13, take_profit_price13, magic_number13+" Wish Upon - BLMT", magic_number13,1) < 0)
        Print("Error Opening Longs: ", ErrorDescription(_LastError));
  }}
else
    for (i = OrdersTotal() - 1; i >= 0; i--)
     if (TimeCurrent()-OrderOpenTime()>=ClosePendingInSeconds)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number13)
          if (OrderType() == ORDER_TYPE_BUY_LIMIT)
            if (!OrderDelete(OrderTicket()))
              Print("Error: ", ErrorDescription(_LastError));



///opening longs - BURN

nlongs=GetNlongSize();
nshorts=GetNshortSize();
if (NormalizeDouble((nshorts-nlongs),2)>MaxLots) longsz = NormalizeDouble((nshorts-nlongs),2);
else longsz = NormalizeDouble(MaxLots/1.5,2);
if (longsz>MarketInfo(Symbol(),MODE_MAXLOT)) longsz=MarketInfo(Symbol(),MODE_MAXLOT); 

 
if ((nshorts>nlongs || nlongs==0 )  && longsz>0  && nlongs<MaxLots && iRSI(symbol,1440,2,PRICE_MEDIAN,1)>7  &&  iRSI(symbol,1440,2,PRICE_MEDIAN,0)>7  && iRSI(symbol,240,2,PRICE_MEDIAN,2)>7 && iRSI(symbol,240,2,PRICE_MEDIAN,1)>7 &&
     !(iRSI(symbol,1440,2,PRICE_MEDIAN,2)> 95 && iStochastic(symbol,1440,8,3,3,MODE_SMA,0,MODE_MAIN,2)>75) &&
     ((embeddedoverbought && ExtUpFractalsBuffer[4]!=EMPTY_VALUE && High[4]>iHigh(Symbol(),0,iHighest(Symbol(),0,MODE_HIGH,8,5)) && High[4]-Low[1]>FSize/2*Point*10 && Low[0]>Low[1] && Low[3]<Low[4] && Low[2]<Low[3] )
          || (embeddedoverbought && ExtUpFractalsBuffer[4]!=EMPTY_VALUE && High[4]-Low[1]>FSize/2*Point*10 && Low[0]>Low[1] && Low[3]<Low[4] && Low[2]<Low[3] && (ExtMapBuffer2[4]!=EMPTY_VALUE || ExtMapBuffer2[3]!=EMPTY_VALUE || ExtMapBuffer2[2]!=EMPTY_VALUE  || ExtMapBuffer2[1]!=EMPTY_VALUE  ) )
                 ) 
      && !(RSI2[0]<60 && RSI2[1]>75 && RSI2[2]<75 && embeddedoversold && !Close[0]<iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,i)-FMax*3*10*Point)
&& !(High[0]>iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,0)-FMax*10*Point && iLow(Symbol(),30,iLowest(Symbol(),30,MODE_LOW,3,0))-40*Point<iMA(symbol,30,414,0,MODE_EMA, PRICE_LOW,0)-FMax*10*Point)
   && !(iLow(symbol,1440,0)<db14+2*pacing && (iHigh(symbol,1440,2)>db14+2*pacing   || iHigh(symbol,1440,3)>db14+2*pacing || iHigh(symbol,1440,4)>db14+2*pacing || iHigh(symbol,1440,5)>db14+2*pacing)) 
 && iHigh(symbol,30,iHighest(symbol,30,MODE_HIGH,26,1))-Close[0]>FSize/2*10*Point
 && longsz>0
 )
  {
  
    open_price14 = NormalizeDouble(iLow(Symbol(),30,iLowest(Symbol(),30,MODE_LOW,3,0))-40*Point,Digits);

     if ( RSI2[0]<60 && RSI2[1]>75 && RSI2[2]<75) stop_loss_price14 = NormalizeDouble(0.1,Digits);
    else stop_loss_price14 = NormalizeDouble(0.2,Digits);
    take_profit_price14 = NormalizeDouble(0,Digits);
 for (i = OrdersTotal() - 1; i >= 0; i--)

      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number14) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_BUY_LIMIT) {
            if ((NormalizeDouble(OrderOpenPrice(), Digits) != open_price14) || (NormalizeDouble(OrderStopLoss(), Digits) != stop_loss_price14) || (NormalizeDouble(OrderTakeProfit(), Digits) != take_profit_price14)) {
              if (!OrderModify(OrderTicket(), open_price14, stop_loss_price14, take_profit_price14, OrderExpiration()))
                Print("Error: ", ErrorDescription(_LastError));
            }
            break;
          }
          else if (order_type == ORDER_TYPE_BUY)
            break;
        }
    if (i < 0){
  //  RemoveStopsandTargets();
    Print("longsize: ", longsz); 
      if (OrderSend(symbol, OP_BUYLIMIT,  longsz, open_price14, 3, stop_loss_price14, take_profit_price14, magic_number14+" Wish Upon - BLMT", magic_number14,1) < 0)
        Print("Error Opening Longs - Burn: ", ErrorDescription(_LastError));
  }}
else
    for (i = OrdersTotal() - 1; i >= 0; i--)
     if (TimeCurrent()-OrderOpenTime()>=ClosePendingInSeconds)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number14)
          if (OrderType() == ORDER_TYPE_BUY_LIMIT)
            if (!OrderDelete(OrderTicket()))
              Print("Error: ", ErrorDescription(_LastError));

 
 
 
/// opening shorts 

nlongs=GetNlongSize();
nshorts=GetNshortSize();
if (NormalizeDouble((nlongs-nshorts),2)>MaxLots) shortsz = NormalizeDouble((nlongs-nshorts),2);
else shortsz = NormalizeDouble(MaxLots/1.5,2);        
if (shortsz>MarketInfo(Symbol(),MODE_MAXLOT)) shortsz=MarketInfo(Symbol(),MODE_MAXLOT); 


if ((nshorts<nlongs || nshorts==0 )  && shortsz>0 && buylevel<Bid-.001 && nshorts<MaxLots && MathAbs(iMA(symbol,30,414,0,MODE_EMA, PRICE_HIGH,1)-High[1])>FSize*10*Point
  && iRSI(symbol,1440,2,PRICE_MEDIAN,1)>5 && iRSI(symbol,1440,2,PRICE_MEDIAN,0)>5 && iRSI(symbol,1440,2,PRICE_MEDIAN,0)<90
   &&(
       (ExtMapBuffer3[0]==EMPTY_VALUE && ExtMapBuffer3[1]==EMPTY_VALUE && ExtMapBuffer3[2]==85)
    || (countup == 0 && RSI2[0]<92 && RSI2[1]>94)  
    || (iFractals(symbol,30,MODE_UPPER,1) && embeddedoversold && countup==1)
/////golfer sell        
    || (embeddedoversold && omega[0]<0 && RSI2[0]>44 && RSI2[1]<25 && RSI2[2]>40)
    || (ExtMapBuffer3[2]==85 && ExtMapBuffer3[1]!=85)
    || lastfhigh !=500
    )
    
        && !(Low[0]<iMA(symbol,30,414,0,MODE_EMA, PRICE_HIGH,0)+FMax*10*Point && iHigh(Symbol(),30,iHighest(Symbol(),30,MODE_HIGH,3,0))>iMA(symbol,30,414,0,MODE_EMA, PRICE_HIGH,0)+FMax*10*Point) 
        && Close[0]-iLow(symbol,30,iLowest(symbol,30,MODE_LOW,26,1))>FSize/2*10*Point 
        
        && shortsz>0
        )
   {
  
 // if (ddiu[2] && !ddiu[1] && !ddiu[3] ) Print("Should had opened a short here at market: ", i); 
    if ( RSI2[0]>44 && RSI2[1]<25 && RSI2[2]>40) open_price2 = NormalizeDouble(Bid,Digits);
    else open_price2 = NormalizeDouble(iHigh(Symbol(),30,iHighest(Symbol(),30,MODE_HIGH,3,0)),Digits);
   //else open_price = NormalizeDouble(longaveragebuffer/nlongs-2490*Point, Digits);
//  Print("shortsize: ", shortsz);
   if ( RSI2[0]>44 && RSI2[1]<25 && RSI2[2]>40) stop_loss_price2 = NormalizeDouble(2,Digits);
    else stop_loss_price2 = NormalizeDouble(3,Digits);
    take_profit_price2 = NormalizeDouble(0,Digits);
    for (i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number15) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_SELL)
            break;
        }
    if (i < 0){
 //     RemoveStopsandTargets();
      Print("shortsize: ", shortsz); 
      if (OrderSend(NULL, OP_SELLLIMIT, shortsz, open_price2, 3, stop_loss_price2, take_profit_price2, magic_number15+" Wish Upon - SLMT", magic_number15,1) < 0)
        Print("Error Opening Shorts: ", ErrorDescription(_LastError));
  }}
  else
    for (i = OrdersTotal() - 1; i >= 0; i--)
     if (TimeCurrent()-OrderOpenTime()>=ClosePendingInSeconds)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number15)
          if (OrderType() == ORDER_TYPE_SELL_LIMIT)
            if (!OrderDelete(OrderTicket()))
              Print("Error: ", ErrorDescription(_LastError));
 


/// opening shorts BURN

nlongs=GetNlongSize();
nshorts=GetNshortSize();
if (NormalizeDouble((nlongs-nshorts),2)>MaxLots) shortsz = NormalizeDouble((nlongs-nshorts),2);
else shortsz = NormalizeDouble(MaxLots/1.5,2);        
if (shortsz>MarketInfo(Symbol(),MODE_MAXLOT)) shortsz=MarketInfo(Symbol(),MODE_MAXLOT);

if ((nshorts<nlongs || nshorts==0 )  && shortsz>0 && buylevel<Bid-.001 && nshorts<MaxLots && MathAbs(iMA(symbol,30,414,0,MODE_EMA, PRICE_HIGH,1)-High[1])>FSize*10*Point
  && iRSI(symbol,1440,2,PRICE_MEDIAN,1)>5 && iRSI(symbol,1440,2,PRICE_MEDIAN,0)>5 && iRSI(symbol,1440,2,PRICE_MEDIAN,0)<90
   &&(
     ( embeddedoversold && ExtDownFractalsBuffer[4]!=EMPTY_VALUE && High[1]-Low[4]>FSize/2*Point && High[0]<High[1] && High[3]>High[4] && High[2]>High[3] && (ExtMapBuffer3[4]==85 || ExtMapBuffer3[3]==85 || ExtMapBuffer3[2]==85 || ExtMapBuffer3[1]==85  )  && ExtMapBuffer2[4]==EMPTY_VALUE && ExtMapBuffer2[5]==EMPTY_VALUE && ExtMapBuffer2[6]==EMPTY_VALUE  && ExtMapBuffer2[7]==EMPTY_VALUE )
    
     || ( embeddedoversold && ExtDownFractalsBuffer[4]!=EMPTY_VALUE && Low[4]<iLow(Symbol(),0,iLowest(Symbol(),0,MODE_LOW,8,5)) && High[1]-Low[4]>FSize/2*Point && High[0]<High[1] && High[3]>High[4] && High[2]>High[3] && ExtMapBuffer2[4]==EMPTY_VALUE && ExtMapBuffer2[5]==EMPTY_VALUE && ExtMapBuffer2[6]==EMPTY_VALUE  && ExtMapBuffer2[7]==EMPTY_VALUE  )
     
     
    )
    
        && !(Low[0]<iMA(symbol,30,414,0,MODE_EMA, PRICE_HIGH,0)+FMax*10*Point && iHigh(Symbol(),30,iHighest(Symbol(),30,MODE_HIGH,3,0))>iMA(symbol,30,414,0,MODE_EMA, PRICE_HIGH,0)+FMax*10*Point) 
        && Close[0]-iLow(symbol,30,iLowest(symbol,30,MODE_LOW,26,1))>FSize/2*10*Point 
       && shortsz>0 )
   {
  
  open_price2 = NormalizeDouble(iHigh(Symbol(),30,iHighest(Symbol(),30,MODE_HIGH,3,0))+30*Point,Digits);
   //else open_price = NormalizeDouble(longaveragebuffer/nlongs-2490*Point, Digits);
//  Print("shortsize: ", shortsz);
   if ( RSI2[0]>44 && RSI2[1]<25 && RSI2[2]>40) stop_loss_price2 = NormalizeDouble(2,Digits);
    else stop_loss_price2 = NormalizeDouble(3,Digits);
    take_profit_price2 = NormalizeDouble(0,Digits);
    for (i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number16) {
          order_type = OrderType();
          if (order_type == ORDER_TYPE_SELL_LIMIT) {
            if ((NormalizeDouble(OrderOpenPrice(), Digits) != open_price2) || (NormalizeDouble(OrderStopLoss(), Digits) != stop_loss_price2) || (NormalizeDouble(OrderTakeProfit(), Digits) != take_profit_price2)) {
              if (!OrderModify(OrderTicket(), open_price2, stop_loss_price2, take_profit_price2, OrderExpiration()))
                Print("Error: ", ErrorDescription(_LastError));
            }
            break;
          }
          else if (order_type == ORDER_TYPE_SELL)
            break;
        }
    if (i < 0){
  //    RemoveStopsandTargets();
      Print("shortsize: ", shortsz);  
      if (OrderSend(NULL, OP_SELLLIMIT, shortsz, open_price2, 3, stop_loss_price2, take_profit_price2, magic_number16+" Wish Upon - SLMT", magic_number16,1) < 0)
        Print("Error Opening Shorts - Burn: ", ErrorDescription(_LastError));
  }}
else
    for (i = OrdersTotal() - 1; i >= 0; i--)
     if (TimeCurrent()-OrderOpenTime()>=ClosePendingInSeconds)
      if (OrderSelect(i, SELECT_BY_POS))
        if (OrderMagicNumber() == magic_number16)
          if (OrderType() == ORDER_TYPE_SELL_LIMIT)
            if (!OrderDelete(OrderTicket()))
              Print("Error: ", ErrorDescription(_LastError));

       
  return(0);
}

bool CheckforInversion(int currentpos, int length)
{
  bool condition = False; 
   for(int k=currentpos; k<currentpos+length; k++)
      if (plus[k+7]<minus[k+7]) {condition=True; break;}
   return (condition);
}

bool CheckforTup(int currentpos, int length)
{
  bool condition = False; 
   for(int k=currentpos; k<currentpos+length; k++)
      if (tup[k]!=EMPTY_VALUE) {condition=True; break;}
   return (condition);
}

bool CheckforTdn(int currentpos, int length)
{
  bool condition = False; 
   for(int k=currentpos; k<currentpos+length; k++)
      if (tdn[k]!=EMPTY_VALUE) {condition=True; break;}
   return (condition);
}
 
double ChoppinessIndex(int period, int bar)
  {
    double Low0 = 0, High0 = 0, Close1 = 0;
    double TrueRangeLow = 0, TrueRangeHigh = 0, TrueRangeSum = 0, Input = 0;
    double PeriodTrueRangeLow = 999999999, PeriodTrueRangeHigh = 0, PeriodTrueRange = 0;

    for(int k=bar; k<bar+period; k++)
    {
      Low0   = iLow(NULL,240,k);
      High0  = iHigh(NULL,240,k);
      Close1 = iClose(NULL,240,k+1);

      if (Low0<Close1)  TrueRangeLow  = Low0;  else TrueRangeLow  = Close1;
      if (High0>Close1) TrueRangeHigh = High0; else TrueRangeHigh = Close1;
      
      if (TrueRangeLow <PeriodTrueRangeLow)  PeriodTrueRangeLow  = TrueRangeLow;  // find true low of period
      if (TrueRangeHigh>PeriodTrueRangeHigh) PeriodTrueRangeHigh = TrueRangeHigh; // find true high of period

      TrueRangeSum += TrueRangeHigh;
      TrueRangeSum -= TrueRangeLow;
    }

    PeriodTrueRange = PeriodTrueRangeHigh - PeriodTrueRangeLow;
    if (PeriodTrueRange==0) PeriodTrueRange = MathPow(10, -12); // avoid possibility of division by zero
    Input = TrueRangeSum / PeriodTrueRange;
    return ((logN(Input, 10, MathPow(10, -12)) / logN(period, 10, MathPow(10, -12))) * 100);
  }

double logN(double x, double base, double epsilon)
  {
    double integer = 0.0;
    if ((x < 1) || (base < 1)) return(0);

    while (x < 1)
    {
      integer -= 1;
      x *= base;
    }
  
    while (x >= base)
    {
      integer += 1;
      x /= base;
    }
  
    double partial = 0.5;
    x *= x;
    double decimal = 0.0;

    while (partial > epsilon)
    {
      if (x >= base)
      {
        decimal += partial;
        x = x / base;
      }
      partial *= 0.5;
      x *= x;
    }
    
    return (integer + decimal);
  } 


double StdDev(int shift, int samples)
  {
  double x0=0, x1=0, x2=0;
  for (int m=0; m<samples; m++)
    {
    x0 = ExtMapBuffer[m+shift];
    x1 += x0;
    x2 += MathPow(x0,2);
    }
  return(MathSqrt((x2-(x1*x1/samples))/(samples-1))); // minimum samples is 2, enforced in the init section
}

double RemoveStopsandTargets()
{
   int i;
   for (i = OrdersTotal() - 1; i >= 0; i--){
   if( OrderSelect(i,SELECT_BY_POS, MODE_TRADES)) 
    if( OrderType()==OP_BUYSTOP) 
       OrderDelete( OrderTicket() );
       else if( OrderType()==OP_SELLSTOP) 
                 OrderDelete(OrderTicket());
      if( OrderType()==OP_BUYLIMIT) 
       OrderDelete( OrderTicket() );
       else if( OrderType()==OP_SELLLIMIT) 
                 OrderDelete(OrderTicket());
               
                 
                 }
 //                 for (i = OrdersTotal() - 1; i >= 0; i--){
  
//   if( OrderSelect(i,SELECT_BY_POS)){

  

 //         if (OrderType() == OP_SELL && OrderMagicNumber()!=magic_number3){
  //            if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(0,4),  NormalizeDouble(0,4), OrderExpiration()))
 //               Print("Error: ", ErrorDescription(_LastError));
  //         }
   
 //    if (OrderType() == OP_BUY && OrderMagicNumber()!=magic_number3) { 
                   
 //             if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(0,4),  NormalizeDouble(0,4), OrderExpiration()))
 //               Print("Error: ", ErrorDescription(_LastError));
  //        }
  //   }     
  // }
 return(0);
}

 
double GetNlongSize()
{
double nlongs = 0;
double nshorts = 0;
for(int i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
             if (OrderType() == OP_BUY && OrderMagicNumber()!=magic_number) 
             {
               if (OrderMagicNumber()==53 )  nlongs = nlongs+OrderLots()*.8; 
               else nlongs = nlongs+OrderLots();
             }  
               
             if (OrderType() == OP_SELL && OrderMagicNumber()!=magic_number2 )
             {
               if (OrderMagicNumber()==53 )  nshorts = nshorts+OrderLots()*.8; 
               else nshorts = nshorts+OrderLots(); 
             }
                      
   }
   return(nlongs);
}


double GetNshortSize()
{
double nlongs = 0;
double nshorts = 0;
for(int i=OrdersTotal()-1; i>=0 ; i--)
 {   
   
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        { 
           Print("Access to orders list failed with error (",GetLastError(),")");
           break;
        }
             if (OrderType() == OP_BUY && OrderMagicNumber()!=magic_number) 
             {
               if (OrderMagicNumber()==53 )  nlongs = nlongs+OrderLots()*.8; 
               else nlongs = nlongs+OrderLots();
             }  
               
             if (OrderType() == OP_SELL && OrderMagicNumber()!=magic_number2 )
             {
               if (OrderMagicNumber()==53 )  nshorts = nshorts+OrderLots()*.8; 
               else nshorts = nshorts+OrderLots(); 
             }
                      
   }
   return(nshorts);
}