Download MetaTrader 5
To add comments, please log in or register
How to choose the most appropriate signal and subscribe to it in no time
brettosm8
241
brettosm8 2014.07.02 02:58 

Hi there,

Quick question.

I want to open an order based on the previous order that hit it's stoplosss.

To access the order that has just hit stoploss, such as it's OrderType(), OrderProfit(), OrderMagicNumber() etc, do I need to select it from ORDER_HISTORY, or can I access it from ORDER_POOL as it hits stoploss, from within my code.

Below is code that doesn't appear to open a new order after a current order closes with a loss.

void closeAndEscalateOrders()
   {
      // if reahces SL and trade is loss, then escalate trade
      if(!OrderSelect(0, SELECT_BY_POS)) Print("Error: Unable to select order! code #", GetLastError());
      
      if(OrderType() == OP_BUY)
         {
            // if SL reached and trade is loss
            if(Bid <= OrderStopLoss() && OrderProfit() < 0)
               {
                  stopLoss = OrderStopLoss();
                  if(!OrderClose(OrderTicket(),OrderLots(),Ask,3)) Print("Error: Unable to close order! code #", GetLastError());
                  Print("Level: ", levelCount);
                  levelCount++;
                  if(!OrderSend(Symbol(),OP_SELL,volume*volumeMultiplier,Bid,3,stopLoss+stopLossDistance,0)) Print("Error: Unable to send order! code #", GetLastError());
               }// end if
               
            // if SL reached and trade is win
            if(Bid <= OrderStopLoss() && OrderProfit() >= 0)
               {
                  if(!OrderClose(OrderTicket(),OrderLots(),Ask,3)) Print("Error: Unable to close order! code #", GetLastError());
                  Print("Won at level: ", levelCount);
               }// end if
         }// end OrderType OP_BUY
      
      if(OrderType() == OP_SELL)
         {
            // if SL reached and trade is loss
            if(Ask >= OrderStopLoss() && OrderProfit() < 0)
               {
                  stopLoss = OrderStopLoss();
                  if(!OrderClose(OrderTicket(),OrderLots(),Bid,3)) Print("Error: Unable to close order! code #", GetLastError());
                  Print("Level: ", levelCount);
                  levelCount++;
                  if(!OrderSend(Symbol(),OP_BUY,volume*volumeMultiplier,Ask,3,stopLoss-stopLossDistance,0)) Print("Error: Unable to send order! code #", GetLastError());
               }// end if
               
            // if SL reached and trade is win
            if(Ask >= OrderStopLoss() && OrderProfit() >= 0)
               {
                  if(!OrderClose(OrderTicket(),OrderLots(),Ask,3)) Print("Error: Unable to close order! code #", GetLastError());
                  Print("Won at level: ", levelCount);
               }// end if
         }// end OrderType OP_SELL
   }// end closeAndEscalateOrders


Thanks!

Brad.

qjol
3243
qjol 2014.07.02 03:43  
brettosm8
241
brettosm8 2014.07.02 07:45  

Hi there,

I have updated my code as below.  In the function escalateOrders(),

if(Ask >= stopLoss) // Stoploss has been hit

doesn't appear to ever evaluate as true and a therefore a buy order is sent.

Below the code I have included a screen shot to show where I'm expecting it to do so.

string comment;

extern double boxSize = .0025;
extern double reversalAmount = 1;
long chartID = ChartID();
//-- place orders
bool actioned;
double boxTop;
double boxBottom;
double stopLossDistance = boxSize * reversalAmount;
int TF;
extern double minVolume = 0.01;
extern double volumeMultiplier = 2;
double volume = minVolume;
int levelCount;
//-- cancelInvalidatedOrders
bool orderOpened;
int ticket;
double stopLoss;
int orderType;
bool invalidatedOrdersCanceled;
//-- updateStopLoss
double nextBoxTop;
double nextBoxBottom;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
      placeOrders();
      cancelInvalidatedOrders();
      escalateOrders();
      updateStopLoss();
  }
//+------------------------------------------------------------------+
void updateStopLoss()
   {
      // if price reaches next box, update SL.
      for (int i = OrdersTotal(); i > 0; i--)
         {
            if(!OrderSelect(i-1,SELECT_BY_POS)) Print("Error: Unable to select order! code #", GetLastError());
            
            if(OrderMagicNumber()<20)
               {
                  if(OrderType() == OP_BUY)
                     {
                        if(Bid >= nextBoxTop)
                           {
                              nextBoxTop += boxSize;
                              if(!OrderModify(OrderTicket(),OrderOpenPrice(), nextBoxTop,0,0)) Print("Error: Unable to modify order! code #", GetLastError());
                           }// if Ask >= boxTop + boxSize
                     }// OrderType OP_BUY
      
                  if(OrderType() == OP_SELL)
                     {
                        if(Ask <= nextBoxBottom)
                           {
                              nextBoxBottom -= boxSize;
                              if(!OrderModify(OrderTicket(),OrderOpenPrice(), nextBoxBottom,0,0)) Print("Error: Unable to modify order! code #", GetLastError());
                           }// end Bid <= nextBoxBottom
                     }// OrderType OP_SELL
               }// end for
         }// end for
   }

void escalateOrders()
   {  
      // if reahces SL and trade is loss, then escalate trade
      for (int i = OrdersTotal(); i > 0; i--)
         {
            if(!OrderSelect(i-1, SELECT_BY_POS)) Print("Error: Unable to select order! code #", GetLastError());
            
            if(OrderMagicNumber() < 20)
               {
                  if(orderType == OP_BUY)
                     {
                        if(Bid <= stopLoss) // Stoploss has been hit
                           {
                              comment += "\nFound Bid <= OrderStopLoss";
                              Comment(comment);
                              
                              if(!OrderSelect(ticket, SELECT_BY_TICKET,MODE_HISTORY)) Print("Error: Unable to select automatically closed order! code #", GetLastError());
                              comment += "\nSelected closed order";
                              Comment(comment);
                              
                              if(OrderProfit() < 0) // Position is a loss
                                 {
                                    comment += "\nDetermined order profit < 0";
                                    Comment(comment);
                                    
                                    // Position closed automatically
                                    comment += "\nPosition closed automatically";
                                    Comment(comment);
                                    
                                    // Open order in opposite direction
                                    volume *= volumeMultiplier;
                                    if(!OrderSend(Symbol(),OP_SELL,volume,Bid,3,boxTop,0,"",10+TF)) Print("Error: Unable to send order! code #", GetLastError());
                                    levelCount++;
                                    comment += "\nOrder opened in opposite direction";
                                    comment += "\nlevelCount: " + IntegerToString(levelCount);
                                    Comment(comment);
                                 }// end if
                           }// end if
                     }// end if
                  if(orderType == OP_SELL)
                     {
                        if(Ask >= stopLoss) // Stoploss has been hit
                           {
                              comment += "\nFound Bid <= OrderStopLoss";
                              Comment(comment);
                              
                              if(!OrderSelect(ticket, SELECT_BY_TICKET,MODE_HISTORY)) Print("Error: Unable to select automatically closed order! code #", GetLastError());
                              comment += "\nSelected closed order";
                              Comment(comment);
                              
                              if(OrderProfit() < 0) // Position is a loss
                                 {
                                    comment += "\nDetermined order profit < 0";
                                    Comment(comment);
                                    
                                    // Position closed automatically
                                    comment += "\nPosition closed automatically";
                                    Comment(comment);
                                    
                                    // Open order in opposite direction
                                    volume *= volumeMultiplier;
                                    if(!OrderSend(Symbol(),OP_SELL,volume,Bid,3,boxTop,0,"",10+TF)) Print("Error: Unable to send order! code #", GetLastError());
                                    levelCount++;
                                    comment += "\nOrder opened in opposite direction";
                                    comment += "\nlevelCount: " + IntegerToString(levelCount);
                                    Comment(comment);
                                 }// end if
                           }// end if Ask <= OrderStopLoss
                     }// end if OrderType == OP_SELL
               }// end if OrderMagicNumber < 20
         }// end for OrdersTotal     
   }// end closeAndEscalateOrders

void cancelInvalidatedOrders()
   {  
      if(!invalidatedOrdersCanceled)
         {
         // Determine if an order has been opened.
         Print("cancelInvalidatedOrders()");
         if (!orderOpened)
            {
               for (int i = OrdersTotal(); i > 0;i--)
                  {
                     if(!OrderSelect(i-1, SELECT_BY_POS)) Print("Error: Unable to select order! code #", GetLastError());
                     Print("Before OrderMagicNumber()<20");             
                     if(OrderMagicNumber()<20)
                        {
                           Print("After OrderMagicNumber()<20");
                           Print("OrderTicket: ", OrderTicket());
                           if (OrderType() == OP_BUY || OrderType() == OP_SELL) 
                              {
                                 orderOpened = true;
                                 comment += "\nConfirmed orders opened.";
                                 Comment(comment);
                              }// end if
                        }// end if OrderMagicNumber < 20
                  }// end for
            }// end if
         
         if (orderOpened)
            {
               for (int i = OrdersTotal(); i > 0; i--)
                  {
                     if(!OrderSelect(i-1, SELECT_BY_POS)) Print("Error: Unable to select order! code #", GetLastError());
                     if(OrderMagicNumber()<20)
                        {
                           if (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP)
                              {
                                 if(!OrderDelete(OrderTicket())) Print("Error: Unable to delete order! code #", GetLastError());
                                 comment += "\nOrderDeleted";
                                 Comment(comment);
                              }// end if
                        }//end if OrderMagicNumber < 20
                  }// end for
                  
               invalidatedOrdersCanceled = true;
               
               for (int i = OrdersTotal(); i > 0; i--)
                  {
                     if(!OrderSelect(i-1, SELECT_BY_POS)) Print("Error: Unable to select order! code #", GetLastError());
                     if(OrderMagicNumber()<20)
                        {
                           ticket      = OrderTicket();
                           stopLoss    = OrderStopLoss();
                           orderType   = OrderType();
                           comment += "\nTicket: " + ticket;
                           comment += "\nStopLoss: " + stopLoss;
                           comment += "\nOrderType: " + orderType;
                           Comment(comment);
                        }// end OrderMagicNumber < 20
                  }// end for
            }// end if
         }// end if invalidatedOrdersCanceled
   }// end cancelInvalidatedOrders

void placeOrders()
   {  
      while (!actioned)
         {
            // locate box price is trading within
         boxBottom      = boxSize * int(Ask / boxSize);
         boxTop         = boxBottom + boxSize;
         nextBoxBottom  = boxBottom - boxSize;
         nextBoxTop     = boxTop + boxSize;
         
         // place orders at box's top and bottom
         levelCount++;
         
         // magic number: 
         // 1x = Modified martingale system
         // x1 = Time frame i.e.
         //       M1: 1    M5: 2    M15: 3   M30: 4   H1: 5    H4: 6    D1: 7    W1: 8    MN: 9
         
         switch (Period())
            {
               case 1:     TF = 1; break; //M1
               case 5:     TF = 2; break; //M5
               case 15:    TF = 3; break; //M15
               case 30:    TF = 4; break; //M30
               case 60:    TF = 5; break; //H1
               case 240:   TF = 6; break; //H4
               case 1440:  TF = 7; break; //D1
               case 10080: TF = 8; break; //W1
               case 43200: TF = 9; break; //MN
               default:    Print("Error: a case doesn't exist for Period() ", Period());
            }
         
         if(!OrderSend(Symbol(), OP_BUYSTOP, volume, boxTop, 3, NormalizeDouble(boxBottom,4), 0, "", 10+TF))
            {
               Print("OrderSend failed with error #",GetLastError());
            }// end if
         if(!OrderSend(Symbol(), OP_SELLSTOP, volume, boxBottom, 3, NormalizeDouble(boxTop,4), 0, "", 10+TF))
            {
               Print("OrderSend failed with error #",GetLastError());
            }// end if

         actioned = true;
         comment = "Orders placed";
         Comment(comment);
         }// end while
   }// end placeOrders


I am running this on the EURUSD M1 TF per tick but I have included a M5 chart below.

Your assistance much appreciated,

Brad

brettosm8
241
brettosm8 2014.07.02 12:26  
I'm trying another approach on this and may not need this answered..
Ian Venner
2583
Ian Venner 2014.07.02 16:19  
if(!OrderSelect(ticket, SELECT_BY_TICKET,MODE_HISTORY))

SELECT_BY_TICKET doesn't use one of the trade pools it calls the ticket directly so your code will find it regardless of open or closed.

If you want to check if it is closed call the OrderCloseTime() in the same loop. It will return 0 if it is still open.

Also you are calling OrderSelect() loops a lot of times, that is not very efficient.

/
To add comments, please log in or register