MT5 Python login()
Switches the connected terminal to a trading account, by account number, with the password and server optional.
Risk warning: CFDs and spread bets are complex instruments and come with a high risk of losing money rapidly due to leverage. You can lose money on these products, and each provider publishes its own loss figure under FCA rules. You should consider whether you understand how they work and whether you can afford to take the high risk of losing your money. Automated and API trading can amplify losses through bugs, connectivity failures and runaway orders.
This is a Python function, not an HTTP endpoint. It has no method, no path and no address to send a request to: the package talks to a MetaTrader 5 terminal running on the same computer.
The page's example types a password into the code. The sample here reads it from an environment variable instead, and the page says the password can be left out altogether where the terminal has it saved.
Signature
The form of the call on the vendor's page, with the vendor's comments taken out.
login( login, password="PASSWORD", server="SERVER", timeout=TIMEOUT )
Arguments
| Name | Type | Description |
|---|---|---|
| loginrequired | Not stated | The trading account number. Given first and without a name. |
| password | Not stated | The account's password. Left out, the terminal uses the password it has saved for the account. |
| server | Not stated | The trade server's name. Left out, the last server used is applied. |
| timeout | Not stated | How long to wait, in milliseconds. The default is given as 60,000. The page says that when the time runs out the call is ended and an exception is raised. |
Return value
- Type
- bool
- What comes back
- True when the terminal connects to the trading account, False otherwise.
Sample
Written by this site from the signature and arguments recorded on this page. It has not been run against a terminal, a server or an account, and the values in it are placeholders. No credential is typed into it: where one is needed it is read from an environment variable on your own machine. Nothing is entered on this site.
import os
import MetaTrader5 as mt5
if not mt5.initialize():
raise SystemExit(f"initialize() failed: {mt5.last_error()}")
account = int(os.environ["MT5_LOGIN"])
# The password is read from your own environment, never typed into the file.
if mt5.login(account, password=os.environ["MT5_PASSWORD"], server=os.environ["MT5_SERVER"]):
print(mt5.account_info())
else:
print("login() failed:", mt5.last_error())
mt5.shutdown()