PythonMetaTrader5
¶
A safe, typed trading layer over the official
MetaTrader5 Python package, built
for bots where a trading call must never hang, never retry blindly, and
never fail silently.
Get started API reference Architecture
-
Every call returns
Requotes and missing quotes are retried a bounded number of times with a fresh quote. Everything else comes back at once as a typed error.
-
No double fills
Timeouts and lost connections are never retried: the order may already be live. They come back as
OUTCOME_UNKNOWN. -
No silent defaults
Values MT5 would quietly read as something else, such as
sl=0orticket=0, are refused before anything is sent. -
Typed results
Ok(receipt)orErr(TradeError)with anErrorKindinstead of magic numbers, checked by mypy and your editor. -
Close-all touches only your bot
close_positions()andcancel_pending_orders()act on the trader's own magic number unless told otherwise. -
Built to be reasoned about
Clean Architecture with ports and adapters, and every non-obvious choice recorded as a decision record.
At a glance¶
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
Before trading real money
Run your bot on a demo account first, give it its own magic, and treat
OUTCOME_UNKNOWN as "maybe filled". The full checklist is in the
user guide.