pymt5
English | 简体中文
Async Python client for MetaTrader 5 Web Terminal, using a reverse-engineered,
encrypted WebSocket binary protocol.
English documentation ·
中文文档 ·
Examples ·
Issues
Unofficial and experimental: pymt5 is not affiliated with or endorsed by
MetaQuotes. Protocol behavior can change across brokers and server builds.
Start with an authorized demo account and read the
security guide before
connecting an application.
Features
| Area |
Capabilities |
| Session |
Async context manager, bootstrap key exchange, login/logout, heartbeat, optional automatic reconnect |
| Account |
Account state, positions, pending orders, deals, and trade history |
| Market data |
Symbol metadata, historical bars, real-time ticks, and order book |
| Streaming |
Raw and typed callbacks, tick/book caches, disconnect notifications |
| Trading |
Market/pending order helpers, position modification/close, raw trade_request() |
| Compatibility |
Selected MetaTrader5-style helpers, explicit tick/bar/trade wire-format controls |
| Operations |
Exception hierarchy, logging, optional metrics, and command rate limiting |
The package name is mt5-web-client; the import name is pymt5.
Python 3.11+ is supported on Linux, macOS, and Windows. No local MetaTrader
terminal is required.
Installation
python -m pip install mt5-web-client
Optional integrations:
python -m pip install "mt5-web-client[structlog]"
python -m pip install "mt5-web-client[pandas]"
For development:
git clone https://github.com/cloudQuant/pymt5.git
cd pymt5
python -m pip install -e ".[dev,docs]"
See the installation guide
for upgrades and verification.
Quick start — read-only
Set credentials through your environment or secret manager. Do not hard-code or
commit them; pymt5 does not implicitly load .env.
export PYMT5_SERVER="wss://web.metatrader.app/terminal"
export PYMT5_LOGIN="your-demo-login"
export PYMT5_PASSWORD="your-demo-password"
The following example connects, loads symbols, and reads account state. It does
not place, modify, or cancel an order.
import asyncio
import os
from pymt5 import MT5WebClient
async def main() -> None:
client = MT5WebClient(
uri=os.environ["PYMT5_SERVER"],
auto_reconnect=True,
)
async with client:
await client.login(
login=int(os.environ["PYMT5_LOGIN"]),
password=os.environ["PYMT5_PASSWORD"],
)
symbols = await client.load_symbols() # dict[str, SymbolInfo]
account = await client.get_account()
print(f"Loaded {len(symbols)} symbols")
print(f"Account currency: {account.get('currency', 'unknown')}")
asyncio.run(main())
Continue with the quick start
for historical bars, managed tick subscriptions, and error handling. Runnable
scripts are listed in the examples guide;
their read-only or mutating scope is labeled explicitly.
Configuration that matters
| Setting |
Default |
Why it matters |
timeout=30.0 |
30 seconds |
A sent request with an uncertain outcome causes connection isolation, not a presumed server result |
auto_reconnect=False |
Disabled |
Reconnects and logs in again after unexpected disconnects; does not retry interrupted trades |
rate_bar_format="auto" |
Strict auto-detection |
Ambiguous/mismatched historical response lengths raise ProtocolError |
tick_price_mode="auto" |
Legacy heuristic |
Prefer scaled or normalized after validating the target server/build |
tick_price_modes={...} |
No overrides |
Case-insensitive per-symbol tick price modes |
trade_protocol="legacy" |
Legacy trade wire format |
build_6090 is an explicit, narrowly observed opt-in, not an automatic build selection |
rate_limit=0 |
Disabled |
Optional token-bucket command throttling |
Full settings and environment variables are in the
configuration guide.
Trading and reliability — read before use
- Use an authorized demo account first. Broker/build compatibility is not
established by offline tests or by a single demo observation.
- A trade timeout or cancellation leaves server execution unknown. Reconcile
orders, deals, and positions before any retry; never assume the trade failed
to execute. Automatic reconnection does not retry it.
- Same-command requests are serialized and pure unsolicited push frames never
complete pending command futures. After a timeout, cancellation, or send
failure where sending may have occurred, the old connection is isolated so a
late response cannot be assigned to a subsequent request on that connection.
This still does not distinguish every duplicate response or push sharing a
command ID.
- Nonzero tick and order-book subscription/unsubscription responses raise
ProtocolError and preserve the last confirmed local subscription set (and
book caches). Explicit logout() or close() clears retained local
subscription state. A build 6320 demo sample rejected removal of all tick
subscriptions; cleanup rejection is not success.
- Volume, price,
heartbeat_interval, and rate_limit/rate_burst inputs
are validated as finite values within supported bounds before sending.
- Tick
auto price normalization remains a compatibility heuristic. Validate
raw and scaled values against the target server before using them in decisions.
- Ordinary
get_positions_and_orders() responses also invoke cmd=4 callbacks;
those callbacks do not distinguish query responses from unsolicited pushes.
See Trading,
Reliability, and
Protocol reference
for details.
Documentation
| English |
中文 |
Contents |
| Documentation home |
文档首页 |
Task-based navigation and project boundaries |
| Quick start |
快速开始 |
Safe first connection and core workflows |
| User guides |
使用指南 |
Market data, trading, streaming, configuration |
| API reference |
API 参考 |
Client, events, data classes, exceptions, constants |
| Troubleshooting |
故障排查 |
Connection, login, rates, subscriptions, diagnostics |
| Development |
开发指南 |
Tests, quality gates, bilingual docs, CI |
| Changelog |
更新日志 |
Release history and compatibility notes |
Use the English / 中文 switch on every documentation page. The site root
also provides a language selector. Read the Docs provides versioned
English and
中文 documentation; GitHub Pages
remains available as a mirror.
Development and verification
make check # lint, mypy, offline tests, docs, package checks
python docs/build_docs.py # build /en/ and /zh-CN/
python docs/check_docs.py # validate links and language switches
CI tests Python 3.11–3.13 on Linux, macOS, and Windows. Ordinary CI and release
tests explicitly deselect integration, never use demo credentials, and enforce
100% offline statement coverage. An offline pass is not live broker
certification.
Read-only demo acceptance
Use an authorized demo account and an exact symbol that is actively trading.
Set PYMT5_SERVER, PYMT5_LOGIN, and PYMT5_PASSWORD through your secret
manager, then run during that symbol's market hours:
export PYMT5_INTEGRATION=1
export PYMT5_REQUIRE_TICK=1 # no tick is a failure, not a skip
export PYMT5_TEST_SYMBOL=EURUSD
export PYMT5_LOG_LEVEL=CRITICAL # avoid sensitive login/session logs
python -m pytest tests/test_integration.py -v --tb=short
The ten tests cover connection/login, symbols and full symbol details, account
and terminal reads, positions/orders/history queries, historical bars,
heartbeat/health, and real tick subscriptions. They never place or modify
trades. Without PYMT5_REQUIRE_TICK=1, no tick within 30 seconds remains a skip
for local closed-market diagnostics, not evidence that tick parsing passed.
Build 6320 rejects removal of the final tick subscription with code=1; the
contract test requires the client to raise and preserve the confirmed state,
while successful removal on other servers must clear it. Closing the connection
performs final cleanup.
Scheduled demo CI
.github/workflows/demo.yml runs separately at 01:00 and 13:00 UTC,
Monday–Friday, or by manual dispatch. Scheduled runs are disabled until a
maintainer sets repository variable PYMT5_DEMO_ENABLED=1. Configure protected
GitHub environment demo with:
- secrets
PYMT5_LOGIN and PYMT5_PASSWORD;
- optional repository/environment variables
PYMT5_SERVER and
PYMT5_TEST_SYMBOL (defaults: the MetaQuotes Web endpoint and EURUSD).
The job requires a real tick and never runs on pull requests. Cron is only a
market-hours heuristic: exchange holidays, symbol-specific sessions, and manual
runs still require an active symbol. GitHub schedules workflows from the default
branch; the workflow must first be pushed and be available on the applicable
ref. Local test commands do not constitute a remote GitHub Actions run.
When reporting an issue, include the server build, minimal reproduction, and
sanitized exception output. Never include passwords, tokens, session IDs, CIDs,
or private account/position data.
License
MIT © cloudQuant. MetaTrader and MetaQuotes are trademarks of their
respective owners; this project is independent and unofficial.