Skip to content

PythonMetaTrader5 Code Coverage

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

pip install PythonMetaTrader5
  • 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.

    Retries

  • No double fills


    Timeouts and lost connections are never retried: the order may already be live. They come back as OUTCOME_UNKNOWN.

    Error kinds

  • No silent defaults


    Values MT5 would quietly read as something else, such as sl=0 or ticket=0, are refused before anything is sent.

    ADR 0008

  • Typed results


    Ok(receipt) or Err(TradeError) with an ErrorKind instead of magic numbers, checked by mypy and your editor.

    Results and errors

  • Close-all touches only your bot


    close_positions() and cancel_pending_orders() act on the trader's own magic number unless told otherwise.

    Magic numbers

  • Built to be reasoned about


    Clean Architecture with ports and adapters, and every non-obvious choice recorded as a decision record.

    Decisions

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.