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 due to the 30+ pips spread. This looks more like a glitch for the broker won’t even be open for trading for another 1 or 2 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);
}

Vignetta

This is a programming idea for displaying two numbers i.e. a percentage or an oscillator’s reading as 2 balls visible from the other side of the room. The color gets changed in certain ranges. This routine does not deal with the decimals.

Here the two numbers represent the price’s location relative to the E-32 channel.

deletetxt1("Vignetta");


int twodigits = NormalizeDouble(100-((top_of_the_range-Close[0])/(top_of_the_range-bottom_of_the_range)*100),0);


int tens = round(twodigits/10);

int ones = twodigits-tens*10; 

string stens, sones;



switch(tens)
{
case  1:   stens=CharToStr(140);
        break;
case  2:   stens=CharToStr(141);
        break;
case  3:   stens=CharToStr(142);
        break;        
case  4:   stens=CharToStr(143);
        break;
case  5:   stens=CharToStr(144);
        break;
case  6:   stens=CharToStr(145);
        break;        
case  7:   stens=CharToStr(146);
        break;                
case  8:   stens=CharToStr(147);
        break;                        
case  9:   stens=CharToStr(148);
        break;                      
  default: stens=CharToStr(139);
      break;
  }
  

switch(ones)
{
case  1:   sones=CharToStr(140);
        break;
case  2:   sones=CharToStr(141);
        break;
case  3:   sones=CharToStr(142);
        break;        
case  4:   sones=CharToStr(143);
        break;
case  5:   sones=CharToStr(144);
        break;
case  6:   sones=CharToStr(145);
        break;        
case  7:   sones=CharToStr(146);
        break;                
case  8:   sones=CharToStr(147);
        break;                        
case  9:   sones=CharToStr(148);
        break;                      
  default: sones=CharToStr(139);
      break;
  }
 

 
string jointstring=stens+sones;

 ObjectCreate("Vignetta",OBJ_LABEL,0,0,0,0,0);
         ObjectSet("Vignetta",OBJPROP_XDISTANCE,3*15); 
         ObjectSet("Vignetta",OBJPROP_YDISTANCE,3*15);

if (100-((top_of_the_range-Close[0])/(top_of_the_range-bottom_of_the_range)*100)>=60 && 100-((top_of_the_range-Close[0])/(top_of_the_range-bottom_of_the_range)*100)<=70 )  ObjectSetText("Vignetta",jointstring,80,"Wingdings",Crimson);
else if (100-((top_of_the_range-Close[0])/(top_of_the_range-bottom_of_the_range)*100)>=30 && 100-((top_of_the_range-Close[0])/(top_of_the_range-bottom_of_the_range)*100)<=40 )   ObjectSetText("Vignetta",jointstring,80,"Wingdings",Green);  
else if (ones<5 && tens<1)  ObjectSetText("Vignetta",jointstring,80,"Wingdings",Green);
else if (ones>3 && tens==9)  ObjectSetText("Vignetta",jointstring,80,"Wingdings",Crimson);
else ObjectSetText("Vignetta",jointstring,80,"Wingdings",Brown);
To put numbers on an indicator, you would have to change the first 0 in the ObjectCreate parameters to 1, 2 etc. which is the indicator_window number

The deletetxt1 routine came from somewhere, I just made it more universal.

   void deletetxt1(string text){
   for(int iObj=ObjectsTotal()-1; iObj >= 0; iObj--){
      string   on = ObjectName(iObj);
      if(StringFind(on, text) == 0)  ObjectDelete(on);
}  }
deletetxt1("Over");

// oscillator-reading version

int twodigits = NormalizeDouble(stoch60[0],0);

//string tds = IntegerToString(twodigits);

int tens = round(twodigits/10);

int ones = twodigits-tens*10; 

string stens, sones;

//Print("tens=",tens);
//Print("ones=",ones);


switch(tens)
{
case  1:   stens=CharToStr(140);
        break;
case  2:   stens=CharToStr(141);
        break;
case  3:   stens=CharToStr(142);
        break;        
case  4:   stens=CharToStr(143);
        break;
case  5:   stens=CharToStr(144);
        break;
case  6:   stens=CharToStr(145);
        break;        
case  7:   stens=CharToStr(146);
        break;                
case  8:   stens=CharToStr(147);
        break;                        
case  9:   stens=CharToStr(148);
        break;                      
  default: stens=CharToStr(139);
      break;
  }
  

switch(ones)
{
case  1:   sones=CharToStr(140);
        break;
case  2:   sones=CharToStr(141);
        break;
case  3:   sones=CharToStr(142);
        break;        
case  4:   sones=CharToStr(143);
        break;
case  5:   sones=CharToStr(144);
        break;
case  6:   sones=CharToStr(145);
        break;        
case  7:   sones=CharToStr(146);
        break;                
case  8:   sones=CharToStr(147);
        break;                        
case  9:   sones=CharToStr(148);
        break;                      
  default: sones=CharToStr(139);
      break;
  }

 
string jointstring=stens+sones;

//if (Close[0]>plus[0] && buy[1]) jointstring=jointstring+CharToStr(66);
//else if (Close[0]>plus[0] && sell[1]) jointstring=jointstring+CharToStr(73);

//if (Close[0]<minus[0] && sell[1]) jointstring=jointstring+CharToStr(66);
//else if (Close[0]<minus[0] && buy[1]) jointstring=jointstring+CharToStr(73);

      ObjectCreate("OverD", OBJ_TEXT, indicator_window, Time[10], 77); 

if (stoch60[0]>88) ObjectSetText("OverD",jointstring,40,"Wingdings",Purple);
else if (stoch60[0]<12)  ObjectSetText("OverD",jointstring,40,"Wingdings",Green);  
else if (ones<6 && tens<=1)  ObjectSetText("OverD",jointstring,40,"Wingdings",Green);
else if (ones>2 && tens==9)  ObjectSetText("OverD",jointstring,40,"Wingdings",Purple);
else ObjectSetText("OverD",jointstring,40,"Wingdings",Brown);

When You Don’t Even Know What You Have

I have spent the last 6 years trading and developing indicators solely for the EUR/USD.

I think I had good odds for coming up with the answers I wanted, and look at how far I managed to get!

LEMA 30N X-Factor

I think I’m onto something with that 65% and 35%.

Stochastic Bars Mixed Black Panel

The greenery is “The Forest”

Fibonaccis? You’re joking, rigtht?

Volatility has nothing to do with how far the instrument would get.

All calculations were done with two constants: fluctuation size and fluctuation maximum.

…

Aleš’s Lessons #12 – Trading The E-32 Channel

the lines got labelled up

you can see that the Wave 2 pullback came back to the upper half’s oversold level at 60%

you had to be looking for a sell, for the 0% or overdrive down level got more or less touched, and this strength measurement means that the market is strong to the downside

a turn would happen when it would start to miss the mark, like it did at the top: it went into the E-32 (in hourly denomination) upper overbought, but it did not get beyond 96%, and started making lower highs, broke into the upper oversold zone and presented a perfect sell

the recent 2 touches on the 0% mark and the next miss (looking like a head and shoulders on the 30-min) said that the market went too far, but it is still very strong to the down side (in fact, if anything, it has picked up some extra momentum)

the mean reversion took back price again into the 60-70% range before the next waterfall down

Wave 5 down is now sitting at a point where the structure theoretically could be turned into an upward move by purchasing the 40-30% range of the channel: the up move would become a qualified Wave 1 up by crossing over to the other side of Mr. Maroon and Wave 2 down would be printed with the hourly red stochastic going below 20

I personally think that the market is going to make this a 5th leg down and going to miss the 0% by some single digits and perhaps make a head by applying a beat sometime later

there is enough daily fuel to get below 1.17

the system is calling this structure an A-B-C move, and the Crack Ho is inches away from cracking back below 45 which would rule the crack above 55 section a fake out

so, that’s the other 2 balls to keep an eye on

(the liquidity break purple strike out re-enforced the move to the upside)

those projected distance numbers ARE attainable

…

who in their right mind would want to be long this?

Driven Thrusts Reprise

I have tempered with the subject before, i.e. in my e-book that was released in March, 2019, but never before on a 1H chart.

I had made great progress indentifying certain features, see a blog entry somewhere under the title of Driven Thrusts & Lackluster Busts, I managed to distinguish between a screw driver and a drive/ double drive, thus things are starting to fall in place rapidly: the previous passes on 30 min RSI2s are of great help with starting out not from scratch on this time frame.

First some snapshots of Thrusts and Failures (busts).

Now my attempt for laying down the foundations.

Definitions:

What is a Thrust? It is a 14-sample new low/high with no beat on the next hour and was preceded by a drive within the last 16 hours (and there was no thrust 3 or 4 hours ago.)

The Drive is at least 3 hours worth of potent selling/buying.

Failures may be different kinds, i.e. there was a Thrust not long ago, there was no drive within the allotted sample size.

So let’s see a real life example of monitoring for a failure. On the image at the start of this article the F did not have potent selling/drive within the last 14 bars. When the F got printed and price got back above the last T terminal, that was your buy signal to go long for a driven thrust on the upside.

The chain of T-s followed by the “no more selling” signal marked the end of a Wave 1, since this was an impulsive looking structure.

Wave 2 clues – if you have been following my works – include a move back through at least the closer end of Mr. Maroon and 9-sample Stochastic D going back into overbought.

I did what every EUR/USD resident should do upon a realization and tolled the bells.

This is where we currently are at. The pink/magenta circles are the Maroon fake-outs (they come standard with the LEMA30N).

The white circles are highlighting the idea that the overdrive line may actually exist.

The yellow circle highlights the reaction from the 89-eyed Iguana (a squaring move), the next encounter was a let go, so the third one should be a spike.

I decided on ND standing for No Drive and the FCB standing for Failed To Close Below.

The drive signal I have yet to figure.

Wave 3 is showing the first thrust. We have gotten quite close to the daily fuel limit with the low at 1.1753.

The one other thing I wanted to mention is that the top was made with a double driven thrust (so picture a double sized T at the end):

There was an extension fill along the way, but a new projected distance target was also generated by this Wave 3 down.

Go figure, 1.17 coincides with the overbought neckline. I think that’s a target.

And the oversold level of 1.1748 is going to let price go on the second knock, believe you me.

for (i = 330 ; i >= 0; i--) {     
      if (i>0 && Low[i]<iLow(symbol,0,iLowest(symbol,0, MODE_LOW,14,i+1)) && Low[i-1]>Low[i]){
         j=i+2;
         while (j<i+14){
            if (RSI2[j]<18 && RSI2[j+1]<18 && RSI2[j+2]<19) break;
            j++;
         }
       if (j<i+14 && Close[i]<Open[i+1] && !tdown[i+3] && !tdown[i+4] ){
          ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i], Low[i]-20*Point); 
          ObjectSetText("TEE"+DoubleToStr(i), "T", 22, "Impact", FireBrick);  
          tdown[i]=true;
       
       }  
              else  if (i>0 && j==i+14 && Low[i]<Low[i+1] && !(RSI2[i]<18 && RSI2[i+1]<18)) {
          ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i], Low[i]-20*Point); 
          ObjectSetText("TEE"+DoubleToStr(i), "ND", 22, "Impact", Yellow);  
       }
       
       
       else if (i>0 && j<i+14 && Low[i]<Low[i+1]){
          ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i], Low[i]-20*Point); 
          ObjectSetText("TEE"+DoubleToStr(i), "FCB", 22, "Impact", Navy);  
       }
      
 
      
      }
      
      if (i>0 && High[i]>iHigh(symbol,0,iHighest(symbol,0, MODE_HIGH,14,i+1)) && High[i-1]<High[i]){
         j=i+2;
         while (j<i+14){
            if (RSI2[j]>82 && RSI2[j+1]>82 && RSI2[j+2]>75) break;
            j++;
         }
       if (j<i+14 && !tup[i+3] && !tup[i+4] ){
          ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i], High[i]+90*Point); 
          ObjectSetText("TEE"+DoubleToStr(i), "T", 22, "Impact", Navy);  
          tup[i]=true; 
       }  
       
              else if (i>0 && j==i+14 && High[i]>High[i+1] && !(RSI2[i]>82 && RSI2[i+1]>82)) {
          ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i],  High[i]+90*Point); 
          ObjectSetText("TEE"+DoubleToStr(i), "ND", 22, "Impact", Yellow);  
       }
       
        else if (i>0 && j<i+14 && High[i]>High[i+1] && Close[i]<Open[i+1]){
          ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i],  High[i]+90*Point); 
          ObjectSetText("TEE"+DoubleToStr(i), "FCA", 22, "Impact", FireBrick);  
       }
 
      
      }
      
   
}

Homework:

What comes next?

…

Coming along nicely…

remember, that a Drive is a thrust at the same time, but the Thrust has a time constraint, thus it can show a winding down

…

As a farewell, a riddle to think about: how can the oversold level be above the overbought?

E96 let go - buy Green River - buy Mr. Maroon - 2x stretch reaction (sell) 
	- buy Mr. Maroon  - 3x stretch reaction (3x) 

	buy fresh out of overbought 4x -> target 100% 
	- 1st miss: buy fresh oversold - target 100%
	- 2nd miss: buy fresh out of overbought - target 100%
	100% beaten 3 times ->
	easing back to just out of overbought -> buy 3x 
	100% beaten 2 times, missed 1 time -> it is over with

sell miss of 100% -> target 0% 
	-> 3 fresh oversold touches with 2 reactions back to overbought 
	-> a final miss of the 0 - it's over with

buy miss of 0%	-> reaction from fresh out of oversold 
	-> buy Green River
	-> add fresh oversold 2x
	-> 100% hit 2x, 1x miss

sell miss of 100%
	-> add on fresh out of oversold
	-> 0% miss gets beaten by 44 pips

buy the beat of 0% miss 
	-> add on Green River -> target 100%
	-> 100% miss: it's over with
	
sell miss of 100% 
	-> 0% hit 
	-> reaction from 28 pips beat of 0% hit
	-> sell fresh out of oversold
	-> 0% beat 2x

The Bid In The Market #2

We left with the previous article pointing out the presence of a triangle.

I certainly had my mind set on a bear flag and a lower low first to complete the Wave 4 before the final move up.

The weekend open and shallow dip was particularly tricky, for with the increased spread (10 pips or so) you could never take advantage of it, the lowest fill would had been 1.1838 despite the bid chart showing 1.18292.

What are you looking for on the upside when a terminal wave is printing?

Although the Energy Bands were not able to keep up with wave Wave 3, they managed to catch the top of Wave 4 and Wave 5 came rather close to it, so they could have helped a bit.

What else? Symmetry perhaps:

The most recent stretches went to about 4x stretch from the mean. Price came close to this as well – with volatility dropping away a bit.

Yet another near miss was the overdrive-line.

Could we still get a beat after this 4-H exhaustion? Perhaps… price is still in the overbought. But I’m not expecting it, for the whole structure to the upside was of the corrective kind, an A-B-C – see the abundance of the overlaps.

The two extension (projected distance) lines were the best clues, as they got their fill and 7-pip of extra beyond. Price seems to be interested in the trend line once again for a back test.

The overbought neckline is now in line with the last swing low @ 1.1710. I expect that low to be tested next.

The Bid In The Market

Someone seems to be overly convinced about the dollar going to zero, thus keep on buying utilizing the current overbought safety.

The first deep pullback was a mean reversion. It made it to the Green River Killer. The Green River can stop a move, any move.

The market eeked out a higher high, but barely and at 4x stretch from the mean.

The next mean reversion went through the mean and achieved approximately the average of the two mean reversion calls: (1.1664+1.1748)/2 = 1.1706

This time the area of interest was the lower guard rail (and a bit beyond), which is 1x stretch from the mean.

The rally stalled at 2x stretch from the mean making a lower high print. The lower high and the higher low points towards a squeeze happening, i.e. a pennant / triangle.

The most recent buy entry was a no-brainer again in the shape of the Green River. Now, there is a stall at the Upper Guard Rail. Why?

What happens if we already saw the failed break of the triangle at 70% into its length, and if we move the upper line lower to get the inner vector?

Then this is the perfect entry to go short – at least to the overbought neckline -> 1.1687

Just sayin’

…

Back test of the last consolidation level, the trendline and the last bearish engulfing candle

The Crack Ho

Once upon a time, not long ago…

If you want to be become a miionaire, you should start by studying the behavior of a crack ho. Ho-ho-ho! No kidding.

She is known as 60-sample hourly stochastic D, and she has 3 delay & 3 smoothing.

On the image below you can see the C.H. cracking below 45 – thus a new lower range gets cracked open.

The bottom crack is shown by the lady in black.

On the image below you can see C.H. cracking above 55 and diverting traffic back into the upper range.

The image below shows the bottom cracking wide open again.

This guardian angel provides a money back guarantee service until she gets called into dance – and she tends to put up not much resistance, like a hooker that is hooked on… crack.

…

Smaller than 3: satisfied customer

stoch60[i]=iStochastic(symbol,0,60,3,3,MODE_SMA,0,MODE_SIGNAL,i);

…

You mean the Minimum/Target (of the cat B. buy signal) was at 1.1811 & price only went to 1.1808?

I better get good at this and fast!

Pinning Down The Embedded Features

(…for the overbought side as it stands currently…)

It’s gonna be a long one, so grab a cup of tea!

Step 1. Identify the embedded overbought condition

I handed out the free tool for this one (instrument independent) in Aleš’s Lessons #10 under the name of Comfort Levels 4H Lucid and marked up the back test of the overbought neckline on the image above. The Blue, 80% line has not been seen back since – this is the realm of the overbought safety where higher highs are more or less guaranteed.

The first tail spin happened after a 585 pips relentless run up measured from the back test of the neck line and was 213 or so pips long (green).

The run up had a total of four, 4H exhaustion beats or 3 break outs. Not gonna confuse you with break beats, don’t worry.

2. Exhaustions

Any energy sequence could come to a halt after a beat: no interest in continuation would result in not breaking the beat. Let’s see if we can define a maximum duration for a break to must happen.

The first exhaustion – shown by the Choppiness_DV plots had 3 consecutive beats and the break of the beat happened 20×4 hours after the exhaustion and in a rather volatile manner.

Conclusions here: the break out is not very clean with multiple kick backs reaching up to 66 pips. The optimum way of playing is to have a holding and scale out on a beat. Reload below two 4-Hour lower lows – see brown box. Your optimal get out has to do with the count: you want to be active from count 8.

The second exhaustion had its beat 6 bars later and the break out was 12x 4 Hours down the road – with not much kick back this time. Interestingly the 8-count fell on the 3rd exhaustion print, which was also a beat. That’s two scores for the 8-count.

There were no 2x 4H lower low entries here, but the break itself was a safe adding point say 6-9 pips out.

From the 3rd exhaustion the count does not seem to get the exit right with the number 8, but it does get something else right: the number 7 count provides you with the stop loss values for the parabolic ending (lowest low of 6/7 gives the actual number). So, 1.1828 would had been your trail stop stop out if you did not want to scale out upon seeing the green circle event – the engulfing candle that was brought on by the 4th exhaustion.

The #1 counts were great entries, but you would not have these printed real time for you need 2 more candles before a candle can be called a fractal. For quick trades, you have the 7-count real time, and you can sell off on the 8-12 counts.

The last exhaustion was also a beat, but I could not write one software for every possible occurrences: a higher high and a close back below is always a spark, and can always balloon into a rapid fire.

Before closing out the exhaustion/beat section, let’s acknowledge the fact that the tail spin ended in an exhaustion-beat which was not followed up by a break as well as the new run for the top resulted in another exhaustion beat.

Routine: Choppiness_DV

Since the whole thing looks like a ranging / consolidation are it is safe to think that if this was to continue, the most likely thing to print here is a bull flag, which would give a lower sightly low as the next low risk entry somewhere between 1.1694 and 1.1651 (overbought neckline currently).

Of course, the 2nd tail spin can also turn into something more.

3. Projected distance

Since the neck line back test, the projected distance values brought on turbulence and and you were always able to sell for a profit if you were starting to short 7-pips out and added to your short every 10 pips further out. Even the worst location did come into money by 27 pips at the end, and the most abuse to endure would had been a total of 77 pips on the first position.

Routine: Projected Distance 240

Currently there’s a projected distance value at 1.1707.

The 1.1648 has no extended line on the right and still registers (see short purple line on the right), because of the way I wrote the search. There was no low below and close below event. This may be a mistake or could be a benefit. It is interesting to note that the value itself at 1.1648 is awfully close to the previously mentioned 1.1651 overbought neckline.

4. The Overdrive

I have talked about the possibility that the overdrive lines on the 4H charts may end up looking rudimentary. The circled values sync up much better on a 15-min chart, see the previous posts.

Routine: Overdrive / 2Fractals 15-min

The point here is that if the price reacts on cue to these hourly E-32 displacements, they verify the presence of the E-32 channel.

ODU[i]=E32L[i]+FMax*22*Point;
ODD[i]=E32L[i]-FMax*22*Point;

If these points coincide with exhaustions, your narrative have more evidence to work with to vindicate a turn.

The current touch did not come on an exhaustion-beat, so I am expecting more downside.

5. “It’s all about the RSI”

The latest addition, the plot of below 16 RSI 2 readings can help figure the tail spins / deep corrections. See my last article, “How Did I Know” for this one.

Routine: RSI2 Basic

  if (RSI2[i]<16 && iClose(symbol,1440,1)> iHigh(NULL,240,iHighest(NULL, 240, MODE_HIGH, 1590))-(iHigh(NULL,240,iHighest(NULL, 240, MODE_HIGH, 1590))-iLow(NULL,240,iLowest(NULL, 240, MODE_LOW, 1590)))*.2 
         && iClose(symbol,1440,2)> iHigh(NULL,240,iHighest(NULL, 240, MODE_HIGH, 1590))-(iHigh(NULL,240,iHighest(NULL, 240, MODE_HIGH, 1590))-iLow(NULL,240,iLowest(NULL, 240, MODE_LOW, 1590)))*.2 
         && iClose(symbol,1440,3)> iHigh(NULL,240,iHighest(NULL, 240, MODE_HIGH, 1590))-(iHigh(NULL,240,iHighest(NULL, 240, MODE_HIGH, 1590))-iLow(NULL,240,iLowest(NULL, 240, MODE_LOW, 1590)))*.2 
      ){
         ObjectCreate("TitusOverOne"+DoubleToStr(i), OBJ_TEXT, indicator_window, Time[i], RSI2[i]+16);  
         if (RSI2[i+2]<16 && RSI2[i+1]<16 && RSI2[i]<16) ObjectSetText("TitusOverOne"+DoubleToStr(i), DoubleToStr(NormalizeDouble(RSI2[i],1),1), 13, "Arial", Magenta); 
         else ObjectSetText("TitusOverOne"+DoubleToStr(i), DoubleToStr(NormalizeDouble(RSI2[i],1),1), 13, "Arial", Crimson);