# EA not close all open psition with magic number

Hi,

I note a strange behavior with my EA. Sometimes it closes the opened positions but without  magic number.

I tried to figure out why but I can't find the reason

I'm using the following code to open trade

```trade.SetExpertMagicNumber(magic);
// ....
// ....
}```

and this one to make some calculation

```   datetime today     = TimeCurrent() ;
datetime yesterday = TimeCurrent() - (60 * 60 * 24);
HistorySelect(0,TimeCurrent());
for (int l = HistoryDealsTotal()-1; l >= 0; l--) {
if(deal.SelectByIndex(l)) {
if ( deal.Entry()==DEAL_ENTRY_OUT && deal.Symbol() == Symbol() ) {
if ( deal.Magic() == magic) {
double orderProfit = (deal.Profit() + deal.Swap() + deal.Commission());
if( TimeDay(deal.Time()) == TimeDay(today) &&
TimeMonth(deal.Time()) == TimeMonth(today) &&
TimeYear (deal.Time()) == TimeYear(today) ) {
profitToday += orderProfit;
}
if( TimeDay  (deal.Time()) == TimeDay(yesterday) &&
TimeMonth(deal.Time()) == TimeMonth(yesterday) &&
TimeYear (deal.Time()) == TimeYear(yesterday) ) {
profitYesterday += orderProfit;
}
}
}
}
}```

I use the following code to close my orders

```void CloseAllOrders() {
for (int m = PositionsTotal()-1; m >= 0; m--) {
if ( position.SelectByIndex(m)) {
if(   position.Symbol() == Symbol()
&& position.Magic() == magic) {

}
}
}
}```

When I use debugger some deal have magic number equal '0' but I don't closed them manually. They have been closed by the EA.
So I don't understand why

Someone can help me ?

Files:
Capture.PNG  32 kb

Do you set the 'Magic number' for an object of the CTrade trade class? ( SetExpertMagicNumber )
Documentation on MQL5: Standard Library / Trade Classes / CTrade / SetExpertMagicNumber
• www.mql5.com

Do you set the 'Magic number' for an object of the CTrade trade class? ( SetExpertMagicNumber )

Yes. Look at the first bloc code I posted

michel picard :

Yes. Look at the first bloc code I posted

You are initializing to ' magic ' and the positions are trying to sort by ' magicbuy '.