Warm tip: This article is reproduced from serverfault.com, please click

OrderClose not working in MQL4 without proper error feedback

发布于 2021-02-22 22:59:03

So I have this EA that should close 2 trades together under certain conditions. Sometimes it closes only 1/2, sometimes it closes both smoothly. I cannot really pinpoint the times it closes only one and detect a pattern so I can spot the logical error.

P.S.: Obviously the trades are from different pairs running from an EA within 1 chart/pair.

The error message is this: invalid ticket for OrderClose function

But the trade clearly exists, and i make sure I have it within the int as every time I restart the EA, if trade is already open (detected by comment) it has a message like that: "Buy trade: [ticket number], recognised." So I know for fact that it is recognised and within the proper int to be used. Any ideas about the error's source?

OrderClose(TicketA,LotSize,iClose(NULL,0,0),Slippage,clrGray);
OrderClose(TicketB,LotSize,iClose(SymbolB,0,0),Slippage,clrGray);

Will this fix this? I mean... it will be errored out 2/4 close orders... but I don't really care about how beautiful it looks.

OrderClose(TicketA,LotSize,Ask,Slippage,clrGray);
OrderClose(TicketB,LotSize,Bid,Slippage,clrGray);
OrderClose(TicketA,LotSize,Ask,Slippage,clrGray);
OrderClose(TicketB,LotSize,Ask,Slippage,clrGray);
Questioner
Pantelis Pap.
Viewed
0
tomgny 2021-02-24 22:31:53

Make sure that you didn't override TicketA or TicketB variable somewhere.

You can use OrderLots() function instead of using LotSize, especially when this value is changing during EA process. Additionally, by checking the OrderType(), you will avoid a mistake at the closing price.

Example:

if(yourCloseCondition){
    if(OrderSelect(ticket, SELECT_BY_TICKET)){
        if(OrderType() == OP_BUY){
            if(OrderClose(ticket, OrderLots(), Bid, 0)){
                //Print("success");
            }
        }
        if(OrderType() == OP_SELL){
            if(OrderClose(ticket, OrderLots(), Ask, 0)){
                //Print("success");
            }
        }
    }
}

Also check docs: OrderClose() and OrderType().

Update:

For different pairs running within 1 chart use close price from MarketInfo

Example:

MarketInfo("EURUSD",MODE_BID);

Check MarketInfo().