Aleš’s Lessons #13 – Static and Lucid Targets

Static targets are a snapshot of a calculation that do not change by whatever price does, whilst the lucid ones are the moving averages or their displacements.

Plot RSI2 Zero, Overdrive and RSI2 Direccione LX on a hourly chart.

T3s are static measurements from a condition I dubbed Wave 3, for Wave 3’s tend to have this kind of an overheated ending. T3 is probably the best location for an exit and a fade, for you have the exact level on your hand way ahead of time.

The displacement changes a bit according to the price’s residence on the long term comfort levels.

Just keep in mind that there could be a second call, and for that reason apply a better than break even stop loss once in gains by say 20 pips.

T2 is the second best price location for an exit as well as a fade, but this one is lucid – see the automatization part at the end. Play the fade the same way as the T3, with a protective stop loss in gains, don’t go in again once stopped out and be conscious of the fact that you may have to open a trade at market, some distance away from the actual bands if you don’t happen to be there at the right moment.

A T2 fade could be paired up with with a T2->0L target which is also lucid, but for an idea I plotted an approximate location as a snapshot of the other side of Mr. Maroon.

The static T1 target is coming from the Zero condition – more on this in the Make Your Own Indicator article. The yellow numbers carry a little more weight for they are further away from the safety nets, and the “shadow” accent is a print with the right EMA configuration – for extra promotion.

The Bull Config / Bear Config switch is as simple as the relationship of the first two safety nets E-16 & E-32, for I did not feel like complicating things with 6 different configurations by throwing the 3rd safety net, Mr. Maroon to the mix.

As you can see, the Zero condition is yet another exit / fade, but you would actually need 2 more candles – so a hint more than an extra hour for the call to be certain.

The ticker now cites the T2 lucid values as well as the (c)onditional values that hinge on the 60-sample stochastic D reading (aka Crack Ho), and they are the 65%+ and the 35%- values of the E-32 channel as for overbought and oversold (the inner dotted plots on the Stochastic Bars for 15M).

Automatization

After putting the Trail Stop Only LT Modified EA on an Eur/USD chart (I prefer a 30-minute one) and turning up the Auto Trading, you can start aiming for lucid targets:

  1. for a 3-pip overshot of the E-16 current value in (blue) use 0.5 stop loss for longs and 5.0 stop loss for shorts
  2. for a 3-pip overshot of the E-32 current value in (blue) use 0.6 stop loss for longs and 6.0 stop loss for shorts
  3. for a discharge on the E-32 channel’s overdrive lines use 0.8 stop loss for longs and 8.0 stop loss for shorts
i.e.
/////Long Target - Code 5 E16

if( OrderType()==OP_BUY && OrderStopLoss()==.5 && OrderTakeProfit()!=NormalizeDouble(iMA(symbol,30,32,0,MODE_EMA, PRICE_CLOSE,0),4) && OrderOpenPrice()<NormalizeDouble(iMA(symbol,30,32,0,MODE_EMA, PRICE_CLOSE,0),4)-20*Point
 ) 
       { OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), NormalizeDouble(iMA(symbol,30,32,0,MODE_EMA, PRICE_CLOSE,0)+20*Point,4), OrderExpiration());
          Print("LONG Target Set to E-16 @ "+DoubleToStr(NormalizeDouble(iMA(symbol,30,32,0,MODE_EMA, PRICE_CLOSE,0)+20*Point,4),4));}

Appendix

The expert adjusts stop losses and targets depending on the stop loss you enter.

if the stop loss isn’t zero (left empty) or if you enter 2.0 for shorts and 0.2 for longs and not some other Code

the auto trail stop would lock in
1.5 pip after 4 in gains, 3 pips after 8 in gains
& trail the stop 16 pips behind after 20+ pips in gains

using 3 & 0.3 (Code 3)
would lock in 64 pips upon exceeding 64 pips gains


Code 4 adjusts the target 16 pips above the 8-sample 15 minute low / 16 pips below the 8-sample 15min high(not sure about this one any more)
Code 5: E16 target+ 2pips extra
Code 6: E32 target + 3 pips extra
Code 7: 5 pips closer than Mr. Maroon (playing it safe)
Code 8: Overdrive as tartget
Code 9: 89 EMA

there is also a 2.5 / 0.25 combo that would behave as 2 / 0.2 and on top of that first it would find the last 15 minute fractal and set that as a target

C – Parabolic

The C leg of a corrective move can go parabolic.

The D-W-D structure is banging out a solid trend line currently.

D stands for drive.

W is a whip of volatility – when the volatility drops too low, there is a quick counter move that behaves like a gear shift from low to high.

The last Drive is the closure to the C leg making it go exponential.

The two mentioned Parabolic C legs are in white.

The trendline that the two C-s have banged out.

The logic for the upside:

if (i>0 && RSI2[i-1]<68 && RSI2[i]>82 && RSI2[i+1]>82 && RSI2[i+2]>68){
               ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i],  High[i]+90*Point); 
          ObjectSetText("TEE"+DoubleToStr(i), "D", 22, "Impact", Blue);  
         }
        
      if (i>0 && High[i]>(iHigh(symbol,0,iHighest(symbol,0, MODE_HIGH,12,i+1))) && High[i-1]<High[i] && High[i]> iMA(symbol,0,67,0,MODE_EMA, PRICE_LOW,i)-120*Point){
          if (tup[i+3] || tup[i+4]){
          ObjectCreate("TEEP"+DoubleToStr(i), OBJ_TEXT, 0, Time[i], High[i]+90*Point); 
          ObjectSetText("TEEP"+DoubleToStr(i), "W", 22, "Impact", Crimson);  }
          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); 
          
        if (High[i]> iMA(symbol,0,67,0,MODE_EMA, PRICE_HIGH,i)+100*Point && High[i]< iMA(symbol,0,67,0,MODE_EMA, PRICE_HIGH,i)+320*Point )     ObjectSetText("TEE"+DoubleToStr(i), "T20%", 22, "Impact", Navy); 
       else  if (High[i]> iMA(symbol,0,67,0,MODE_EMA, PRICE_HIGH,i)+320*Point && High[i]< iMA(symbol,0,67,0,MODE_EMA, PRICE_HIGH,i)+640*Point )     ObjectSetText("TEE"+DoubleToStr(i), "T60%", 22, "Impact", Navy); 
       else   ObjectSetText("TEE"+DoubleToStr(i), "T80%", 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) && RSI2[i+4]<86) {
          ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i],  High[i]+90*Point); 
          ObjectSetText("TEE"+DoubleToStr(i), "ND-90%   ", 22, "Impact", Yellow);  
          
          ObjectCreate("TEEP"+DoubleToStr(i), OBJ_TEXT, 0, Time[i], High[i]+120*Point); 
          ObjectSetText("TEEP"+DoubleToStr(i), "brk:"+DoubleToStr(NormalizeDouble(High[i]+100*Point,4),4), 12, "Impact", Black);  
       }
       
        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), "T/FCA", 22, "Impact", FireBrick);  
       }
      
       
      if (i>0 && RSI2[i]>82 && RSI2[i+1]>68 && (RSI2[i+2]>68 || RSI2[i-1]>76) ){
       
        // && RSI2[i+3]>44
        //
          ObjectCreate("TEE"+DoubleToStr(i), OBJ_TEXT, 0, Time[i],  High[i]+90*Point); 
       if (i>0 && (RSI2[i]>99 || RSI2[i-1]>99))  ObjectSetText("TEE"+DoubleToStr(i), "Ds", 22, "Impact", Blue);  
          else ObjectSetText("TEE"+DoubleToStr(i), "D", 22, "Impact", Blue);  
         tup[i]=true;
       }
 }

Now we are up to E in the legs, yet the impulse move down has not been entirely taken back by the 3 pushes up, which way would Wave 3 be?

What was missing until now after the D-W-D? The Orange Zero.

Wave 3 – Wave 5 Relationship

This is a valuable insight for those aiming to pin a reversal perfectly.

Let’s start with figure 1.

You can see, that as soon as a “3” identified, the “5” can be projected with high accuracy. On this image above there are two “3”-s, yes, for the first number 3 is the wave 3 of the Wave 3 whilst the second one is Wave 3 preceding Wave 5 – yet the distance is very similar.

These projection triangles are made of 4 pieces with the 3rd rung being extended and spelled out for good measure.

The third rung is 36 pips beyond the end point and the total triangle is 50, that is not expected to be reached. Guess where your stop would go.

The reason for the 4 slices has to do with the price’s long term Stochastics: these 3-s were printed in the last 10% of the long term range (shown by Comfort Levels Lucid), otherwise they would be only 3 slices.

The actual high was 1.20106 – which would had meant 8.6 pips accuracy for catching the top – and let’s not forget that you had 23 hours to place the order ahead of time.

The one that occurred on the downside recently had 3 slices, for it was not in the lower 10%. The second rung came into play at 26 pips out. The accuracy was 2 pips and it got its fill 68 hours down the road.

Not sure if you are learning something here, but I think I am. The last move up was an ABC move, and accordingly it did not come with a comparable Wave 3 and Wave 5. C is an even better location to defy the direction for it sets up a lower high (or higher low), but not nearly as predictable how far price shall get.

stoch is iStochastic(symbol,0,9,3,3,MODE_SMA,0,MODE_SIGNAL,i);

RSI2 is iRSI(symbol,0,2,PRICE_MEDIAN,i);

   ////3 up
   if (RSI2[i]>RSI2[i+1] && RSI2[i+2]>RSI2[i+1] && RSI2[i+1]<18 && RSI2[i+1]>5 && (RSI2[i+8]>90 || RSI2[i+9]>90 || RSI2[i+4]>90 || RSI2[i+5]>90 || RSI2[i+6]>90 || RSI2[i+7]>90) && stoch[i+4]>60 && High[i]>iMA(NULL,0,67,0,MODE_EMA,PRICE_HIGH,i)){
      j=i+7;
      while (j<i+14){
         if (RSI2[j]>RSI2[j+1] && RSI2[j+2]>RSI2[j+1] && RSI2[j+1]>RSI2[i+1] && RSI2[j+1]<56) break;
         j++;
      }
-------------------------------------------------------------------

 ////3 dn
      if (RSI2[i]<RSI2[i+1] && RSI2[i+2]<RSI2[i+1] && RSI2[i+1]>92 && RSI2[i+1]<95 && (RSI2[i+8]<10 || RSI2[i+9]<10 || RSI2[i+4]<10 || RSI2[i+5]<10 || RSI2[i+6]<10 || RSI2[i+7]<10) && stoch[i+4]<40 && Low[i]<iMA(NULL,0,67,0,MODE_EMA,PRICE_LOW,i)){
      j=i+7;
      while (j<i+14){
         if (RSI2[j]<RSI2[j+1] && RSI2[j+2]<RSI2[j+1] && RSI2[j+1]<RSI2[i+1] && RSI2[j+1]>44) break;
         j++;
      }

These are part of Stochastic Combo w/ Divergences

Make Your Own Indicator

Boyd myoi & wysiwyg.

1H timeframe.

Plot 4 MAs.

16 EMA HL2 in blue

32 EMA HL2 in yellow

67 EMA on Highs in Maroon

67 EMA on Lows in Maroon

Plot a 2 sample RSI on HL2. You can add horizontal lines at 99, 96, 4 and 1.

Zoom it out to make readings more visible.

You should not plot oscillators or MAs on closing prices, they are irrelevant information.

Learn the concept of Flip & Zero.

Flip is an RSI2 reading that is larger than 96 and smaller than 98 or smaller than 4 and larger than 2.

This is new market directive turning your EMAs into safety nets. Counter trades should be kept to touch downs on the 16, the 32 or the other side of Mr. Maroon. The stronger the trend the less safety nets would reverse it back.

The Zero (98 to 100 or 2 to 0) brings about a short term counter move that may not stop till the other side of Mr. Maroon (safety net 3), a 4-hour pivot or the close to other side of the previous range (the overbought/oversold far end). This signal is active not in real time, but upon a relief: once the RSI2 reading drops back below 98 or gets back above 2.

Aeroplanes = 4h pivot: the next resistance when the EMA configuration is bullish and the first 3 safety nets did not hold.

the code should have lines like these:

& if your plots look a little bit like this, you are all set…

Sorry, I don’t have the routine separately only as part of the RSI2 Basic.

Image below shows a 5% move: from the bottom of the upper reversal zone to the middle of it.

dual color arrows

Something interesting: cyan high volume bar on the left got undercut by 9 pips on the move down.

The second cyan high volume bar got exceeded by 9 pips on the upside.

One of them just added to their position. Who was it?

Indicators

Indicators are the best thing happened since sliced bread. They allow for statistics and applied logic time travel beyond a human’s capability to recall things and to live forever.

Trading can become a routine done with confidence. On the chart below concentrate on 2 things: the category B Buy warnings and the ginormous numbers stating the Minimum / Target which was just hit. Actually, I missed my time window (sample size) to show the 1.1835 print on the large numbers, but they are still there on the right with the memory function in magenta in small.

When the green B-s appear, you know that you should start thinking about buying. You need some additional knowledge that the low should not be further from the low indicated by the last B by more than 35 pips – see my Cat B signals video on my channel.

So now you know the exit: M/T, all you need is the where exactly and the when. (Stochastic Combo w/ Divergences)

These can be fine tuned with other indicators. The E32 channel can show you where price is out of overbought (below the yellow dots plotted by this Cadillac version of the Stochastic Bars Mixed) and the green vertical stripe came from my 2Fractals routine on this 15-min chart.

The latest tweaks on RSI2 Basic allow me to get the timing right:

The knowledge to be rolled over here was remembering that a Strong Drive would not normally stand for the end of a move: a thrust would be needed to occur (in 14 hours), and the duration under which the thrust prints cannot exceed hours of strong selling, for then it would end up making another Drive, not a Thrust. Meaning: it is possible to utilize the time constraint knowledge for an entry. For instance, in this case the beat was a measly fake out worth of some 10 pips, and I was picturing a healthier thrust, so my pending orders were not filled, yet this did not stop me from buying at 1.1762 at market when the 2-hour clock was running out.

I could figure the other end of the range thanks to my No-Drive yellow plot inventions and could think into the future in a coherent manner.

How could anyone not value all these additional information versus raw data that does not by itself mean anything?

The only tricky part is not forgetting to look at all these plots and frequently.

The buy low was 32 pips below the first B
The buy low was 42.7 pips below the first B’s swing low
Correction up reaching full charge on the daily. Look out below!
ABC move up.
E16 confusion – stall

Conserving and Concentrating Your Energy

Time is money, and energy is timing.

I have put out plenty of literature about Energies, so I’m not going into discussing in detail why the best interaction location is an anticipation of a beat.

The exhaustion-beat-break loop can be disconnected with the lowest possible risk between the beat and the break, thus your to do list should start with

  1. Identifying 4H energy exhaustions
Below: full charge for later

2. Anticipating a beat & scaling in

The gray vertical lines are the beats. They should appear within 6x 4H candle prints. Notice the full charge on the CI before breaking the bisque exhaustion high. On the way down the teal exhaustion received two consequitive beats, but this is what the scaling out was invented for – 38 pips lower you are still opening positions.

make up your mind on your maximum invested size

with size conscience brace for a maximum 45 pips beat

slice up your maximum size to 4 chunks; put your pending orders out starting at 8 pips, 16 pips, 26 pips and 36 pips

Exhaustion beat ticker for the move back from the beat low to 2x 38 pips higher.

use a counter-hedge 55 pips out

you may want to put more weight on the 16 and 26 pips locations, and if you want to be aggressive, you may start at 4 pips

if you ever wondered about what automatisation would come in handy for in trading is this: quick actions, calculations, multiple changes at mimimum time

think how you as a human could manage this event of a beat with unknown ultimate length wanting to maximise your potential for the expected turn around

after the time has spent some time beyond the exhaustion level, and comes back through it, you could pick up the remainder of your maximum size whilst simultaneously deleting the pending limit orders and moving your hedge level closer

3. Managing your trade

aim for the likely move 2 fluctuation maximum away, but be proactive enough to apply a protective, in the money stop loss upon hitting 1 fluctuation maximum and / or lighten up on the holdings

& you may find yourself noticing that breaks that materialize are preceded by full charge in the energy, and you would be absolutely right: disturbance in the force should be straightened out first before a new dawn awakens in the same direction

& now I would like to sell this francishe for $5 billion, because I am industrial, I travel light and I watch a lot of magic

once I drove by George Lucas in Richmond, and once a Jaguar XJS that was previously owned by Steve Wozniak was in my possession witph his Los Gatos address on the paperwork – the speaker grills were made to Apple logos

Bonus Wells Fargo calendar

…bonus Profit Factor snapshot for Aug, 2020 plus these 5 days

…only had time today to live up to yesterday’s promises…

Thrust vs No Drive… again?

Who Won? – The Market Decides

Remember the clash where the market went seemingly nuts over an epic Powell speech?

Pay attention to who had the upper hand (Drive) going into it, and what happened after the No Drive print on the bottom?

To be on the safe side, you can always plot Mr. Maroon to find the Wave 2, for Wave 2s come back through it.

Is it possible that the tiny slant back up was a Wave 2 yet again? Possible, for sure, but for the purposes of this article, what I wanted to show you was the run up of Driven-Driven-Driven-Driven-Driven-Thrust that came out of the No Drive print.

Now, there was another ND, and a paradigm shift happened when it got overrun, and if would be reasonable to think that the new wave structure would be coming out of this event.

Looks like you don’t have to decide after all. You just need to obtain a copy of my RSI2 Basic.

How Far Can You Go?

Checklist with 6 components.

  1. Extension Fill – the last projected distance was made at 1.1972 as shown by the Projected Distance 240

Near Misses

2. The most recent maximum stretch was at 3.6x, this run has scored 3.37 so far on the Stretch Marker

3. Attack on the overdrive line. Price has already managed to score an overbought reading at 90%+ of the E-32 Channel – shown by the latest version of the Stochastic Bars Mixed

4. The Dynamic version of the Energy Bands (CI Moat) show a close call to the water filled area that is starting at 1.20131 the previous run up also missed it, by 7 pips

Additional numeral checks

5. Level of 4H exhaustion – you want to see a print below 38 on the 7-sample CI reading – currently at 35.38 ✓

6. Psychological number? 1.20 in this case, a rather round one – may or may not be reached, but you can expect at least from price to give it a good try.

Final advice:

Keep an eye out for Continuation divergences – here shown by the RSI2 Basic, for that is where the new attacks come out of.

bonus image:

the relationship between wave 3 and wave 5 of Wave 3 and the relationship between Wave 3 and Wave 5

Why Fully Automated Trading on MT4 is not a Viable Thing

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

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

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

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

So, I had to investigate what happened.

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

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

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

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

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

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


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

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

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

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

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

int deinit() {
  return(0);
}

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

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

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

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

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

profits = 0;
 int hstTotal=OrdersHistoryTotal();

 counter = 0;
int overdrivecounter =0;

int no56b=0;
int no57s=0; 

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

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

   double comparison = AccountEquity()/AccountBalance(); 

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

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

      }


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



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

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

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



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

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


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

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

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


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




//Find last SDN

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

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

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

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

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




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

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

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

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


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

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

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

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

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




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

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

   
    }     
    
    
  
int countback=4;
int countup=4;

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

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

int lastflow = 500;
int lastfhigh = 500;


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


///find last fractal low within 11

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



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

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


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


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

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


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

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


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

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


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

     }
     
     
     
}




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

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




///lock in 1.5 pip after 4 in gains

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



///lock in 3 pips after 8 in gains

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

         

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

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

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

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



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

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

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

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


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

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

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

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


if (Equity_Based_Hedge) {


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

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

overdrivecounter =0;

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

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

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

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

   Sleep(1800);
   }

nlongs=0;
nshorts=0;

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

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

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

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

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

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

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

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

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


nlongs=0;
nshorts=0;

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

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

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

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

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

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

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

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

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

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

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

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

nlongs=0;
nshorts=0;

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

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

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

 nlongs=0;
nshorts=0;

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

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


double fullhedge_shorts = nlongs-nshorts;

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

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


}


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

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

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

////golf buy at purple haze                

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

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

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



///opening longs - BURN

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

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

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

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

 
 
 
/// opening shorts 

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


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


/// opening shorts BURN

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

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

       
  return(0);
}

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

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

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

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

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

      TrueRangeSum += TrueRangeHigh;
      TrueRangeSum -= TrueRangeLow;
    }

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

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

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

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


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

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

  

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

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


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

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