mt5.last_error() in MetaTrader5 Python: find out why the last call failed
Returns the code and description of the last error the MetaTrader5 package recorded. Call it right after a function returns None or False.
Signature
mt5.last_error() What it does
Most functions in the package do not raise exceptions. They return None or False, and last_error() tells you what went wrong.
The codes are the package's own result codes: small negative numbers for call problems, and numbers from -10000 down for problems with the link to the terminal. A code of 1 means the last call worked.
What it returns
- A tuple
(code, description): an integer and a short English text.
Example
import MetaTrader5 as mt5
if not mt5.initialize():
raise SystemExit(mt5.last_error())
rates = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_H1, 0, 100)
if rates is None:
code, text = mt5.last_error()
print(f"no bars: {code} {text}")
mt5.shutdown() Common mistakes
- Read it straight away. The next call overwrites it, even a call that works.
order_send()is different: when it returns a result, the trade outcome is inresult.retcode, a 10000-range code.last_error()only matters whenorder_send()returnsNone.- Codes from -10000 down mean the link to the terminal broke, not that your request was wrong. After an order, that means the outcome is unknown until you look.
The same with Tickwire on Linux
The package needs a Windows terminal on the same machine. Tickwire runs the terminal for you and gives you a REST API, so the code below runs on Linux, macOS or a server.
Tickwire answers every failure with one JSON shape, {"error": ..., "message": ...}, and a trade reply carries numericCode and stringCode. You never need a separate call to learn why something failed.
Every code is explained in the MetaTrader error codes library, including the Python package codes.
Related functions
- mt5.initialize() in MetaTrader5 Python: connect Python to the terminal
- mt5.order_send() in MetaTrader5 Python: place, change or close a trade
- mt5.order_check() in MetaTrader5 Python: test an order before you send it
Related error codes
- MT5 Python error -1: Generic failure (RES_E_FAIL)
- MT5 Python error -2: Invalid parameters (RES_E_INVALID_PARAMS)
- MT5 Python error -4: Not found (RES_E_NOT_FOUND)
- MT5 Python error -6: Authorization failed (RES_E_AUTH_FAILED)
- MT5 Python error -10001: IPC send failed (RES_E_INTERNAL_FAIL_SEND)
- MT5 Python error -10002: IPC receive failed (RES_E_INTERNAL_FAIL_RECEIVE)
- MT5 Python error -10004: No IPC connection (RES_E_INTERNAL_FAIL_CONNECT)
- MT5 Python error -10005: IPC timeout (RES_E_INTERNAL_FAIL_TIMEOUT)
MT5 from Python, on any machine
One REST API for MT4 and MT5, with idempotent orders and an audit log. Read the MT5 Python API page or the quickstart.