PythonMetaTrader5
A safe, typed trading layer over the official
MetaTrader5 Python package.
Built for bots (webhook executors, signal followers) where a trading call must never hang, never retry blindly, and never fail silently:
- Every trading call returns. Requotes are retried a bounded number of times
with a fresh quote; everything else comes back immediately as a typed error.
(The deprecated
Broker.login(ToEffect=True)is the one exception: as in 2.x, it keeps trying until the login works.) - No silent defaults. Values that MT5 would quietly read as something else
are refused before sending:
sl=0("no stop"),ticket=0(possibly "no filter"),volume=True(one lot), NaN and infinities. - No double fills. Timeouts and lost connections are never auto-retried: the order may already be live.
- Typed results.
Ok(receipt)orErr(TradeError)with anErrorKind(MARKET_CLOSED,NO_MONEY,INVALID_STOPS, ...) instead of magic numbers. - Correct prices and lots. Prices snap to the symbol's tick grid, volumes are checked against min/max/step, the filling mode is chosen from the symbol.
- Magic numbers. Tag your bot's trades and close/cancel only those.
- SL/TP as prices or distances in points.
- 2.x compatible. The old
Brokerclass still works (deprecated).
One connection per process: the official package keeps a single global terminal session, so a second
connect()(or its failed login) affects the first. Run one process per account.Thread-safe within the library: every terminal call holds one process-wide lock, so a threaded webhook server can share a
Trader. The MT5 functions re-exported throughPythonMetaTrader5hold it for each single call (a pair such asorder_send+last_erroris not atomic). Calls you make to theMetaTrader5module directly bypass it.Requires Windows with a MetaTrader 5 terminal installed (the official
MetaTrader5package is Windows-only). Enable Algo Trading in the terminal.
Installation
pip install PythonMetaTrader5
Quick start
from PythonMetaTrader5 import Err, Ok, Side, Stop, connect
match connect(12345678, "password", "MetaQuotes-Demo", magic=1001):
case Err(error):
raise SystemExit(f"cannot connect: {error}")
case Ok(trader):
pass
with trader: # shuts the terminal connection down on exit
result = trader.open_position(
"EURUSD", Side.BUY, 0.10,
sl=Stop.points(1000), # 1000 points below the entry price
tp=1.12500, # a plain float is an absolute price
comment="webhook #42",
)
match result:
case Ok(receipt):
print("filled at", receipt.price, "deal", receipt.deal)
case Err(error):
print("not opened:", error.kind, error.message)
trader.close_positions("EURUSD") # only this bot's (magic 1001) positions
API
connect(login, password, server, *, path=None, timeout_ms=60000, magic=0, deviation=10, retry=None) -> Result[Trader, TradeError]
login must be a positive integer or a string of ASCII digits; True,
12345678.9 and similar values are rejected rather than coerced.
Trader method |
Returns |
|---|---|
open_position(symbol, side, volume, *, sl=None, tp=None, price=None, comment=None) |
Result[TradeReceipt, TradeError] |
place_limit_order(symbol, side, volume, price, *, sl=None, tp=None, comment=None) |
Result[TradeReceipt, TradeError] |
close_positions(symbol=None, *, ticket=None, magic=<own>, comment=None) |
Result[list[TradeReceipt], BatchFailure] |
cancel_pending_orders(symbol=None, *, magic=<own>, kind=None) |
Result[list[TradeReceipt], BatchFailure] |
positions(symbol=None, *, ticket=None, magic=None) |
Result[list[Position], TradeError] |
pending_orders(symbol=None, *, magic=None, kind=None) |
Result[list[PendingOrder], TradeError] |
shutdown() |
None |
side:Side.BUY/Side.SELL, or the strings"buy","sell","long","short".sl/tp: a float is an absolute price;Stop.points(n)is a distance ofnpoints from the entry price (Stop.at_price(p)is the explicit form). For limit orders the distance is measured from the limit price, and for a market order with an explicitpricefrom that price. A float stop that is zero, negative or not finite is rejected (INVALID_STOPS); passNonefor no stop.Stop.points()/Stop.at_price()raiseValueErrorunless the value is a positive finite number (bool and str included; a zero stop would mean "no stop" to MT5); the sign of a points distance is ignored. Akindthat is not aStopKindraisesTypeError. A stop that resolves outside the tick grid's range, or to zero or below, isINVALID_STOPSwhen the order is built. For a value that may be bad at runtime, such as an ATR that is NaN during warm-up, useStop.parse(value, StopKind.POINTS), which returnsOk(stop)/Err(INVALID_STOPS).- Amounts may be
int,float,Decimalor numpy scalars;booland strings are refused (the deprecatedBrokerstill converts numeric strings). price(market orders): send at this price once instead of the live quote.comment: at most 29 UTF-16 units: 29 characters, but characters outside the BMP, such as most emoji, count as 2 (combined emoji more). TheMetaTrader5package refuses 30 or more (measured on 5.0.6231; its docs say 31). Longer comments, and comments that are notstr, are rejected before sending, not truncated.close_positions()andcancel_pending_orders()act only on the trader's ownmagicunless you pass another one (ADR 0011);magic=Noneis still "own". To act on the whole account, manual trades included, passmagic=ANY_MAGIC. Aticketis closed whatever its magic.positions()andpending_orders()still list every magic by default.- Manual trades have magic 0, the
connect()default, so set your ownmagicfor this to protect them. Until then a close/cancel that affects magic-0 items logs a warning;magic=0passed explicitly acknowledges it. On a netting account a position keeps the magic of the deal that opened it, so merged volume cannot be told apart by magic; a defaulted close/cancel that matches nothing logs how many items with other magics it left open. - A magic must be an integer from 0 to 2**64-1 (MT5's ulong);
connect()returnsErr(INVALID_ARGUMENT)otherwise, e.g. forNone. An empty string""as symbol is rejected too. BatchFailure.errorsnames every position/order that failed (TradeError.ticket).BatchFailure.succeededholds the receipts of the ones that worked; theirorder/dealare the IDs of the closing deal, not the position ticket.ticketmust be a positive integer;0,Trueor"7"are rejected.
Errors
TradeError(kind, message, retcode=None, receipt=None, ticket=None). The
receipt carries the broker's raw answer when there was one. Retry policy:
| Server answer | What happens |
|---|---|
| market deal (entry or close): done | Ok(receipt) |
| pending order: placed or done | Ok(receipt) |
| market deal: partial fill | PARTIAL_FILL with the receipt; part of the deal exists, never re-sent |
| market deal: placed (queued, not executed) | OUTCOME_UNKNOWN with the receipt, never re-sent |
| requote, price changed, no quotes, too many requests | retried with a fresh quote, up to RetryPolicy.attempts (default 3, 0.5 s apart), then RETRIES_EXHAUSTED |
timeout, no connection, or order_send lost in IPC |
OUTCOME_UNKNOWN, never retried: check positions() first |
| anything else | the matching ErrorKind, returned at once |
| refused before sending: the terminal's symbol data cannot price an order (point 0, NaN tick size, volume step 0, ...) | BROKEN_SYMBOL_DATA, the same on every resend: escalate, don't retry. Closing still works on such symbols |
from PythonMetaTrader5 import RetryPolicy, connect
connect(..., retry=RetryPolicy(attempts=5, delay_seconds=0.2))
Logging
The library logs through the standard logging module under the
PythonMetaTrader5 logger and never configures handlers itself. Without any
logging configuration, warnings and errors still reach stderr.
Migrating from 2.x
from PythonMetaTrader5 import Broker keeps working and emits a
DeprecationWarning. from PythonMetaTrader5 import * still brings in the
MetaTrader5 functions and constants, as in 2.x. Several 2.x behaviours were unsafe and changed: see
MIGRATION.md.
Development
python -m venv .venv && .venv\Scripts\activate
pip install -e ".[dev]"
ruff check src tests scripts && ruff format --check src tests scripts
mypy
pytest --cov
tests/contract compares the unit-test fakes with the installed MetaTrader5
package and is skipped where it is not installed (anywhere but Windows).
Integration tests trade on a demo account and are skipped unless
MT5_LOGIN, MT5_PASSWORD and MT5_SERVER are set (they refuse to run on a
live account): pytest -m integration.
Architecture and decisions: docs/architecture.md, docs/adr.
License
CC BY-NC 4.0. Trading carries risk; this software comes without any warranty.
Metadata
Release files for PythonMetaTrader5 3.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pythonmetatrader5-3.0.0.tar.gz | 40.2 kB | Without provenance | Details for pythonmetatrader5-3.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pythonmetatrader5-3.0.0-py3-none-any.whl | Python 3 | none | any | Details for pythonmetatrader5-3.0.0-py3-none-any.whl |
Total release size: 86.7 kB
Release files / pythonmetatrader5-3.0.0.tar.gz
| Download URL | pythonmetatrader5-3.0.0.tar.gz |
|---|---|
| Size | 40.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d3afc1766e8502540334a012d9ce29204ac4ab767e4f142009ce64ce8b7df38a
|
|
BLAKE2b-256 checksum How to use checksums |
38e505e56d5f698d19ef08a63a9da410a60f322bfb502607d56c0310a66e370b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.15.2
|
Release files / pythonmetatrader5-3.0.0-py3-none-any.whl
| Download URL | pythonmetatrader5-3.0.0-py3-none-any.whl |
|---|---|
| Size | 46.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c70353151aeab9d74955608bf1315429ad3a9633f5e37a2bca8ebdd2fc84d1e0
|
|
BLAKE2b-256 checksum How to use checksums |
5409367c8b059343260f39852424528c8e9ad16b66b2f56a403162494af6ca85
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.15.2
|
Security for PythonMetaTrader5 3.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.