![MQL5 - Language of trade strategies built-in the MetaTrader 5 client terminal](https://c.mql5.com/i/registerlandings/logo-2.png)
You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
EAs must be coded to recover. If the power fails, OS crashes, terminal or chart is accidentally closed, on the next tick, any static/global ticket variables will have been lost. You will have an open order but don't know it, so the EA will never try to close it, trail SL, etc. How are you going to recover?
Use a OrderSelect / Position select loop on the first tick, or persistent storage (GV+flush or files) of ticket numbers required.
It did work when I did select the order and tried closing it.
I didn't noticed that the ticket was destroyed in the first loop as William pointed out. and probably should have used OrdersTotal()>0 instead.
As Daniel points to the subject and general process:
Get OrdersTotal()
then make your aka for loop to count the order,
Select the type of order using the flag noted in the OrderSelect() definitions in the manual. aka OrderSelect(), then by flag, then by mode: https://docs.mql4.com/trading/orderselect
Read this and search for some examples of other EA's that open and close orders. You will see the similar types of loops that OrderSelect()
https://www.cashbackforex.com/article/retrieving-order-information-with-orderselect
Notice OrderSelect() is a bool type either true or false
Other examples in the forums.
https://www.mql5.com/en/forum/127124
You have to just keep reading and reading mostly but in time you will fully understand how to Open and Close Orders and how to Select an order for processing either to close or modify it.
Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number/symbol filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum (2013)
PositionClose is not working - MQL5 programming forum (2020)
MagicNumber: "Magic" Identifier of the Order - MQL4 Articles (2006)
Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles (2011)
Limit one open buy/sell position at a time - General - MQL5 programming forum (2022)
You need one Magic Number for each symbol/timeframe/strategy.
Trade current timeframe, one strategy, and filter by symbol requires one MN.
If trading multiple timeframes, and filter by symbol requires use a range of MN (base plus timeframe).
Why are MT5 ENUM_TIMEFRAMES strange? - General - MQL5 programming forum - Page 2 #11 (2020)