As others mentioned, first you need to declare ticket
outside the if()
statement. If you want to close the order later, when it's in profit, you can't do it straight inside the else{...}
block - the price cannot be lower than pricepoint
and higher than pricepoint
at the same time.
Since your EA
will run with each tick, the variable ticket
will contain your new ticket number only for one cycle. If that's what you want your code would look like this:
double pricepoint = 1.36900;
int ticket = -1;
// buy condition is met
if (Bid < pricepoint)
{
// you should consider using Symbol() to get the chart symbol
ticket = OrderSend("EURUSD", OP_BUY, 0.01, Ask, 0, 0, 0, "My 1st Order!");
if (ticket < 0)
{
Print("OrderSend failed with error #", GetLastError());
}
else
Print("OrderSend placed successfully");
}
// ... later in code
// if you want to close specifically the ticket that was opened in the same tick cycle
if (ticket > 0)
{
if (OrderSelect(ticket, SELECT_BY_TICKET) == true)
{
// use OrderTicket(), OrderLots() and other Order functions to get the ticket properties
OrderClose(OrderTicket(), OrderLots(), Bid, 0, clrNONE);
}
else
Print("OrderSelect returned the error of ",GetLastError());
}
I don't recommend working with tickets this way though. It will take some time before your orders are in profit (if ever). You can loop through all open tickets and close those that are in profit like this:
for (int i = 0; i < OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS) == true)
{
// we only care about opened market orders, not pendings
if (OrderType() > OP_SELL)
continue;
// we only want to close orders that are in profit
if (OrderProfit() < 0)
continue;
if (OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0, clrNONE) == false)
Print("OrderClose returned the error of ",GetLastError());
// we need to adjust the control variable for the order we just closed
else
i--;
}
else
Print("OrderSelect returned the error of ",GetLastError());
}
MQL4
. Kindly post your code-snippets at least with the function header and global-scope declarations --- ref.: >>> stackoverflow.com/a/36240564/3666197 Next, you might have already noticed on your own, thatOrderClose( ... );;
line is syntactically wrong. For a real trading strategy, there are some more steps to be added to a fully fledged[ EA ]
code, so feel free to ask more. – user3666197