mt5.login() in MetaTrader5 Python: log in to a trading account
Logs the connected terminal in to a trading account, or switches it to another one. Returns True when the login worked and False when it did not.
Signature
mt5.login(login, password=..., server=..., timeout=...) What it does
Use login() after initialize() to move the terminal to another account without restarting it.
initialize() can log in too. Use login() when you want to keep the two steps apart, or switch accounts during a session.
Parameters
| Parameter | What it is |
|---|---|
login | The trading account number. Required. |
password | The account password. Optional: the terminal falls back to the password it saved for that account. |
server | The trade server name, as the terminal's login window shows it. Optional: the saved server is used. |
timeout | How long to wait, in milliseconds. The default is 60000. |
What it returns
Truewhen the terminal logged in to the account.Falsewhen it did not.mt5.last_error()tells you why, often an authorization failure (-6).
Example
import os
import MetaTrader5 as mt5
if not mt5.initialize():
raise SystemExit(mt5.last_error())
if mt5.login(int(os.environ["MT5_LOGIN"]),
password=os.environ["MT5_PASSWORD"],
server=os.environ["MT5_SERVER"]):
print("logged in to", mt5.account_info().login)
else:
print("login failed:", mt5.last_error())
mt5.shutdown() Common mistakes
- The server name must match the terminal's list exactly, suffix and all. A close guess fails.
- The terminal switches account for every script attached to it. If two scripts share one terminal, a
login()in one moves the other too. - Keep passwords out of the code and out of logs. Read them from the environment.
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.
On Tickwire you give the login, server and password once, when you add the account. The hosted terminal logs in and stays logged in. Your code only holds a Tickwire API key, never the broker password.
Each account has its own terminal, so working with two accounts never means switching one terminal back and forth. Read account-information on each to confirm which account you are on.
GET /users/current/accounts/{account_id}/account-informationGET /users/current/accounts/{account_id}/health
Related functions
- mt5.initialize() in MetaTrader5 Python: connect Python to the terminal
- mt5.account_info() in MetaTrader5 Python: read balance, equity and margin
- mt5.last_error() in MetaTrader5 Python: find out why the last call failed
- mt5.shutdown() in MetaTrader5 Python: close the link to the terminal
Related error codes
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.