Open opposite order - page 3

 
RaptorUK:

It can be if it has a different Magic Number than  MagicNumber  or it is for a symbol other than the symbol that the EA is running on or if it is a OP_SELLLIMIT or OP_BUYLIMIT . . .   also, you need to check the return values from your OrderDelete() calls . . .

Why do you need to call RefreshRates()  ?  I don't mean get rid of them,  but can you explain why you are calling RefreshRates() where you are ?


What are Function return values ? How do I use them ? 

 


Hi RaptorUK.

As far I understand the MagicNumber is the same and are OP_SELLSTOP and OP_BUYSTOP.

OrderDelete() calls , I'm afraid don't understand what you mean....

RefreshRates() I just put there after the problem with he close.

Now i'm in Lisbon (Portugal). 

Luis 

 
luisneves:


Hi RaptorUK.

As far I understand the MagicNumber is the same and are OP_SELLSTOP and OP_BUYSTOP.

OrderDelete() calls , I'm afraid don't understand what you mean.... 

When you call OrderDelete()   (by using the OrderDelete() function)  it returns a value, it returns a bool value,  if the value is true the OrderDelete() worked,  if it is false the OrderDelete() failed . . .  so check the return value and if it is false report the error to the log using Print()  or use Comment() or Alert()  so that you know you have a problem and can investigate it.

 

Based on your code I would make these changes . . . .  if it were my code I would make additional changes to print more information in the event of an error,  Bid, Ask, FreezeLevel, StopLevel, etc.  

void CloseAll()
   {
   int OrdType, GLError;
   
   RefreshRates();
                    
   for(int OrderPos = OrdersTotal()-1; OrderPos >= 0; OrderPos--)
      if( OrderSelect(OrderPos, SELECT_BY_POS, MODE_TRADES)
         && OrderMagicNumber() == MagicNumber 
         && OrderSymbol() == Symbol())
         {
         OrdType = OrderType();
         if(OrdType == OP_BUY || OrdType==OP_SELL)
            {
            if(!OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), UseSlippage, Yellow))
               GLError = GetLastError();
            }

         if(OrdType == OP_SELLSTOP || OrdType == OP_BUYSTOP || OrdType == OP_BUYLIMIT || OrdType == OP_SELLLIMIT)
            {
            if(!OrderDelete(OrderTicket())
               GLError = GetLastError();
            }

         if(GLError > 0) Print("Error Closing/Deleting Order, error # ", GLError, " for ticket: ", OrderTicket());         
         }
   } 
 
RaptorUK:

When you call OrderDelete()   (by using the OrderDelete() function)  it returns a value, it returns a bool value,  if the value is true the OrderDelete() worked,  if it is false the OrderDelete() failed . . .  so check the return value and if it is false report the error to the log using Print()  or use Comment() or Alert()  so that you know you have a problem and can investigate it.

 

Based on your code I would make these changes . . . .  if it were my code I would make additional changes to print more information in the event of an error,  Bid, Ask, FreezeLevel, StopLevel, etc.  

 

 


Hi RaptorUK,

The reason why the  pending order have not been deleted have to do with the taking profit that was to low in this case 5 pips. When I put it to 10 pips the order delete.My confusion come from the fact  if I had a routine to put the stoploss, open price and take profit out of the freeze zone why this have no work. Ok but now is working.

By the way, I want to close the opposite order once the other have been trigger.For that I've put this extra code but(you can start laughing...) but nothing....

Any help here?

 

 while(IsTradeContextBusy()) Sleep(10);
                   RefreshRates();
         Ticket=OrderSend(Symbol(),OP_BUYSTOP,LotSize,BuyLevel,UseSlippage,BuyStopLoss,BuyTakeProfit,"Buy Stop Order",MagicNumber,0,Green);
         if(Ticket>0)
         
          int o=OrderType();
          if (o==OP_BUY)
          OrderDelete(OrderTicket());        
           {
            if(OrderSelect(Ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY Stop Order Opened : ",OrderOpenPrice());
           }
         //else Print("Error opening BUY Stop Order : ",GetLastError());
 
luisneves:


Hi RaptorUK,

1.  The reason why the  pending order have not been deleted have to do with the taking profit that was to low in this case 5 pips. When I put it to 10 pips the order delete.My confusion come from the fact  if I had a routine to put the stoploss, open price and take profit out of the freeze zone why this have no work. Ok but now is working.

2.  By the way, I want to close the opposite order once the other have been trigger.For that I've put this extra code but(you can start laughing...) but nothing....

Any help here?


1.  Ah,  this is why you need to check return values and print error codes, etc.   You need to ensure tat any trade actions on any Order comply with the information here:  Requirements and Limitations in Making Trades

 

 2.  Yu have to wait for the Order to change type from OP_BUYSTOP to OP_BUY, it might take some time,  so you need to keep checking . . .  once it has turned into an  OP_BUY then you can close the opposite Order  and to do that you are going to have to find the correct Order to close.  you should read my recent conversation with WhooDoo22   that conversation covers a similar topic.

 

Hi RaptorUk,

I've follow the link you provided but the theme nevertheless interesting, is to long ans with so many diverge opinions that I've loos myself in them.

so, I've introduce a code to close the opposite pending  and again nothing and can't see nothing in the journal that gives a help soever.....  what am I missing here ......

 thanks for any light.....

Luis 

//Sell Pending Stop Loss & Take Profit Calculation     
     
   if(StopLoss>0)SellStopLoss=PendingSellPrice+(StopLoss*pt);
   if(TakeProfit>0)SellTakeProfit=PendingSellPrice-(TakeProfit*pt);
   
//Place Sell Pending Order
        
         while(IsTradeContextBusy()) Sleep(10);
                   RefreshRates();       
         Ticket=OrderSend(Symbol(),OP_SELLSTOP,LotSize,SellLevel,UseSlippage,SellStopLoss,SellTakeProfit,"Sell Stop Order",MagicNumber,0,Red);
         if(Ticket>0)OppositePendindDel();          
           {
            if(OrderSelect(Ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL Stop Order Opened : ",OrderOpenPrice());
           }
        //else Print("Error opening SELL Stop Order : ",GetLastError());
         } 
//+---------------------------------------------------------------------------+
int OppositePendindDel()
{
 int c,d,GLError;
 int e=OrdersTotal();
 
 for(c=e-1;c>=0;c--)
 {  
   OrderSelect(c,SELECT_BY_POS,MODE_TRADES);
   if(OrderType()==OP_BUY||OrderType()==OP_SELL)
   {
    for(d=e-1;d>=0;d--)
    {
     OrderSelect(d,SELECT_BY_POS,MODE_TRADES);
     
      if(OrderType()==OP_SELLSTOP)
     {
      if(!OrderDelete(OrderTicket()))
            GLError = GetLastError();
      
      return(1);
      }
      if(OrderType()==OP_BUYSTOP)
      {
       if(!OrderDelete(OrderTicket()))
             GLError = GetLastError();
       }
       if(GLError > 0) Print("Error Closing/Deleting Order, error # ", GLError, " for ticket: ", OrderTicket());
       return(1);
       }
      }
     }
    }
 
luisneves:

Hi RaptorUk,

I've follow the link you provided but the theme nevertheless interesting, is to long ans with so many diverge opinions that I've loos myself in them.

so, I've introduce a code to close the opposite pending  and again nothing and can't see nothing in the journal that gives a help soever.....  what am I missing here ......

 

RaptorUK:

 2.  You have to wait for the Order to change type from OP_BUYSTOP to OP_BUY, it might take some time,  so you need to keep checking . . .  once it has turned into an  OP_BUY then you can close the opposite Order  and to do that you are going to have to find the correct Order to close.  

 
RaptorUK:

 


 


Hi RaptorUK ,

 Ok, now seems that is deleting the opposite pending order after one pending comes triggered.,but now some orders come in doubles, meaning, the ea put a sell and buy at same time and lot size is the same for the two orders when it must put a order a time. I started get crazy.....

Any help here, please!!!! 

Files:
 
luisneves:


Hi RaptorUK ,

 Ok, now seems that is deleting the opposite pending order after one pending comes triggered.,but now some orders come in doubles, meaning, the ea put a sell and buy at same time and lot size is the same for the two orders when it must put a order a time. I started get crazy.....

Any help here, please!!!! 

Looking at your code I find it very hard to follow what you are trying to do,  I see very few comments to help me,  your start() function does not show me what you are trying to do on each tick,  you have no consistent layout of indentation.

What is the function  GoToClose()   meant to do ?  if you made some comments at the start of the function describing what it is supposed to do then I could see if it is actually doing what it is meant to be doing,  currently what it does is call a function,   CloseAll();   if any single trade that matches your Symbol & Magic Number is in profit by any amount,  or if you have more than 7 trades for any symbol and any Magic Number.  CloseAll()  only closes trades for your Symbol & Magic Number  so if you had 7 trades for a different Symbol or Magic Number GoToClose()  would keep calling CloseAll()  and nothing else will happen. 


If you placed a manual trade on your Demo account and then ran your EA it would do nothing . . .  it would see the trade but not ignore it,  it would count it and as a result not place a trade of it's own,  nor would it close this open trade.   What should your EA do in this situation ?  what if there were a trade placed by another EA with a different Magic Number ?

You need to get a clear picture of what you are trying to do,  comment your start() function so the flow and process is clear,  comment every function so it is clear what each is meant to do.   When you have done this you may well understand where your problem lies . . .

 
RaptorUK:

Looking at your code I find it very hard to follow what you are trying to do,  I see very few comments to help me,  your start() function does not show me what you are trying to do on each tick,  you have no consistent layout of indentation.

What is the function  GoToClose()   meant to do ?  if you made some comments at the start of the function describing what it is supposed to do then I could see if it is actually doing what it is meant to be doing,  currently what it does is call a function,   CloseAll();   if any single trade that matches your Symbol & Magic Number is in profit by any amount,  or if you have more than 7 trades for any symbol and any Magic Number.  CloseAll()  only closes trades for your Symbol & Magic Number  so if you had 7 trades for a different Symbol or Magic Number GoToClose()  would keep calling CloseAll()  and nothing else will happen. 


If you placed a manual trade on your Demo account and then ran your EA it would do nothing . . .  it would see the trade but not ignore it,  it would count it and as a result not place a trade of it's own,  nor would it close this open trade.   What should your EA do in this situation ?  what if there were a trade placed by another EA with a different Magic Number ?

You need to get a clear picture of what you are trying to do,  comment your start() function so the flow and process is clear,  comment every function so it is clear what each is meant to do.   When you have done this you may well understand where your problem lies . . .


Hi RaptorUK,

Sorry for the mess. To this moment seems that the EA is doing what one expect from it except this issue;

The EA should open an opposite order each time that the former order don't take the TakeProfit with a lot size increment and with the same TakeProfit amount and it does it.The issue is that it must put only one order a time and it put more than one. Taking a look on the report you can see that the order 6 and 7 are both a sell and the order 7 should be a buy.

Now I've put the the code by function. The reason that I have all those void calls is that I want to have a full working independent blocks and here I know that I am with problems to arrange this The Go to Open and go to Close is just a way to say if we don't have open orders the firs go to open if not the go to close ( is a mess I need to work on this...) I'm using symbol and magic number to guarantee that the ea just deal with is own orders.  

The main strategy is (and the blocks are by this order); 

1- Two pending orders are above  and under the price. Once the price triggers one of them the opposite pending is deleted. This is working.

2- If price picks the TakeProfit then the order is closed and the EA resumes again putting two pending orders and the process starts again. This is working

2- if price don't pick the TakeProfit and bounces back once it runs the TakeProfit amount down (for Buy orders) then a opposite Sell order should open with the same TakeProfit amount and with a lot size greater than the former one. This is working except that it puts more than one order and from the Report one could see that the orders 6 and 7 are both Sell orders and should be only one the 7 should be a Buy. 

3- Once the last order takes a profit all the open orders should close. And the process starts gain.This is working.

4- In this ping pong one should expect that at the most at 7 times an order picks the TakeProfit if not then these orders are closed.

5-To open opportunity for a increase profit a break even or minimum profit trailing stop should be used. for example, if we want for TakeProfit 2 pips then we wait for price reach 3 pips and then one of these functions ( break even or minimum profit trailing stop) put a stop line at the 2 pips level. If price goes up (for Buy) then the stop line will go with it and once the price bounce back 1 pip the the order close and because it have a profit all open orders are closed. Here I'm not sure if this can work properly. 

Thanks

Luis 

Files:
 
luisneves:


Hi RaptorUK,

Sorry for the mess. To this moment seems that the EA is doing what one expect from it except this issue;

The EA should open an opposite order each time that the former order don't take the TakeProfit with a lot size increment and with the same TakeProfit amount and it does it.The issue is that it must put only one order a time and it put more than one. Taking a look on the report you can see that the order 6 and 7 are both a sell and the order 7 should be a buy.

Now I've put the the code by function. The reason that I have all those void calls is that I want to have a full working independent blocks and here I know that I am with problems to arrange this The Go to Open and go to Close is just a way to say if we don't have open orders the firs go to open if not the go to close ( is a mess I need to work on this...) I'm using symbol and magic number to guarantee that the ea just deal with is own orders.  

The main strategy is (and the blocks are by this order); 

1- Two pending orders are above  and under the price. Once the price triggers one of them the opposite pending is deleted. This is working.

2- If price picks the TakeProfit then the order is closed and the EA resumes again putting two pending orders and the process starts again. This is working

2- if price don't pick the TakeProfit and bounces back once it runs the TakeProfit amount down (for Buy orders) then a opposite Sell order should open with the same TakeProfit amount and with a lot size greater than the former one. This is working except that it puts more than one order and from the Report one could see that the orders 6 and 7 are both Sell orders and should be only one the 7 should be a Buy. 

3- Once the last order takes a profit all the open orders should close. And the process starts gain.This is working.

4- In this ping pong one should expect that at the most at 7 times an order picks the TakeProfit if not then these orders are closed.

5-To open opportunity for a increase profit a break even or minimum profit trailing stop should be used. for example, if we want for TakeProfit 2 pips then we wait for price reach 3 pips and then one of these functions ( break even or minimum profit trailing stop) put a stop line at the 2 pips level. If price goes up (for Buy) then the stop line will go with it and once the price bounce back 1 pip the the order close and because it have a profit all open orders are closed. Here I'm not sure if this can work properly. 

Thanks

Luis 

 Ok, think that found what is wrong with the several orders opening. I had to include these on code (Negrito Italic);

Open Opposite Order
 
   double  MartingaleBuyPrice = Ask+StopLevel;
   if(MartingaleBuyPrice<UpperStopLevel)MartingaleBuyPrice=UpperStopLevel+MinStop*pt;
   
   double MartingaleSellPrice= Bid-StopLevel;
   if(MartingaleSellPrice>LowerStopLevel)MartingaleSellPrice=LowerStopLevel-MinStop*pt;
   
   int Op;  
   
   for(int Counter = OrdersTotal()-1; Counter >= 0; Counter--)
      {
      if(OrderSelect(Counter,SELECT_BY_POS,MODE_TRADES))  
         {
         if(OrderSymbol() == Symbol()&& OrderMagicNumber() == MagicNumber)
            {
            Op = OrderType();

            if(Op == OP_BUY && ((OrderOpenPrice()-OrderClosePrice())/pt)> ReturnDist && SellTicket==0)
               {                
               SellTicket = OrderSend(Symbol(), OP_SELL, mlots, MartingaleSellPrice, UseSlippage, 0, 0, "Sell Order", MagicNumber, 0, Red);
               if(SellTicket > 0) 
                  {
                  Print("Opposite Sell order placed # ", SellTicket);
                  AddLimitsSell();
                  }
               else
                  {
                  Print("Order Send failed, error # ", GetLastError() );
                  }
               }
               
            if(Op == OP_SELL && (OrderClosePrice()-OrderOpenPrice()/pt)> ReturnDist && BuyTicket==0)
               {               
               BuyTicket = OrderSend(Symbol(), OP_BUY, mlots, MartingaleBuyPrice, UseSlippage, 0, 0, "Buy Order", MagicNumber, 0, Green);
               if(BuyTicket > 0)
                  {
                  Print("Opposite Buy order placed # ", BuyTicket);
                  AddLimitsBuy();
                  }
               else
                  {  
                  Print("Order Send failed, error # ", GetLastError());
                  }   
               }
            }
         }
      }
   }
//+------------------------------------------------------------------+  
void AddLimitsBuy()
                  {
                  OrderSelect(BuyTicket,SELECT_BY_TICKET);
                  OpenPrice = OrderOpenPrice();
                  StopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
                                       RefreshRates();  
                                      UpperStopLevel = Ask + StopLevel;
                                      LowerStopLevel = Bid - StopLevel;
                                      
                                      
                                      if(StopLoss > 0) BuyStopLoss   = OpenPrice - (StopLoss * pt);
                  if(TakeProfit > 0)BuyTakeProfit = OpenPrice + (TakeProfit * pt);
                                      
                                      if(BuyStopLoss > 0 && BuyStopLoss > LowerStopLevel) 
                                              {                                 
                                                    BuyStopLoss = LowerStopLevel - MinStop*pt;
                                              }
                                      
                                      if(BuyTakeProfit > 0 && BuyTakeProfit < UpperStopLevel) 
                                              {
                                                     BuyTakeProfit = UpperStopLevel + MinStop*pt;
                                              }

                                      if(IsTradeContextBusy())Sleep(10);        

                  if(BuyStopLoss > 0 || BuyTakeProfit > 0) 
                     {          
                      OrderModify(Ticket,OP_BUY,BuyStopLoss,BuyTakeProfit,0);                            
                     }
                    } 
//+------------------------------------------------------------------+
void AddLimitsSell()
                  {
                  OrderSelect(SellTicket,SELECT_BY_TICKET);                 
                  OpenPrice = OrderOpenPrice();
                  StopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
                                      RefreshRates();   
                                      UpperStopLevel = Ask + StopLevel;
                                      LowerStopLevel = Bid - StopLevel;
                                      
                                      
                                      if(StopLoss > 0) SellStopLoss = OpenPrice + (StopLoss*pt);
                                      if(TakeProfit > 0) SellTakeProfit = OpenPrice - (TakeProfit*pt);
                                    
                                      if(SellStopLoss > 0 && SellStopLoss < UpperStopLevel) 
                                              {                                 
                                                    SellStopLoss = UpperStopLevel + MinStop*pt;
                                              }
                                      if(SellTakeProfit> 0 && SellTakeProfit > LowerStopLevel) 
                                              {
                                                    SellTakeProfit = LowerStopLevel - MinStop*pt;
                                              }
                                            
                                      if(IsTradeContextBusy()) Sleep(10);       

                  if(SellStopLoss > 0 || SellTakeProfit > 0) 
                    {           
                      OrderModify(Ticket,OP_SELL,SellStopLoss,SellTakeProfit,0);
                    }                    
                   }  


 

Missing Report file