How to close the last trade EXACTLY at the open of the next trade?

 
So I have a system where I open a new trade every 10 pips and close out the last trade. 

The last trade is also modified to set the stop loss to 10 pips.

Currently, I have a function that does this:

void TradeCloser(){ //start

            int total = OrdersTotal();
            if (total > 0)
            {
            for(int cnt=0;cnt<total;cnt++)
            {
               if(OrderSelect(cnt,SELECT_BY_POS))
               {
            
                     if ((Next_BUY_Order_Comment == "M1") && (OrderType() == OP_BUY)) // compare the commenting
               {
                  // do what you want.
               
                  OrderClose(Close1B(),Order0_Lot,MarketInfo(OrderSymbol(),MODE_BID),2,Red);

               }
                     if ((Next_BUY_Order_Comment == "M2") && (OrderType() == OP_BUY)) // compare the commenting
               {
                  // do what you want.
                  OrderClose(Close2B(),Order1_Lot,MarketInfo(OrderSymbol(),MODE_BID),2,Red);
               }
                     if ((Next_BUY_Order_Comment == "M3") && (OrderType() == OP_BUY)) // compare the commenting
               {
                  // do what you want.
                  OrderClose(Close3B(),Order2_Lot,MarketInfo(OrderSymbol(),MODE_BID),2,Red);
               }
                     if ((Next_BUY_Order_Comment == "M4") && (OrderType() == OP_BUY)) // compare the commenting
               {
                  // do what you want.
                  OrderClose(Close4B(),Order3_Lot,MarketInfo(OrderSymbol(),MODE_BID),2,Red);
               }
               
                     if ((Next_BUY_Order_Comment == "M5") && (OrderType() == OP_BUY)) // compare the commenting
               {
                  // do what you want.
                  OrderModify(Close5B(), OrderOpenPrice(), OrderOpenPrice()-sala, OrderTakeProfit(), OrderExpiration(), CLR_NONE);
                  OrderClose(Close5B(),Order4_Lot,MarketInfo(OrderSymbol(),MODE_BID),2,Red);
               }
               
               if ((Next_SELL_Order_Comment == "M1") && (OrderType() == OP_SELL)) // compare the commenting
               {
                  // do what you want.
                  OrderClose(Close1S(),Order0_Lot,MarketInfo(OrderSymbol(),MODE_ASK),2,Blue);

               }
                     if ((Next_SELL_Order_Comment == "M2") && (OrderType() == OP_SELL)) // compare the commenting
               {
                  // do what you want.
                  OrderClose(Close2S(),Order1_Lot,MarketInfo(OrderSymbol(),MODE_ASK),2,Blue);
               }
                     if ((Next_SELL_Order_Comment == "M3") && (OrderType() == OP_SELL)) // compare the commenting
               {
                  // do what you want.
                  OrderClose(Close3S(),Order2_Lot,MarketInfo(OrderSymbol(),MODE_ASK),2,Blue);
               }
                     if ((Next_SELL_Order_Comment == "M4") && (OrderType() == OP_SELL)) // compare the commenting
               {
                  // do what you want.
                  OrderClose(Close4S(),Order3_Lot,MarketInfo(OrderSymbol(),MODE_ASK),2,Blue);
               }
               
                     if ((Next_SELL_Order_Comment == "M5") && (OrderType() == OP_SELL)) // compare the commenting
               {
                  // do what you want.
		  OrderModify(Close5S(), OrderOpenPrice(), OrderOpenPrice()+sala, OrderTakeProfit(), OrderExpiration(), CLR_NONE);
                  OrderClose(Close5S(),Order4_Lot,MarketInfo(OrderSymbol(),MODE_ASK),2,Blue);
               }
            
         }
      }
   }



//end
}
int Close1B()
{

    int      Close1B = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_BUY) && (OrderComment()== "First" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close1B = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close1B);
  }

int Close2B()
{

    int      Close2B = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_BUY) && (OrderComment()== "M1" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close2B = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close2B);
  }

int Close3B()
{

    int      Close3B = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_BUY) && (OrderComment()== "M2" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close3B = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close3B);
  }

int Close4B()
{

    int      Close4B = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_BUY) && (OrderComment()== "M3" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close4B = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close4B);
  }
  
int Close5B()
{

    int      Close5B = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_BUY) && (OrderComment()== "M4" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close5B = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close5B);
  }
  
int Close6B()
{

    int      Close6B = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_BUY) && (OrderComment()== "M5" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close6B = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close6B);
  }

int Close1S()
{

    int      Close1S = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_SELL) && (OrderComment()== "First" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close1S = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close1S);
  }

int Close2S()
{

    int      Close2S = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_SELL) && (OrderComment()== "M1" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close2S = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close2S);
  }

int Close3S()
{

    int      Close3S = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_SELL) && (OrderComment()== "M2" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close3S = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close3S);
  }

int Close4S()
{

    int      Close4S = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_SELL) && (OrderComment()== "M3" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close4S = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close4S);
  }
  
int Close5S()
{

    int      Close5S = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_SELL) && (OrderComment()== "M4" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close5S = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close5S);
  }
  
int Close6S()
{

    int      Close6S = -1;                  // None open.
 for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
     OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         //if( ! OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue;
         if( OrderSymbol() == Symbol()         
            && ( OrderType() == OP_SELL) && (OrderComment()== "M5" ))    

                 Alert("Job Ticket:" ,OrderTicket(), " found");
                 Close6S = OrderTicket();
                 RefreshRates();

                }
//----
   return(Close6S);
  }  


What I am doing is first closing the trade (by running this function) before opening the next trade by doing OpenTrade(Symbol(), OP_BUY, Next_BUY_Lot_Size); or OpenTrade(Symbol(), OP_SELL, Next_SELL_Lot_Size);

Example 

TradeCloser();
OpenTrade(Symbol(), OP_BUY, Next_BUY_Lot_Size);


However, the trade does not close EXACTLY at the open of the next trade. It happens before but at a different price which causes me uncessecary and extra losses.


Would OrderCloseBy() do the trick here? Example of what I am thinking: OrderCloseBy(Close1B,Close2B, CLR_NONE);

Can you guys spot the mistake? I've been losing sleep over this for some time now.

 
marth tanaka:
So I have a system where I open a new trade every 10 pips and close out the last trade. 

The last trade is also modified to set the stop loss to 10 pips.

Currently, I have a function that does this:



What I am doing is first closing the trade (by running this function) before opening the next trade by doing OpenTrade(Symbol(), OP_BUY, Next_BUY_Lot_Size); or OpenTrade(Symbol(), OP_SELL, Next_SELL_Lot_Size);

Example 


However, the trade does not close EXACTLY at the open of the next trade. It happens before but at a different price which causes me uncessecary and extra losses.


Would OrderCloseBy() do the trick here? Example of what I am thinking: OrderCloseBy(Close1B,Close2B, CLR_NONE);

Can you guys spot the mistake? I've been losing sleep over this for some time now.

It's very unclear what you are trying to accomplish here, and your code is difficult to read since it doesn't follow any indentation convention and it's incomplete. If you don't know how to indent your code you can always have metaeditor do it for you by selecting Tools->Styler. 


In the future you should clean up your code and be more specific on what you are trying to accomplish. 


So I have a system where I open a new trade every 10 pips and close out the last trade. 

What does this even mean? You are reversing @ ever 10 pips? You are going all the same direction? Which is the "last trade"? Can you see how ambiguous this all is?
 
nicholi shen:

It's very unclear what you are trying to accomplish here, and your code is difficult to read since it doesn't follow any indentation convention and it's incomplete. If you don't know how to indent your code you can always have metaeditor do it for you by selecting Tools->Styler. 


In the future you should clean up your code and be more specific on what you are trying to accomplish. 


What does this even mean? You are reversing @ ever 10 pips? You are going all the same direction? Which is the "last trade"? Can you see how ambiguous this all is?
For example, take a look at this ea attached. In this ea, I open a trade and if the trade goes the wrong direction (against price) I open another trade with the second trade being at a distance of 3 pips from the first trade with double lots and so forth.

However the problem is that when it closes a trade and opens the next one, it does not close and open at the exact same price. There is a small difference. The image attached is a visual example of the problem I am trying to explain.
How could I fix this so that it opens and closes at the exact same price? Using a pending order? If so, how would I fit in a pending order here?
 
marth tanaka:
For example, take a look at this ea attached. In this ea, I open a trade and if the trade goes the wrong direction (against price) I open another trade with the second trade being at a distance of 3 pips from the first trade with double lots and so forth.

However the problem is that when it closes a trade and opens the next one, it does not close and open at the exact same price. There is a small difference. The image attached is a visual example of the problem I am trying to explain.
How could I fix this so that it opens and closes at the exact same price? Using a pending order? If so, how would I fit in a pending order here?
A SELL close at Ask and open at Bid. You can't have them at the same price so simply. You need to place a SELL STOP at the close price of your previous order, it the broker allow it. And you could have slippage.
 
Alain Verleyen:
A SELL close at Ask and open at Bid. You can have them at the same price so simply. You need to place a SELL STOP at the close price of your previous order, it the broker allow it. And you could have slippage.
I tried to open and close a sell at both the ask price and vice versa, however, it did not work and threw error 138. I dont belive you can sell at the wrong price (Ask). 



Your idea of a SELL/BUY STOP looks promising. Im a little confused/newbie so could you provide an example? particularily in the example ea attached. Thank you for your time.
 
marth tanaka:
I tried to open and close a sell at both the ask price and vice versa, however, it did not work and threw error 138. I dont belive you can sell at the wrong price (Ask). 
Sorry I made a type, I mean "you can't have them...". A market sell trade is always open at Bid price, not possible to change that.
Your idea of a SELL/BUY STOP looks promising. Im a little confused/newbie so could you provide an example? particularily in the example ea attached. Thank you for your time.

If you want coding help, please provide your attempt.

 
Alain Verleyen:
Sorry I made a type, I mean "you can't have them...". A market sell trade is always open at Bid price, not possible to change that.

If you want coding help, please provide your attempt.

I did make multiple attempts. My first one was the first post in this forum. Maybe you missed that. I then posted the sample ea because it is a dumbed down/easier to edit version of my 2000 lines of code ea. I feel like if someone could help code a buy/sell stop order into the sample ea, I could learn from your example and code it into my main ea.
 

There is only one way to reverse a position "at the exact time" and that is to place an order for double the volume of the open position in the opposite direction. For example to reverse a 1 lot SELL you'd need to place an order for a 2 lot BUY, and your resulting position would net 1 lot long. With hedging accounts you'll need to use closeby to avoid double fees for managing your position this way. The command function is OrderCloseBy and here is an example of how to use it. 

bool multiple_closeby(string symbol, int magic=0)
{
   for(int i=OrdersTotal()-1; i>=1; --i) {
      if(position_select(i, symbol, magic)) {
         int ticket = OrderTicket();
         int type = OrderType();
         for(int j=i-1; j>=0; --j) {
            if(position_select(j, symbol, magic) && OrderType() != type) {
               if(OrderCloseBy(OrderTicket(), ticket))
                  return multiple_closeby(symbol, magic);
               else
                  return false;
            }
         }
      }
   }
   return true;
}

bool position_select(int index, string symbol, int magic)
{
   return (
      OrderSelect(index, SELECT_BY_POS)
      && OrderSymbol() == symbol
      && OrderMagicNumber() == magic
      && OrderType() < 2
   );
}


 

 
nicholi shen:

There is only one way to reverse a position "at the exact time" and that is to place an order for double the volume of the open position in the opposite direction. For example to reverse a 1 lot SELL you'd need to place an order for a 2 lot BUY, and your resulting position would net 1 lot long. With hedging accounts you'll need to use closeby to avoid double fees for managing your position this way. The command function is OrderCloseBy and here is an example of how to use it. 


 

I am not reversing a position though. when price moves against me 3 pips from my original sell, i place another sell. When price moves 3 pips against my second sell, I place another sell and so forth.


I know it is possible to close the previous sell and place a new sell exactly at the close of the last sell because I did it manually using limit orders. However, I cant get it to work in mt EA. Any more ideas guys? Feeling desperate.

 
nicholi shen:

The command function is OrderCloseBy and here is an example of how to use it. 


modified some of your code, to select highest lot first.

bool CTrade::multiple_closeby_symbol(const int magic = 0) {
   double lot = 0;
   for(int i=OrdersTotal()-1; i>0; i--){
      if(position_select(i,magic) && OrderLots()>lot) {
         int    first_ticket = OrderTicket();
         int    first_type   = OrderType();
         for(int j=i; j>=0; j--){
            if(selectTradeHedging(j,first_type,magic)) {
               bool closeorder = false;
               closeorder = OrderCloseBy(first_ticket,OrderTicket());
               if(closeorder) return multiple_closeby_symbol(magic);
               else return false;
            }
         }
         break;
      }
   }
   return true;
}

bool selectTradeHedging(int i, int masterType, int magic = 0){
   int opposite = 100;
   if(masterType==OP_BUY) opposite = OP_SELL;
   else if(masterType==OP_SELL) opposite = OP_BUY;
   
   return (
      OrderSelect(i,SELECT_BY_POS) 
      && OrderSymbol() == _Symbol 
      && OrderType()==opposite
   );
}

bool position_select(int index, int magic) {
   return (
      OrderSelect(index, SELECT_BY_POS)
      && OrderSymbol() == _Symbol;
      && OrderMagicNumber() == magic
      && OrderType() < 2
   );
}
 
If you just want to add volume to your trades in the same direction - no need to close previous trade, but just open a new one with additional volume.
Reason: