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 in result.retcode, a 10000-range code. last_error() only matters when order_send() returns None.
  • 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 error codes

All MetaTrader5 Python functions

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.