Download MetaTrader 5

Change Trade Direction when SL hit

To add comments, please log in or register
Agus Widjaja
148
Agus Widjaja  

Can anybody help please ?

I have EA like this :

#property copyright "Copyright © 2016, Agus Widjaja"
#property link      "fandelafx.co"
//#property strict

//---- input parameters

extern double Lots                           = 0.1;
extern int    TakeProfit                     = 10;  
extern int    StopLoss                       = 10; 
int           Trailing_Stop                  = 0;
int           MaximumOpenTrade               = 1;
int           MaxOpenTrade                   = 300;

extern string _MINIMUMPROFIT                 = "______ TARGET MINIMUM PROFIT ______";
extern bool    Use_Minimum_Profit            = true;
extern int     Minimum_point                 = -10;
 
extern string _TIMEFILTER                    = "_______ TIME FILTER BROKER TIME _______";
extern bool    Use_TimeFilter                = false;
extern int     StartHour                     = 2;
extern int     EndHour                       = 15;
int    EndHour1, StartHour1, GMTOffset;
string comment1;

extern int     Magic                         = 291275;

bool   STP_Broker                     = false;  
bool bolehbuy=true, bolehsell=true;
double MinLots, MaxLots, minlot, TPBuy, SLBuy;
int    DIGIT, convert, slippage=10, spread,stoplevel;
double last_lot_sell, last_price_sell, last_lot_buy, last_price_buy, last_price, last_lot;
int    last_type, pending, OpenOrders, cnt, openbuy, opensell;
bool   CLOSE, DELETE;
datetime time;
double last_tp, last_sl;
int buystop=0;
int buylimit=0;
int sellstop=0;
int selllimit=0;
string X[401];
datetime last_time_open;
double H1_H0, H1_L0, H1_H1, H1_L1, H1_H2, H1_L2, H1_H3, H1_L3, H1_O1, H1_C1, H1_O2, H1_C2, H1_O3, H1_C3;
double MA200, MA75, MA15, OSMA1, OSMA2, OSMA3, CCI, ATR, RSI ;
int tiket_buy=999999;
int tiket_sell=999999;
int tiket_buy_tertua;
int tiket_sell_tertua;
double tickvalue;
datetime timeclose;

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
minlot =MarketInfo(Symbol(),MODE_MINLOT);
if (minlot/0.01==1) {DIGIT=2;} else {DIGIT=1;}
if (MarketInfo (Symbol(), MODE_LOTSTEP)*10<1)  {DIGIT=2;} else {DIGIT=1;}
if (Digits==5 ||Digits==3) {convert=10; slippage=100;} else {convert=1;}
MinLots = NormalizeDouble((MarketInfo(Symbol(), MODE_MINLOT)),DIGIT);
MaxLots = NormalizeDouble((MarketInfo(Symbol(), MODE_MAXLOT)),DIGIT);
if(Lots<MinLots){Lots=MinLots;}
if(Lots>MaxLots){Lots=MaxLots;}
Lots = NormalizeDouble (Lots,DIGIT);
stoplevel=(int)MarketInfo(Symbol(),MODE_STOPLEVEL);
spread = (int) MarketInfo(Symbol(),MODE_SPREAD);
if (Trailing_Stop*convert<stoplevel+spread && Trailing_Stop!=0) {Trailing_Stop = (int)((stoplevel+spread)/convert);}
getOpenOrders(TakeProfit, StopLoss, Trailing_Stop, 0, 0);
tickvalue = MarketInfo (Symbol(),MODE_TICKVALUE);


//-------------------------------------------------------------------+
// time check
//-------------------------------------------------------------------

if(TimeCurrent()-last_time_open<7200) {return(0);}

//-----------------------------------------------------------------
// Bar checks
//-----------------------------------------------------------------

MA200       =iMA(Symbol(),PERIOD_M5,200,0,MODE_EMA,PRICE_CLOSE,1);
MA75        =iMA(Symbol(),PERIOD_M5,50,0,MODE_EMA,PRICE_CLOSE,1);
MA15        =iMA(Symbol(),PERIOD_M5,15,0,MODE_EMA,PRICE_CLOSE,1);
OSMA1       =iOsMA(Symbol(),PERIOD_M5,12,26,9,PRICE_CLOSE,1);
OSMA2       =iOsMA(Symbol(),PERIOD_M5,12,26,9,PRICE_CLOSE,2);
OSMA3       =iOsMA(Symbol(),PERIOD_M5,12,26,9,PRICE_CLOSE,3);
CCI         =iCCI(Symbol(),PERIOD_M5,14,PRICE_CLOSE,1);
ATR         =iATR(Symbol(),PERIOD_M5,14,1);
RSI         =iRSI(Symbol(),PERIOD_M5,14,PRICE_CLOSE,1);

H1_H0       =iClose(Symbol(),PERIOD_M5,1);
H1_L0       =iClose(Symbol(),PERIOD_M5,1);
H1_O1       =iOpen(Symbol(),PERIOD_H1,1);
H1_C1       =iClose(Symbol(),PERIOD_H1,1);
H1_O2       =iOpen(Symbol(),PERIOD_H1,2);
H1_C2       =iClose(Symbol(),PERIOD_H1,2);
H1_O3       =iOpen(Symbol(),PERIOD_H1,3);
H1_C3       =iClose(Symbol(),PERIOD_H1,3);

openord();
if (OpenOrders>=MaximumOpenTrade && timeclose!=iTime (Symbol(),0,0))
   {
      if (buy()  && opensell>0) {CloseAllSelective(0); timeclose=iTime (Symbol(),0,0);}
      if (sell() && openbuy>0)  {CloseAllSelective(0); timeclose=iTime (Symbol(),0,0);}
   }
   
openord();
if (OpenOrders>=0 )
   {
      if (closesell()  && opensell>0) {CloseAllProfit(0); }
      if (closebuy()   && openbuy>0)  {CloseAllProfit(0); }
   }  
    
openord();
if (OrdersTotal()<MaxOpenTrade && OpenOrders<MaximumOpenTrade && TimeFilter() && time!=iTime (Symbol(),0,0))
   {
      if (buy() && opensell<1)
        {
            if (OPEN (Symbol(), OP_BUY, Blue, Lots, slippage, Ask, false, StopLoss, TakeProfit, "", Magic))
               {time=iTime (Symbol(),0,0); bolehbuy=false; bolehsell=true;}
         }
     
      if (sell()  && openbuy<1)
        {
            if (OPEN (Symbol(), OP_SELL, Red, Lots, slippage, Bid, false, StopLoss, TakeProfit, "", Magic))
               {time=iTime (Symbol(),0,0);  bolehbuy=true; bolehsell=false;}
         }
   }

//-------------------------------------------------------------------
   return(0);
  //}
//+------------------------------------------------------------------+

  
 //-------------------------------------------------------------------

if (STP_Broker)
   {
      ModifyTP_STP (TakeProfit);
      ModifySL_STP (StopLoss);
   }

  int Error=GetLastError();
  if(Error==130){Alert("Wrong stops. Retrying."); RefreshRates();}
  if(Error==133){Alert("Trading prohibited.");}
  if(Error==2){Alert("Common error.");}
  if(Error==146){Alert("Trading subsystem is busy. Retrying."); Sleep(500); RefreshRates();}

   return(0);
  }
//+------------------------------------------------------------------+

bool closebuy()
{
  //if(ATR>0.0007 && OSMA1>0 && OSMA1<OSMA2 && OSMA2<OSMA3)   {return (true);}
  //if(MA75>MA200 && H1_L0>MA75 && ATR>0.0007 && OSMA1>0 && OSMA1<OSMA2 && OSMA2<OSMA3)   {return (true);}
  //else {return (false);}
}
bool closesell()
{
  //if(ATR>0.0007 && OSMA1<0 && OSMA1>OSMA2 && OSMA2>OSMA3)   {return (true);}
  //if(MA75<MA200 && H1_L0<MA75 && ATR>0.0007 && OSMA1<0 && OSMA1>OSMA2 && OSMA2>OSMA3)   {return (true);}
  //else {return (false);}
}  

// BUY = 0
// SELL = 1
// BUYLIMIT=2
// SELLIMIT=3
// BUYSTOP = 4
// SELLSTOP = 5
void CloseAllProfit (int tipe)
{
    int retry = 0;
    CLOSE=false;
    DELETE=false;
    for(cnt=OrdersTotal();cnt>=0;cnt--)
       {
         if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
         {
             if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic)
             {
               if (OrderType()==OP_BUY && (tipe==0 || tipe==7))
                  {
                    if (OrderProfit()/(OrderLots()*tickvalue) >= Minimum_point*10 || !Use_Minimum_Profit)
                     {
                        retry=0;
                        while (CLOSE==false)
                                {
                                 RefreshRates();
                                 CLOSE = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,Blue);
                                 Print ("CLOSE BUY CRITERIA");
                                if (CLOSE==false) {Sleep(1000); retry++;}
                                 if (GetLastError()==4108 || GetLastError()==145) {CLOSE=true;}
                                }
                          CLOSE=false;
                     }
                  }
                 
                  if (OrderType()==OP_SELL && (tipe==1 || tipe==7))
                  {
                    if (OrderProfit()/(OrderLots()*tickvalue) >= Minimum_point*10 || !Use_Minimum_Profit)
                     {
                        retry=0;
                        while (CLOSE==false)
                                {
                                  RefreshRates();
                                  CLOSE = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,Red);
                                  Print ("CLOSE SELL CRITERIA");
                                  if (CLOSE==false) {Sleep(1000); retry++;}
                                  if (GetLastError()==4108 || GetLastError()==145) {CLOSE=true;}
                                }
                          CLOSE=false;
                      }
                  }   
              }
          }
        }



// BUY = 0
// SELL = 1
// BUYLIMIT=2
// SELLIMIT=3
// BUYSTOP = 4
// SELLSTOP = 5
void CloseAllSelective (int tipe)
{
    int retry=0;
    CLOSE=false;
    DELETE=false;
    for(cnt=OrdersTotal();cnt>=0;cnt--)
       {
         if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
         {
             if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic)
             {
               if (OrderTicket()==tiket_buy_tertua && OrderType()==OP_BUY && (tipe==0 || tipe==7))
                  {
                    if (OrderProfit()/(OrderLots()*tickvalue) >= Minimum_point*10 || !Use_Minimum_Profit)
                     {
                        retry=0;
                        while (CLOSE==false)
                                {
                                 RefreshRates();
                                 CLOSE = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,Blue);
                                if (CLOSE==false) {Sleep(1000); retry++;}
                                 if (GetLastError()==4108 || GetLastError()==145) {CLOSE=true;}
                                }
                          CLOSE=false;
                     }
                  }
               if (OrderTicket()==tiket_sell_tertua && OrderType()==OP_SELL && (tipe==1 || tipe==7))
                  {
                    if (OrderProfit()/(OrderLots()*tickvalue) >= Minimum_point*10 || !Use_Minimum_Profit)
                     {
                        retry=0;
                        while (CLOSE==false)
                                {
                                  RefreshRates();
                                  CLOSE = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,Red);
                                  if (CLOSE==false) {Sleep(1000); retry++;}
                                  if (GetLastError()==4108 || GetLastError()==145) {CLOSE=true;}
                                }
                          CLOSE=false;
                      }
                  }
                }    
              }
        }

}

bool buy()
{
  if(Hour()>=9 && Hour()<10) {
  if(H1_C1>H1_O1 && H1_C2>H1_O2 && H1_C3>H1_O3)   {return (true);}
  if(H1_C1>H1_O1 && H1_C2>H1_O2 && H1_C3<H1_O3)   {return (true);}
  if(H1_C1>H1_O1 && H1_C2<H1_O2 && H1_C3>H1_O3)   {return (true);}
  if(H1_C1<H1_O1 && H1_C2>H1_O2 && H1_C3>H1_O3)   {return (true);}
  else {return (false);}}
}

bool sell()
{
  if(Hour()>=9 && Hour()<10)  {
  if(H1_C1<H1_O1 && H1_C2<H1_O2 && H1_C3<H1_O3)   {return (true);}
  if(H1_C1<H1_O1 && H1_C2<H1_O2 && H1_C3>H1_O3)   {return (true);}
  if(H1_C1<H1_O1 && H1_C2>H1_O2 && H1_C3<H1_O3)   {return (true);}
  if(H1_C1>H1_O1 && H1_C2<H1_O2 && H1_C3<H1_O3)   {return (true);}
  else {return (false);}}
}


void ModifyTP_STP (double takeProfit) // TP disini diambil dari OrderTakeProfit() dari OP terakhir
{
 
   bool modif;
double TP;
for (cnt = OrdersTotal(); cnt >= 0; cnt--)
    {
      if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber()==Magic && (OrderType()==OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP) )
         {
           TP = OrderOpenPrice() + takeProfit*convert*Point;
           if (takeProfit==0) {TP=0;}
           if (takeProfit*convert<stoplevel) {TP=0;} // masukkan tp ke mode hidden.


           if (NormalizeDouble (OrderTakeProfit(),Digits)!=NormalizeDouble (TP,Digits) && NormalizeDouble (OrderTakeProfit(),Digits)==0)
              {
                modif = OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), NormalizeDouble (TP,Digits), 0, CLR_NONE);
              }
         }
         if (OrderSymbol() == Symbol() && OrderMagicNumber()==Magic && (OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP) )
         {
           TP = OrderOpenPrice() - takeProfit*convert*Point;
           if (takeProfit==0) {TP=0;}
           if (takeProfit*convert<stoplevel) {TP=0;} // masukkan tp ke mode hidden.
           if (NormalizeDouble (OrderTakeProfit(),Digits)!=NormalizeDouble (TP,Digits) && NormalizeDouble (OrderTakeProfit(),Digits)==0)
              {
                modif = OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), NormalizeDouble (TP,Digits), 0, CLR_NONE);
              }
         }  
     }
   }
}   

void ModifySL_STP (double stopLoss) // TP disini diambil dari OrderTakeProfit() dari OP terakhir
{
bool modif;
double SL;
for (cnt = OrdersTotal(); cnt >= 0; cnt--)
    {
      if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber()==Magic && (OrderType()==OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP) )
         {
           SL = OrderOpenPrice() - stopLoss*convert*Point;
           if (stopLoss==0) {SL=0;}
           if (stopLoss*convert<stoplevel+spread) {SL=0;} // masukkan tp ke mode hidden.
          
           if (NormalizeDouble (OrderStopLoss(),Digits)!=NormalizeDouble (SL,Digits) && NormalizeDouble (OrderStopLoss(),Digits)==0)
              {
                modif = OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble (SL,Digits), OrderTakeProfit(), 0, CLR_NONE);
              }
         }
         if (OrderSymbol() == Symbol() && OrderMagicNumber()==Magic && (OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP) )
         {
           SL = OrderOpenPrice() + stopLoss*convert*Point;
           if (stopLoss==0) {SL=0;}
           if (stopLoss*convert<stoplevel+spread) {SL=0;} // masukkan tp ke mode hidden.
           
           if (NormalizeDouble (OrderStopLoss(),Digits)!=NormalizeDouble (SL,Digits) && NormalizeDouble (OrderStopLoss(),Digits)==0)
              { 
                modif = OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble (SL,Digits), OrderTakeProfit(), 0, CLR_NONE);
              }
         }  
     }
   }
}

bool OPEN (string symbol, int tipe, color warna, double lots, int slip, double harga, bool hidden_mode, double stopLoss, double takeProfit, string komen, int magic  )
{
     bool ret = false;
     double TP = 0, SL = 0;
     int ticket=0;
     //while (ticket<=0)
           {
             RefreshRates();
             stoplevel=(int)MarketInfo(Symbol(),MODE_STOPLEVEL);
             spread = (int)MarketInfo(Symbol(),MODE_SPREAD);
             if (tipe==OP_BUY || tipe==OP_BUYLIMIT || tipe==OP_BUYSTOP)
                {
                  if (takeProfit*convert>stoplevel && !hidden_mode)            {TP=harga+takeProfit*convert*Point;} else {TP=0;}
                  if (stopLoss*convert>stoplevel+spread && !hidden_mode)       {SL=harga-stopLoss*convert*Point;}   else {SL=0;}
                  if (takeProfit==0) {TP=0;}
                  if (stopLoss==0) {SL=0;}
                }
               
             if (tipe==OP_SELL || tipe==OP_SELLLIMIT || tipe==OP_SELLSTOP)
                {
                  if (takeProfit*convert>stoplevel && !hidden_mode)         {TP=harga-takeProfit*convert*Point;} else {TP=0;}
                  if (stopLoss*convert>stoplevel+spread && !hidden_mode)    {SL=harga+stopLoss*convert*Point;}   else {SL=0;}
                  if (takeProfit==0) {TP=0;}
                  if (stopLoss==0) {SL=0;}
                }
               
             ticket = OrderSend(symbol,tipe,lots,harga,slip,NormalizeDouble(SL,Digits),NormalizeDouble(TP,Digits),komen,magic,0,warna);
             if (ticket<=0) {Sleep(1000);} else {ret = true;}
           }

   return(ret);
}    


bool TimeFilter()
{
   bool ret = false;
EndHour1=EndHour+GMTOffset;
StartHour1=StartHour+GMTOffset;
if ((StartHour+GMTOffset)<0)  {StartHour1=StartHour+GMTOffset+24;}
if ((EndHour+GMTOffset)<0)    {EndHour1=EndHour+GMTOffset+24;}    
if ((StartHour+GMTOffset)>24) {StartHour1=StartHour+GMTOffset-24;}
if ((EndHour+GMTOffset)>24)   {EndHour1=EndHour+GMTOffset-24;}   


if (Use_TimeFilter==false) {comment1=""; return (true);}
      else

if (StartHour1<EndHour1)
       {
         if (Hour()>=StartHour1 && Hour()<EndHour1){comment1=""; ret = true;} else {comment1="WARNING: Trading diluar Time Filter, No Open Position\n"; ret = false;}
       }

     else
    
if (StartHour1>EndHour1)

       {
         if (Hour()>=StartHour1 || Hour()<EndHour1){comment1=""; ret = true;} else {comment1="WARNING: Trading diluar Time Filter, No Open Position\n"; ret = false;}
       }

   return(ret);
}


//+========================================================+
//| GET PIP VALUE                                          |
//+========================================================+
double getPipValue(double ord,int dir)
{
  double val;
  RefreshRates();
  if(dir == 1) val=(NormalizeDouble(ord,Digits) - NormalizeDouble(Ask,Digits));
  else
  val=(NormalizeDouble(Bid,Digits) - NormalizeDouble(ord,Digits));    
  val = val/Point;
  return(val);
}

//+========================================================+
//| GETOPENORDER                                           |
//+========================================================+
void getOpenOrders(double takeProfit, double stopLoss, double trailing_Stop, double StartLock, double Lock)
{
  int totalorders = OrdersTotal();
  for(int j=0; j<totalorders;j++)
       {
         if(OrderSelect(j, SELECT_BY_POS, MODE_TRADES))
         {
            if((OrderType() == OP_BUY || OrderType() == OP_SELL) && OrderSymbol() == Symbol() && OrderMagicNumber()==Magic)
            {
              double val=getPipValue(OrderOpenPrice(),OrderType());            
              if (takeProfit!=0)    {takeProfit(takeProfit, val,OrderTicket());}
              if (stopLoss!=0)      {killTrade(stopLoss, val, OrderTicket());}
              if (trailing_Stop!=0) {TrailingPositions(trailing_Stop, 1, OrderTicket());}
           }
       }          
   }
}
 
//+========================================================+
//| TAKE PROFIT HIDDEN FROM BROKER NAKAL, NO MORE CURANG   |
//+========================================================+
void takeProfit(double TP, double pips, int ticket)
{
   bool ordCls = false;
  if(OrderSelect(ticket, SELECT_BY_TICKET)==true)
       {
            spread=(int)MarketInfo(Symbol(),MODE_SPREAD);
            if(pips>=TP*convert)
                 {
                     if(OrderType()==1) {ordCls = OrderClose(ticket, OrderLots(), Ask, slippage, Red);}
                     if(OrderType()==0) {ordCls = OrderClose(ticket, OrderLots(), Bid, slippage, Blue);}
                 }
        }
}

//+========================================================+
//| STOPLOSS  HIDDEN FROM BROKER NAKAL, NO MORE CURANG     |
//+========================================================+
void killTrade(double SL, double pips, int ticket)

   bool ordCls = false;
    if(OrderSelect(ticket, SELECT_BY_TICKET)==true)
         {   
            
              if(pips<=-SL*convert)
                    {
                         if(OrderType()==1)
                                {ordCls = OrderClose(ticket,OrderLots(),Ask,slippage,Red);}
                                            
                         if (OrderType()==0)         
                                {ordCls = OrderClose(ticket,OrderLots(),Bid,slippage,Blue);}
                
                     }
          }
}

//+========================================================+
//| TRAILING STOP                                          |
//+========================================================+
void TrailingPositions(double TL, double TPStep, int ticket)
{
 bool mdf = false;
 if (OrderType()==OP_BUY  )
       {
          if (NormalizeDouble (Bid,Digits)-NormalizeDouble (OrderOpenPrice(),Digits) >= NormalizeDouble (TL*convert*Point,Digits) )
                {
                   if (NormalizeDouble (OrderStopLoss(),Digits) < NormalizeDouble (Bid-(TL+TPStep-1)*convert*Point,Digits) || NormalizeDouble (OrderStopLoss(),Digits)==0)
                         {
                           mdf = OrderModify(ticket,OrderOpenPrice(),NormalizeDouble (Bid-TL*convert*Point,Digits) ,OrderTakeProfit(),0,CLR_NONE);
                           return;
                         }
                }
        }

 if (OrderType()==OP_SELL )
       {
          if (NormalizeDouble (OrderOpenPrice(),Digits) - NormalizeDouble (Ask,Digits) >= NormalizeDouble (TL*convert*Point,Digits) )
                {
                   if (NormalizeDouble (OrderStopLoss(),Digits) > NormalizeDouble (Ask+(TL+TPStep-1)*convert*Point,Digits) || NormalizeDouble (OrderStopLoss(),Digits) ==0)
                          {
                            mdf = OrderModify(ticket,OrderOpenPrice(),NormalizeDouble (Ask+TL*convert*Point,Digits) ,OrderTakeProfit(),0,CLR_NONE);
                            return;
                          }
                }

       }
}






void openord()
{
OpenOrders=0; openbuy=0; opensell=0; pending=0;
buystop=0;
buylimit=0;
sellstop=0;
selllimit=0;
last_time_open = 0;
tiket_buy=2147483647;
tiket_sell=2147483647;

for(cnt=0;cnt<OrdersTotal();cnt++)  
   {
     if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
     {
       if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic && (OrderType()==OP_BUY ||OrderType()==OP_SELL))
         {
           OpenOrders++;
           last_price = OrderOpenPrice();
           last_lot   = OrderLots();
           last_type  = OrderType();
           last_tp    = OrderTakeProfit();
           last_sl    = OrderStopLoss();
           last_time_open = OrderOpenTime();
         }
    
         if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic && (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP || OrderType()==OP_SELLLIMIT))
         {pending++;}
    
         if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic && OrderType()==OP_BUYSTOP )
         {buystop++;}
     
          if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic && OrderType()==OP_BUYLIMIT )
         {buylimit++;}  
     
          if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic &&  OrderType()==OP_SELLSTOP )
         {sellstop++;} 
     
          if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic && OrderType()==OP_SELLLIMIT)
         {selllimit++;}    
           
          if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic && OrderType()==OP_BUY)
         {
            openbuy++;
            last_price_buy = OrderOpenPrice();
            last_lot_buy   = OrderLots();
            if (OrderTicket()<tiket_buy) {tiket_buy_tertua = OrderTicket(); tiket_buy=OrderTicket();}
         }
          if (OrderSymbol()==Symbol() && OrderMagicNumber() == Magic && OrderType()==OP_SELL)
         {
            opensell++;
            last_price_sell = OrderOpenPrice();
            last_lot_sell   = OrderLots();
            if (OrderTicket()<tiket_sell) {tiket_sell_tertua = OrderTicket(); tiket_sell = OrderTicket();}
         }
      }
   }
}


I want to add condition, if SL hits, directly open opposite way with double lot (for instance : open position is sell with lot = 1.0, when SL hits, directly open buy position with lot = 2.0)


Thank you,

Aleksei Beliakov
26391
Aleksei Beliakov  
hi you can simple check history and if there is new order with profit<0 you can make some action
Osama Shaban
1489
Osama Shaban  

I use this in my own code ...

Sorry, I can't trace others code as every coders uses his own logic, but in general mine could help you ...  I use it in my EA named My Money Machine ... it works with not bugs at all.

You have to call the LastCloseTrade() function before performing the following code to read the Last closed order (type + Lots + profit) to take the right decision ... 

         if(LastOrderProfit < 0){
            NewLots = NormalizeDouble(LastOrderLots*2,LotDigits);
            if(NewLots>MaxLots) NewLots = MaxLots;
            if((LastOrderType == 0){//0 = Buy
               ticket=OrderSend(Symbol(),OP_SELL,NewLots,Bid,Slippage,0,0,Expert_Name,MAGIC,0,Red);
               if(ticket<0){ Print("Sell_Stop OrderSend failed with error 3#",GetLastError()); }
               if(UseSound) PlaySound("alert.wav");

               Sleep(1000);
               if(ticket>0){
                  if(OrderSelect(ticket,SELECT_BY_TICKET)==true)
                  res = OrderModify(OrderTicket(),OrderOpenPrice(),Bid+StopLoss2*Point,Bid-TakeProfit2*Point,0,Green);
               }
               else{
                  Alert
                  ("OrderSend failed with error #",GetLastError());
               }
               
            }
            if(LastOrderType == 1){
               ticket=OrderSend(Symbol(),OP_BUY,NewLots,Ask,Slippage,0,0,Expert_Name,MAGIC,0,Blue);
               if(ticket<0){ Print("Buy_Stop OrderSend failed with error 4#",GetLastError()); }
               if(UseSound) PlaySound("alert.wav");
               
               Sleep(1000);
               if(ticket>0){
                  if(OrderSelect(ticket,SELECT_BY_TICKET)==true)
                  res = OrderModify(OrderTicket(),OrderOpenPrice(),Ask-StopLoss2*Point,Ask+TakeProfit2*Point,0,Green);
               }
               else
                  Alert("OrderSend failed with error #",GetLastError());
            }  
         
         }
...
...
...
} 


void LastClosedTrade(){ 
   int cnt, total; 
   total = OrdersHistoryTotal(); 
   for(cnt=0;cnt<total; cnt++){ 
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_HISTORY)==true)
   
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC && OrderProfit()!=0){
         LastOrderType = OrderType(); 
         LastOrderLots = OrderLots(); 
         LastOrderProfit = OrderProfit(); 
      }
   }
}
To add comments, please log in or register