Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
0941597
chore: fix packaging metadata and repository hygiene
Akinzou Nov 9, 2026
843218a
feat(domain): add pure trading rules with a Result type
Akinzou Nov 9, 2026
97ec9f0
feat(application): add Trader use cases behind Terminal and Clock ports
Akinzou Nov 9, 2026
727480c
feat: add MetaTrader5 adapter, connect() and the 2.x Broker facade
Akinzou Nov 9, 2026
6e7cbee
ci: add CI gates, file-length check and demo-account integration tests
Akinzou Nov 9, 2026
252c68d
docs: rewrite README, add migration guide, changelog, architecture an…
Akinzou Nov 9, 2026
a5a03d4
fix: close review findings on symbol filters, unknown outcomes and fills
Akinzou Nov 9, 2026
23eb1c8
refactor(adapter): resolve every MT5 constant at construction
Akinzou Nov 9, 2026
a69f3b9
fix: second review round on fills, sessions, logins and legacy cancels
Akinzou Nov 9, 2026
f5c0833
fix: confirm market deals only on DONE, one login rule, keep live ses…
Akinzou Nov 9, 2026
bc237d4
fix: always release the MT5 session after a failed login
Akinzou Nov 9, 2026
16cc80b
ci: pin publish workflow actions to commit SHAs
Akinzou Nov 9, 2026
55be3e2
fix: refuse zero stops, bad tickets and non-finite numbers; serialize…
Akinzou Nov 9, 2026
eeaee6b
fix(legacy): return MT5-shaped positions and receipts, accept 2.x num…
Akinzou Nov 9, 2026
56457bc
test: compare fakes with the real MetaTrader5 package, cover login re…
Akinzou Nov 9, 2026
4546b05
docs: list every 2.x behaviour change, fix stale and wrong claims, AD…
Akinzou Nov 9, 2026
23f78ff
fix: close /code-review high findings on legacy limits, bool stops, D…
Akinzou Nov 9, 2026
2359877
refactor: Stop owns its invariants; one number rule; price checked in…
Akinzou Nov 9, 2026
591f1cb
fix: refuse prices that snap to zero; Stop.parse; overflow-safe numbe…
Akinzou Nov 9, 2026
048ab75
fix: one tick-grid helper returning Result for every sent level
Akinzou Nov 9, 2026
a0f2aba
fix: SymbolSpec refuses broken terminal data; absolute stops checked …
Akinzou Nov 9, 2026
098ac0a
fix: check broken symbol data where it is used, so closes keep working
Akinzou Nov 9, 2026
a11a618
fix: broken symbol data is a TERMINAL_ERROR on every entry, never on …
Akinzou Nov 9, 2026
880ca9c
fix: BROKEN_SYMBOL_DATA kind; tradability checked right after the sym…
Akinzou Nov 9, 2026
f3f835c
feat: keep re-exporting the MetaTrader5 namespace for 2.x star imports
Akinzou Nov 9, 2026
05e3c35
refactor: re-export the MetaTrader5 namespace lazily, under the sessi…
Akinzou Nov 9, 2026
d046e6a
fix: a broken MetaTrader5 install keeps the star import working and s…
Akinzou Nov 9, 2026
ceb1102
fix: single error prefix, warning points at the user's import, docs c…
Akinzou Nov 9, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
* text=auto eol=lf
*.bat text eol=crlf
74 changes: 74 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
name: CI

on:
pull_request:
push:
branches: [master]

permissions:
contents: read

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
test:
name: lint, types, unit tests (py${{ matrix.python }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python: ["3.10", "3.11", "3.12", "3.13", "3.14"]
steps:
# Actions are pinned to commit SHAs: a moved tag cannot inject code into CI.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ matrix.python }}
- run: python -m pip install -e ".[dev]"
- run: ruff check src tests scripts
- run: ruff format --check src tests scripts
- run: mypy
- run: pytest --cov --cov-report=term-missing

windows-mt5:
# The real MetaTrader5 wheel exists only on Windows. The adapter is built
# against it, and tests/contract compares the unit-test fakes with it
# (constant values, result field names); elsewhere those tests skip.
# Unit tests here still use the fakes, and no terminal is started.
name: real MetaTrader5 package (Windows)
runs-on: windows-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- run: python -m pip install -e ".[dev]"
- run: python -c "import MetaTrader5 as m; from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal as T; T(m); print('MetaTrader5', m.__version__)"
- run: pytest

semgrep:
name: static analysis (Semgrep)
runs-on: ubuntu-latest
container:
image: semgrep/semgrep
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# ERROR-severity (high/critical) findings fail the job and block the merge.
- run: semgrep scan --config p/python --config p/secrets --config p/github-actions --severity ERROR --error
# WARNING-severity (medium) findings are listed for the PR description, not blocking.
- run: semgrep scan --config p/python --config p/secrets --config p/github-actions --severity WARNING

hygiene:
name: file length, package build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- run: python scripts/check_file_length.py
- run: python -m pip install build twine
- run: python -m build
- run: twine check --strict dist/*
4 changes: 2 additions & 2 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ jobs:

steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4

- name: Setup Python
uses: actions/setup-python@v5
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: '3.x'

Expand Down
18 changes: 18 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Build artefacts
build/
dist/
*.egg-info/

# Python caches
__pycache__/
*.py[cod]
.mypy_cache/
.ruff_cache/
.pytest_cache/
.coverage
coverage.xml
htmlcov/

# Local environments and secrets
.venv/
.env
85 changes: 85 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Changelog

All notable changes to this project are documented here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
[Semantic Versioning](https://semver.org/).

## [3.0.0] - Unreleased

Complete rewrite. See [MIGRATION.md](MIGRATION.md) for every behaviour change.

### Added
- `connect()` and the `Trader` API returning `Result` (`Ok` / `Err`) values.
- Typed errors (`TradeError`, `ErrorKind`) and `BatchFailure` for close-all /
cancel-all with per-ticket outcomes.
- `Stop.points()` / `Stop.at_price()` for SL/TP; plain floats are prices.
- `Stop.parse(value, StopKind)` returns `Ok(stop)` / `Err(INVALID_STOPS)` for
values that may be bad at runtime; the constructors raise `ValueError`, and
a `kind` that is not a `StopKind` raises `TypeError`.
- Magic-number support for entries and as a filter for close/cancel/queries.
- Volume validation against the symbol's min/max/step.
- Filling mode chosen from the symbol's allowed modes.
- Hidden symbols are selected into Market Watch automatically.
- `py.typed`: the package ships type information.
- CI: ruff, mypy --strict, tests on Python 3.10-3.14, a Windows job against the
real `MetaTrader5` package, Semgrep, a 300-line file limit, build checks.
- Integration tests against a demo account.
- Contract tests comparing the unit-test fakes with the real `MetaTrader5`
package (run by the Windows CI job).
- Thread safety: every terminal call holds one process-wide lock.

### Changed
- `Broker` is a deprecated facade over `Trader` with the 2.x method names. It
returns `LegacyPosition` / `LegacyReceipt` named tuples with the fields and
field order of MT5's `TradePosition` / `OrderSendResult`.
- The `MetaTrader5` namespace is still re-exported for `import *` and attribute
access, but lazily, and each re-exported call holds the session lock (a
sequence of calls is not atomic; ADR 0010). `Tick` now means
the library's quote model, and importing the library no longer imports
`MetaTrader5`.
- `Position` carries every `TradePosition` field (`swap`, `identifier`, ...);
`TradeReceipt` gains `retcode_external`.
- Bounded retries (requotes only) instead of endless loops.
- Prices snap to the symbol's tick size instead of rounding to `digits`.
- Logging moved from `loguru` to the standard `logging` module.
- Minimum Python version is 3.10.
- License metadata is CC-BY-NC-4.0 (the MIT classifier was wrong).

### Removed
- `pyautogui` Ctrl+E hotkey on retcode 10027.
- The `import *` re-exports of `time`, loguru's `logger` and `pyautogui`.
- The `Broker.password` attribute.

### Safety
- An empty symbol (`""`) is rejected instead of meaning "every symbol".
- `order_send` failures that may have reached the server are reported as
`OUTCOME_UNKNOWN`, never as a plain terminal error.
- Market deals (entries and closes) succeed only on DONE: a partial fill is a
`PARTIAL_FILL` error, a queued (PLACED) one is `OUTCOME_UNKNOWN`; neither is
re-sent.
- Logins that would be coerced (`True`, `12345678.9`, non-ASCII digits) are
rejected, in `connect()` and in `Broker`.
- Every failed login shuts the terminal session down, and `Broker` refuses to
trade until a login succeeds.
- `sl=0` / `tp=0`, stops that resolve to zero or below, tickets that are not
positive integers, `volume=True` and non-finite numbers are rejected before
sending.
- Entries on a symbol whose data cannot price an order (no usable tick size
or point, a NaN tick size, negative digits, volume step 0, ...) return
`BROKEN_SYMBOL_DATA` instead of sending NaN prices or stops on the entry price.
Points stops additionally need a usable `point`. NaN or infinite quotes are
`NO_PRICE`. Closing still works on such symbols.
- `positions(symbol, ticket=...)` applies both filters (MT5 drops the symbol
once a ticket is given).
- Pending orders on exchange-execution symbols use RETURN filling.
- `Broker.Close(None)` / `Broker.CancelOrders(None)` act on nothing.

### Fixed
- `Close(ticket=...)` with `symbol=None` crashed.
- `CancelOrders` and `Close` could loop forever.
- Limit orders confirmed with `PLACED` (10008) were re-sent.
- `len(None)` crash when the terminal returned no positions.

## [2.3.2]

Last release of the 2.x line.
16 changes: 16 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
PythonMetaTrader5
Copyright (c) Wiktor Jelen

This work is licensed under the Creative Commons Attribution-NonCommercial 4.0
International License (CC BY-NC 4.0).

You are free to share and adapt this work for non-commercial purposes, provided
you give appropriate credit, link to the license, and indicate if changes were
made.

Full legal code: https://creativecommons.org/licenses/by-nc/4.0/legalcode
Summary: https://creativecommons.org/licenses/by-nc/4.0/

THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. TRADING FINANCIAL
INSTRUMENTS CARRIES RISK; THE AUTHORS ARE NOT LIABLE FOR ANY LOSSES INCURRED
THROUGH THE USE OF THIS SOFTWARE.
117 changes: 117 additions & 0 deletions MIGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Migrating from 2.x to 3.0

3.0 is a rewrite. Existing code using `Broker` keeps running, but the behaviours
below changed on purpose because they were unsafe. Read this list before
upgrading a bot that trades real money.

## Requirements

- Python **3.10+** (2.x claimed 3.6+).
- `pyautogui` and `loguru` are no longer dependencies.
- Creating a `Broker` emits a `DeprecationWarning`. Test suites that run with
`-W error` or pytest's `filterwarnings = error` must allow it, e.g.
`filterwarnings = ["error", "ignore:Broker is deprecated:DeprecationWarning"]`.

## Behaviour changes in `Broker`

### Logging in

| 2.x | 3.0 | Why |
|---|---|---|
| The constructor called `initialize()` without credentials, then `login()`. After a failed login it went on trading on whichever account the terminal had open | A failed login shuts the terminal session down. Every method then returns `None` / `[]` / `False` and logs "not connected" until `login()` succeeds | Orders went to an account nobody asked for |
| A failed `login()` (for example as a health check) left the working session alone | A failed `login()` also shuts the session down and disables the `Broker` until a login works | After a failed login MT5's single per-process session can be left half-open, so later `initialize()` calls fail |
| Several `Broker` objects in one process each believed they had their own connection | Unchanged, but now visible: MT5 has one session per process, so one instance's failed login disconnects the others too | Run one process per account |
| `Broker(True, ...)` or `Broker(12345678.9, ...)` logged into account 1 / 12345678 | Raises `ValueError` (as a non-numeric login already did) | It traded on a different account than intended |

### Opening positions and limit orders

| 2.x | 3.0 | Why |
|---|---|---|
| `OpenPosition`, `Buy*`, `Sell*`, `BuyLimit`, `SellLimit` retried **forever** on any unknown retcode (no money, invalid volume, market closed over the weekend), sending an order every 0.5 s | Requotes are retried at most 3 times. Any other broker refusal returns at once: the receipt is returned and the error is logged | A weekend webhook blocked the bot until Monday; a rejected order was re-sent indefinitely |
| Invalid input was sent anyway and then retried forever | Refused **before sending**: the call returns `None`, not a receipt, and logs why. This covers a volume off the lot step or outside min/max, an unknown symbol, a comment over 31 characters, and the cases below. Check for `None` before reading `.retcode` | Nothing was sent, so there is no broker answer to return |
| `sl=0` / `tp=0` sent 0.0, which MT5 reads as "no stop" | Refused (returns `None`). Pass `None`, or leave the argument out, for no stop | A missing SL field in a webhook opened an unprotected position without any error |
| An unknown `sl_type` / `tp_type` (e.g. `"bogus"`) opened the position with **neither SL nor TP** | Opens nothing, returns `None` and logs the error | The stop the caller asked for was silently dropped |
| `volume=True` was traded as 1 lot; NaN or infinite numbers crashed deep inside | Refused (returns `None`). Numeric strings (`"0.1"`) are still converted as in 2.x | A stray bool must not become one lot |
| `sl_type="offset"` with an explicit `price=` was measured from the live quote | Measured from `price`. With instant execution the order fills only within `deviation` of `price`, so this is a few points at most. With market execution the broker ignores `price` and fills at the market, so a stale `price` moves the stops by the same distance. A stop that lands on the wrong side of the market is rejected by the server (10016), not applied | The stops follow the price the caller asked for. Use absolute stops if they must not depend on `price` |
| On retcode 10027 it pressed **Ctrl+E** via `pyautogui` | Logs "enable Algo Trading" and returns the receipt | Ctrl+E *toggles* Algo Trading and is typed into whichever window has focus |
| A partial or only-queued (PLACED) market entry counted as opened | Logged as an error; the receipt is still returned, so check `receipt.retcode` (10009 = done) | The bot believed it held the full size |
| Retcode 10008 (`PLACED`) for limit orders was treated as failure and re-sent | Treated as success | Limit orders could be placed more than once |
| `ticket=` on `OpenPosition`/`Buy`/`Sell`/`BuyLimit`/`SellLimit` was forwarded as `position` | Refused: returns `None`, logs an error | On hedging accounts it turned an entry into a close of that position |
| Comments longer than 31 characters made `order_send` fail with `None` | Rejected before sending, logged | Explicit error instead of a crash downstream |
| Prices rounded to `digits` | Prices snapped to the symbol's tick size | Symbols with tick 0.25 were rejected |
| Fixed filling: FOK for market entries, IOC for closes and limit orders | Filling chosen from the symbol's allowed modes (FOK > IOC > RETURN); limit orders on exchange-execution symbols use RETURN | Brokers without FOK rejected every order (10030); IOC cancelled exchange limits unless instantly fillable |

### Closing and cancelling

| 2.x | 3.0 | Why |
|---|---|---|
| `Close()` looped until every position closed, e.g. through a whole closed-market weekend | One attempt per position (requotes retried up to 3 times); a failure returns `False`. A reversal written as `Close(s); Buy(s, v)` must check that `Close` returned `True`, or it may end up holding both | Same as the endless entry loop |
| `Close()` always returned `False` | `True` if at least one position closed and none failed, else `False` | The return value was meaningless |
| `Close(symbol=None, ticket=...)` crashed | Each position is closed on its own symbol | It priced the close with the `symbol` argument |
| `Close(None)` without a ticket crashed without closing anything | Still closes nothing: logs an error, returns `False` | Forwarding `None` would close every position on the account |
| `Close(ticket=0)` / `GetPositions(ticket=0)` passed 0 to `positions_get` | Refused: `False` / `[]`, error logged | 0 may mean "no filter" and close the whole account |
| A partly filled close counted as closed | Reported as a failure (`PARTIAL_FILL`), `Close()` returns `False` | The rest of the position was left open silently |
| `CancelOrders(None)` | Cancels nothing and logs an error | Guards against a missing symbol acting on the whole account |
| `CancelOrders` could loop forever on a failed cancel | One attempt per order (requotes retried), failures logged | Same as above |

### Returned objects

| 2.x | 3.0 | Why |
|---|---|---|
| Entries returned MT5's raw `OrderSendResult` | A `LegacyReceipt` named tuple with the same fields in the same order: attribute access, indexing and `_asdict()` work. `request` is always `None` | 3.x does not keep the echoed request |
| `GetPositions()` returned raw MT5 `TradePosition` objects | `LegacyPosition` named tuples with every `TradePosition` field in MT5's order; `as_dict=True` returns the same 12 keys as before | No dependency on MT5 internals |
| `broker.password` attribute | Removed; credentials are kept in a non-printing object | The password showed up in debug dumps |

## Star import: MetaTrader5 names stay, three others are gone

`from PythonMetaTrader5 import *` still brings in the `MetaTrader5`
namespace (`symbol_info`, `ORDER_TYPE_BUY`, ...), as in 2.x (ADR 0010). The
functions now run under the library's session lock, so a single call cannot
land between a `Trader`'s `order_send` and its error read. A sequence of your
own calls (`order_send` then `last_error`) is not atomic, just as in 2.x. Two
differences:

- `Tick` is now the library's own quote model, not MT5's tick struct. Use
`MetaTrader5.Tick` if you need the struct.
- `time`, `logger` (loguru) and `pyautogui`, which 2.x also leaked through the
star import, are gone. Import them yourself:

```python
import time
```

## Logging

2.x printed through `loguru`. 3.0 uses the standard `logging` module (logger
`PythonMetaTrader5`). Errors and warnings still reach stderr without any
configuration; to see info messages:

```python
import logging

logging.basicConfig(level=logging.INFO)
```

## Moving to the 3.0 API

| 2.x | 3.0 |
|---|---|
| `Broker(login, password, server)` | `connect(login, password, server)` → `Ok(trader)` / `Err(error)` |
| `OpenPosition(s, "buy", v, sl=1000, sl_type="offset")` | `trader.open_position(s, "buy", v, sl=Stop.points(1000))` |
| `OpenPosition(s, "buy", v, sl=1.05)` | `trader.open_position(s, "buy", v, sl=1.05)` |
| `Close("EURUSD")` | `trader.close_positions("EURUSD")` |
| `BuyLimit(s, v, stoplimit=1.1)` | `trader.place_limit_order(s, "buy", v, 1.1)` (no automatic market fill when crossed) |
| `CancelOrders(s)` | `trader.cancel_pending_orders(s, kind=PendingKind.LIMIT)` |
| `GetPositions(as_dict=True)` | see below |
| `Disconnect()` | `trader.shutdown()` or `with trader:` |

`positions()` returns a `Result`, and its dictionaries use `side: "buy"` /
`"sell"` instead of the numeric `type`:

```python
match trader.positions():
case Ok(positions):
rows = [p.to_dict() for p in positions]
case Err(error):
print("cannot list positions:", error)
```
Loading
Loading