# Problem with break

105

Hi,

I have problem with break. I'd like exit the loop through all orders after open one trade, but break doesn't work. I used loop because I was going to open different currencies. I used function call to trade individual currency.  Has anyone any suggestion?

```for (int i=0;i<=OrdersTotal();i++)
{
if (OrderSymbol()=="EURUSD")break;

if (A<B){sell}

}```
2232

Encode subsequent "if" statements within a block, otherwise they will execute outside of the initial "if".

It may be wiser to use the Symbol() function or _Symbol instead of "EURUSD" so that the code can adjust to whatever symbol the chart is using instead of a fixed name that may not be valid on another broker or account type.

Also work backwards over the list of Orders, in order for the code to be more robust (see the many posts on the forum about this).

```for( int i=OrdersTotal()-1; i>=0; i-- )
{
{
if( OrderSymbol()==_Symbol ) break;
}
}```
105

Thank you. I read posts on a forum.

1. if I use decrementation it doesn't work. Any position can be open.

2. if I use incrementation (like below), system opens as many possible trades (the same as I wrote first).

```for (int i=0;i<=OrdersTotal();i++)
{
{
if (OrderSymbol()=="EURUSD")break;
}
if (A<B){sell}

}```
2232

It "has" to work! You just have to adjust your code to take into consideration that you are looking at the orders from last to first.

Since the code you supplied is only a "snippet", I am not able to tell you where the code logic is malfunctioning. You will have to provide a larger scope of the code in order to provide a more complete answer.

Also remember, that you have to also check for the Magic Number, Order Type as well as the Symbol. Checking just the Symbol is not sufficient.

15107

kot_filemon: I have problem with break. I'd like exit the loop through all orders after open one trade, but break doesn't work.
```for (int i=0;i<=OrdersTotal();i++)
{
Print(OrderSymbol()," vs EURUSD");
if (OrderSymbol()=="EURUSD")break;

if (A<B){sell}
}
}
Print("loop exit");```
1. "Doesn't work" is meaningless - just like saying the car doesn't work. Doesn't start, won't go in gear, no electrical, missing the key, flat tires - meaningless. There are no mind readers here.
2. Add the changes and run it and prove to yourself that is works just fine.
3. OrderSelect(OrdersTotal() will always fail. Thus you must bracket.
4. Don't hard code symbols If your chart isn't exactly "EURUSD" then it can't work. Broker's use a variety of naming patterns: EURUSD, EURUSDm, EURUSDi, "EURUSD.", "EURUSD..", "EUR.USD", "EUR/USD", "EURUSD.stp", EURUSDct, "EURUSD.G", "EURUSD+", and EURUSDpro at least. Don't hard code things; just use the predefined _Symbol.
105

Can you explain me point 3? Why OrderSelect () with conditions k<=OrdersTotal() will always fail? I tried with k<OrdersTotal() or k!=OrdersTotal() before.

I changed my code according your suggestion WHRoeder and nothing, any position open.  Appeared error 4051 and info "loop exit", but didn't appear info Print(OrderSymbol()," Symbol").

To FMIC - if I use decrementation appear arror 4105

In a book about C language there is info the break allow leave a loop in any time (after 4th loop break out from the loop):

for (int a=1; a!=9; ++a)

{

if (a==5) break;

//do something

}

Moderator
10064

If OrdersTotal()==1, the single order will occupy position 0

So trying to select an Order at position 1 will fail because it doesn't exist.

2232

@kot_filemon: In order to explain things in more detail, you will have to present a more complete copy of your code. It is not possible for us to "read your mind" in order to tell you where the error is.

1. Decrementing is the correct way to it in order to make sure that you never run into problems when orders are closed.
2. When you run into errors, look them up in the help so that you know what they mean. Error 4051 is "Invalid function parameter value" and Error 4105 is "No order selected".
3. If "OrderHistory()" gives you a value of 4 for example, then the index positions are 0,1,2,3 (but not 4). Therefore your loop must never include that value. That is what "WHRoeder" tried to explain to you in "Point 3".

Again, if you want our help in order to fix you code, then show us your real code, not just example snippets which don't real help much understand the problem. You don't have to show the entire EA, just that section of the code.

105

```extern int Ticket;

int start()
{

eurusd();

return(0)
}

void eurusd ()

{

int MagicNumber=OrderMagicNumber();

double A=iClose("EURUSD",PERIOD_M5,1);
double B=iClose("EURUSD",PERIOD_M5,2);

//   for (int k=OrdersTotal()-1;k>=0;k--)
for (int k=1;k<=OrdersTotal();k++)
{
{

Print(OrderSymbol()," vs EURUSD");

if (OrderSymbol()== Symbol() )break;

if ( A>B )
{
RefreshRates();

if (Ticket>0)
{Print("Order placed #",MagicNumber);}
else {Print("OrderSend failed,error#",GetLastError());}

}

if ( A<B)
{
RefreshRates();

Ticket=OrderSend("EURUSD",OP_SELL,0.01,Bid,1,0,0,"eu",MagicNumber);

if (Ticket>0)
{Print("Order placed #",MagicNumber);}
else {Print("OrderSend failed,error#",GetLastError());}
}

}

}
Print("loop exit");

for (int j=OrdersTotal()-1;j>=0;j--)
{

if (OrderSymbol()=="EURUSD")
{
if (OrderType()==OP_BUY && A<B ) {bool ans=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),1);}
if (OrderType()==OP_SELL && A>B) { ans=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),1);}
}
}

Print("error==",GetLastError());

}```

I read what WH and GumRai wrote. I looked into manual and thought about it. This is the loop for open an order.

2232

1. Don't code for the old compiler syntax. Use the proper and strict way of coding for the new MQL4+ Syntax
2. Don't use literal strings for the symbol, as they are different depending on account type and broker.
3. Where possible use NULL for the symbol so as to assume the Chart Symbol automatically.
4. The "OrderMagicNumber()" returns the magic number of an existing and selected order. It does not generate a magic number.
5. The Ticket Number can never be a user parameter ("extern" or "input"). It is generated by the system when an order is created.
6. Unless the strategy is a Multi-time-frame one, use the default chart's time-frame arrays and don't explicitly define it.
7. If you are using only previous bars for detecting the change, then don't execute on every Tick and instead detect when a New Bar is generated.

There are actually many other logic errors, so here is my version of the code that should help you on your way (please note, that "break" was not used here because it does not apply to this logic):

PS! I edited this post several times, so this final version of the code is different from the initial post!

```#property strict

extern int
MyEAMagicNumber = 123456789,
MySlippage = 1;
extern double
MyLots = 0.01;
extern string
MyOrderComment = "TEST";

int OnInit()
{
return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
}

void OnTick()
{
static datetime LastTimestamp = NULL;

// Detect New Bar
if( Time[0] != LastTimestamp )
{
LastTimestamp = Time[0];
ProcessBar();
}
}

void ProcessBar()
{
// Check Close Slope
double CloseSlope = Close[1] - Close[2];
if( CloseSlope > 0 ) ProcessOrders( OP_BUY, OP_SELL );
else
{
if( CloseSlope < 0 ) ProcessOrders( OP_SELL, OP_BUY );
}
}

void ProcessOrders( int TypeOpen, int TypeClose )
{
// Check Orders and Count or Close accordingly;
int ExistOpenCount = 0;
for( int i=OrdersTotal() - 1; i >= 0; i-- )
{
if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
{
if( OrderMagicNumber() == MyEAMagicNumber )
{
if( OrderSymbol() == _Symbol )
{
int TypeOrder = OrderType();

if( TypeOrder == TypeClose )
{
if( !OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), MySlippage ) )
Print("Erro closing order: ", GetLastError() );
}
else
{
if( TypeOrder == TypeOpen ) ExistOpenCount++;
}
}
}
}
}

// Place Order if None exist in the same direction
if( ExistOpenCount < 1 )
{
RefreshRates();
double PriceOpen = ( TypeOpen ==  OP_BUY ) ? Ask : Bid;

int OrderID =
OrderSend( _Symbol, TypeOpen, MyLots, PriceOpen,
MySlippage, 0, 0, MyOrderComment, MyEAMagicNumber );

if( OrderID > 0 )
Print( "Order Placed: ", OrderID );
else
Print( "Order Failed! Error: ", GetLastError() );
}
}```
105

thank you.