MT5 Python initialize()
Connects the Python package to a MetaTrader 5 terminal on the same computer, starting the terminal if it is not running, and can log in to a trading account in the same call.
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 shows three forms of the call: with nothing, with a path alone, and with a path and account details. Its example logs in with an account number and a password typed into the code. The sample here does not: it lets the terminal use the account it already has saved.
Signature
The 3 forms of the call on the vendor's page, with the vendor's comments taken out.
initialize()
initialize( path )
initialize( path, login=LOGIN, password="PASSWORD", server="SERVER", timeout=TIMEOUT, portable=False )
Arguments
| Name | Type | Description |
|---|---|---|
| path | Not stated | Where the terminal's executable is: the page names metatrader.exe or metatrader64.exe. Given first and without a name. Left out, the package looks for the terminal itself. |
| login | Not stated | The trading account number. Left out, the terminal's last used account is used. |
| password | Not stated | The trading account's password. Left out, the password the terminal has saved for that account is used, so it need not appear in code at all. |
| server | Not stated | The trade server's name, as the terminal shows it. Left out, the server saved for that account is used. |
| timeout | Not stated | How long to wait for the connection, in milliseconds. The page gives the default as 60,000, which is 60 seconds. |
| portable | Not stated | Whether to start the terminal in portable mode. The page gives the default as False. |
Return value
- Type
- bool
- What comes back
- True when the connection to the terminal is made, False otherwise. The page's own example reads last_error() after a False.
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 MetaTrader5 as mt5
# No account details in code: the terminal uses the account it already has saved.
if not mt5.initialize():
raise SystemExit(f"initialize() failed: {mt5.last_error()}")
print(mt5.version())
mt5.shutdown()