diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..a40c349 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,63 @@ +name: Docs + +# Built strictly on every pull request; deployed from master, not from the +# release tag (ADR 0013): a fix to the docs should not wait for a release. The +# changelog's Unreleased section names what the site describes but PyPI does +# not have yet. One workflow for both, so the build a pull request checks is +# the build master publishes. +on: + pull_request: + push: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: docs-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + # Strict: a broken link or anchor, a missing README include or a page left + # out of the navigation fails. Linux on purpose: it proves the reference + # never imports the Windows-only MetaTrader5 package. + name: documentation site (mkdocs --strict) + runs-on: ubuntu-latest + steps: + # Actions are pinned to commit SHAs: a moved tag cannot inject code into CI. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + - run: python -m pip install ".[docs]" + - run: mkdocs build --strict + env: + NO_MKDOCS_2_WARNING: "1" + - if: github.event_name != 'pull_request' + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: site + + deploy: + name: publish to GitHub Pages + needs: build + # A pull request or a manual run from a branch must not replace the site. + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master' + # One deployment at a time, and a running one is never cancelled half-way. + concurrency: + group: pages + cancel-in-progress: false + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.gitignore b/.gitignore index b240fa3..b4a70b2 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,9 @@ __pycache__/ coverage.xml htmlcov/ +# Documentation build output (mkdocs build) +site/ + # Local environments and secrets .venv/ .env diff --git a/CHANGELOG.md b/CHANGELOG.md index e945b40..39dbc16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added +- Documentation site at : the + README as the user guide, an API reference generated from the source, the + architecture overview, every ADR, the migration guide and this changelog + (ADR 0013). Built with `mkdocs build --strict` on every pull request and + deployed from master. `pip install -e ".[docs]"` installs the toolchain. +- Docstrings on every public name and method, and on each `ErrorKind` member + saying what it means. A test fails when a public name has no reference entry + or no docstring. + ## [3.0.1] - 2026-11-09 ### Fixed diff --git a/README.md b/README.md index 53ba470..63263a5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # PythonMetaTrader5 [![CI](https://github.com/Akinzou/MetaTrader5-Python/actions/workflows/ci.yml/badge.svg)](https://github.com/Akinzou/MetaTrader5-Python/actions/workflows/ci.yml) +[![Docs](https://img.shields.io/badge/docs-online-blue?logo=materialformkdocs&logoColor=white)](https://akinzou.github.io/MetaTrader5-Python/) [![PyPI](https://img.shields.io/pypi/v/pythonmetatrader5)](https://pypi.org/project/PythonMetaTrader5/) ![Python](https://img.shields.io/badge/python-3.10%2B-blue?logo=python&logoColor=white) ![License](https://img.shields.io/badge/license-CC_BY--NC_4.0-lightgrey.svg) @@ -46,14 +47,18 @@ the release you are reading (ADR 0012). On PyPI the Contents entries above do not jump to their sections; read this page on [GitHub](https://github.com/Akinzou/MetaTrader5-Python/blob/master/README.md#contents) for that. +Documentation site, with this guide, the API reference, the architecture and +every ADR: . + Other documents: [CHANGELOG.md](https://github.com/Akinzou/MetaTrader5-Python/blob/master/CHANGELOG.md) · [MIGRATION.md](https://github.com/Akinzou/MetaTrader5-Python/blob/master/MIGRATION.md) · [docs/architecture.md](https://github.com/Akinzou/MetaTrader5-Python/blob/master/docs/architecture.md) · [docs/adr](https://github.com/Akinzou/MetaTrader5-Python/tree/master/docs/adr) + ## Why this library -- **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. +- **Every trading call returns.** Requotes and missing quotes 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 @@ -99,6 +104,7 @@ To stay on the old API: `pip install "PythonMetaTrader5<3"`. ## Quick start + ```python from PythonMetaTrader5 import Err, Ok, Side, Stop, connect @@ -123,6 +129,7 @@ with trader: # shuts the terminal connection down on exit trader.close_positions("EURUSD") # only this bot's (magic 1001) positions ``` + ## Connecting @@ -429,6 +436,7 @@ to MetaTrader 5. Details: [docs/architecture.md](https://github.com/Akinzou/Meta | [0010](https://github.com/Akinzou/MetaTrader5-Python/blob/master/docs/adr/0010-keep-the-metatrader5-re-export.md) | Keep re-exporting the MetaTrader5 namespace, lazily | | [0011](https://github.com/Akinzou/MetaTrader5-Python/blob/master/docs/adr/0011-close-all-defaults-to-own-magic.md) | Close-all and cancel-all default to the trader's own magic | | [0012](https://github.com/Akinzou/MetaTrader5-Python/blob/master/docs/adr/0012-pin-readme-links-at-publish.md) | Publish from the tag and pin the README's links there | +| [0013](https://github.com/Akinzou/MetaTrader5-Python/blob/master/docs/adr/0013-documentation-site.md) | A documentation site built from the README and the source | ## Development @@ -441,6 +449,14 @@ pytest --cov python scripts/check_file_length.py ``` +The documentation site (ADR 0013) includes this README as its user guide: + +```bash +pip install -e ".[docs]" +mkdocs serve # preview at http://127.0.0.1:8000 +mkdocs build --strict # what CI runs: broken links and anchors fail +``` + `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 @@ -455,3 +471,4 @@ tag and refuses to run from any other ref (ADR 0012). [CC BY-NC 4.0](https://github.com/Akinzou/MetaTrader5-Python/blob/master/LICENSE). Trading carries risk; this software comes without any warranty. + diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md new file mode 100644 index 0000000..786b75d --- /dev/null +++ b/docs/CHANGELOG.md @@ -0,0 +1 @@ +--8<-- "CHANGELOG.md" diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md new file mode 100644 index 0000000..0fe9b55 --- /dev/null +++ b/docs/MIGRATION.md @@ -0,0 +1 @@ +--8<-- "MIGRATION.md" diff --git a/docs/adr/0013-documentation-site.md b/docs/adr/0013-documentation-site.md new file mode 100644 index 0000000..5d4d1ed --- /dev/null +++ b/docs/adr/0013-documentation-site.md @@ -0,0 +1,70 @@ +# ADR 0013: A documentation site built from the README and the source + +- Status: accepted (after 3.0.1, unreleased). Asked for by the package owner on 2026-11-11. + +## Context + +The README is the complete user guide (the owner's 600-line exemption), +but it has no API reference, and the architecture notes and ADRs are loose +Markdown files on GitHub. The owner wants the project documented to a +professional standard: one site with the guide, a reference generated from the +code, and the reasoning behind it. + +Two facts constrain the tooling. The `MetaTrader5` package is Windows-only, +while the docs are built on Linux. And the package root has no static +`__all__`: unknown names resolve lazily through `MetaTrader5` (ADR 0010). + +## Decision + +- **MkDocs with Material for MkDocs and mkdocstrings**, published to GitHub + Pages at . +- **The reference is read statically** by griffe, never imported. It lists + each public name explicitly (`::: PythonMetaTrader5.`), not the + package, so the `MetaTrader5` namespace never leaks into it. + `tests/unit/test_api_reference.py` fails when a public name has no entry or + no docstring, a public method has no docstring, or an `ErrorKind` member does + not say what it means. +- **The README stays the single source of the guide.** `docs/guide.md` + includes it between `` and `[end:guide]` + markers, which PyPI and GitHub do not render. `MIGRATION.md` and + `CHANGELOG.md` are included the same way. The guide is one page so that the + README's in-page links keep working; its links to other documents still + point to GitHub, as on PyPI. +- **`mkdocs build --strict` runs on every pull request**, in the workflow + that deploys, so the build checked on a pull request is the one published. + A broken link or anchor, a missing include, or a page left out of the + navigation fails it. +- **The site is deployed from master** by `.github/workflows/docs.yml`, with + the official Pages actions; GitHub Pages is set to the Actions source. + +We chose MkDocs over Sphinx because Sphinx autodoc imports the package: on +Linux that needs `autodoc_mock_imports` for `MetaTrader5`, and `automodule` +would follow the computed `__all__` into hundreds of MT5 names. The Markdown +documents would also need MyST. `sphinx-autoapi` avoids the import, but not +the second toolchain. + +We chose including the README over moving its text into the site because two +copies of the guide would drift, and the owner wants PyPI to show the +complete guide. + +We chose deploying from master over deploying from the release tag because a +tag-only site could not ship before the next release, and a fix to the docs +would wait for one too. The cost: the site can describe changes not yet on +PyPI. The changelog's `Unreleased` section names them. + +Rejected: Zensical, the successor of Material for MkDocs. At 0.1 its +mkdocstrings support is preliminary. + +## Consequences + +- Material for MkDocs is in maintenance mode and MkDocs 1.6 gets no new + features. The configuration uses no custom hooks and no plugins besides + search and mkdocstrings, because Zensical reads `mkdocs.yml` and every extra + plugin would make moving there harder. +- Docstrings are now user-facing text. They state the contract briefly; the + semantics and examples stay in the guide. `trader.py` and `broker.py` are + close to the 300-line limit, and parameter tables there would push them over. +- The `docs` extra installs the toolchain: `pip install -e ".[docs]"`, then + `mkdocs serve`. +- The 2.x `Broker` is documented as a class only, pointing to the migration + guide. diff --git a/docs/adr/index.md b/docs/adr/index.md new file mode 100644 index 0000000..dd39cc4 --- /dev/null +++ b/docs/adr/index.md @@ -0,0 +1,11 @@ +# Architecture decision records + +Each record explains one decision that shapes how the library behaves: the +context, what was decided, the alternatives that were rejected and why, and +the consequences. They are the reasoning behind the rules in the +[user guide](../guide.md); read one when a behaviour looks surprising. + +A record is never rewritten to match a later decision. A new record supersedes +it, so the history of why the library works this way stays readable. The +[architecture overview](../architecture.md) shows where each decision lives in +the code. diff --git a/docs/assets/favicon.svg b/docs/assets/favicon.svg new file mode 100644 index 0000000..e95e66f --- /dev/null +++ b/docs/assets/favicon.svg @@ -0,0 +1 @@ + diff --git a/docs/guide.md b/docs/guide.md new file mode 100644 index 0000000..c97debe --- /dev/null +++ b/docs/guide.md @@ -0,0 +1,8 @@ +--- +hide: + - navigation +--- + +# User guide + +--8<-- "README.md:guide" diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..44cec79 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,88 @@ +--- +hide: + - navigation + - toc +--- + +# PythonMetaTrader5 + +A safe, typed trading layer over the official +[`MetaTrader5`](https://pypi.org/project/MetaTrader5/) Python package, built +for bots where a trading call must **never hang, never retry blindly, and +never fail silently**. + +[Get started](guide.md#quick-start){ .md-button .md-button--primary } +[API reference](reference/index.md){ .md-button } +[Architecture](architecture.md){ .md-button } + +```bash +pip install PythonMetaTrader5 +``` + +
+ +- :material-timer-check-outline:{ .lg .middle } **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. + + [:octicons-arrow-right-24: Retries](guide.md#retries) + +- :material-content-duplicate:{ .lg .middle } **No double fills** + + --- + + Timeouts and lost connections are never retried: the order may already be + live. They come back as `OUTCOME_UNKNOWN`. + + [:octicons-arrow-right-24: Error kinds](guide.md#error-kinds) + +- :material-shield-check-outline:{ .lg .middle } **No silent defaults** + + --- + + Values MT5 would quietly read as something else, such as `sl=0` or + `ticket=0`, are refused before anything is sent. + + [:octicons-arrow-right-24: ADR 0008](adr/0008-refuse-values-mt5-misreads.md) + +- :material-code-braces:{ .lg .middle } **Typed results** + + --- + + `Ok(receipt)` or `Err(TradeError)` with an `ErrorKind` instead of magic + numbers, checked by mypy and your editor. + + [:octicons-arrow-right-24: Results and errors](guide.md#results-and-errors) + +- :material-robot-outline:{ .lg .middle } **Close-all touches only your bot** + + --- + + `close_positions()` and `cancel_pending_orders()` act on the trader's own + magic number unless told otherwise. + + [:octicons-arrow-right-24: Magic numbers](guide.md#magic-numbers-whose-trades-a-call-touches) + +- :material-sitemap-outline:{ .lg .middle } **Built to be reasoned about** + + --- + + Clean Architecture with ports and adapters, and every non-obvious choice + recorded as a decision record. + + [:octicons-arrow-right-24: Decisions](adr/index.md) + +
+ +## At a glance + +--8<-- "README.md:quickstart" + +!!! warning "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](guide.md#before-trading-real-money). diff --git a/docs/reference/index.md b/docs/reference/index.md new file mode 100644 index 0000000..ae6c89a --- /dev/null +++ b/docs/reference/index.md @@ -0,0 +1,18 @@ +# API reference + +Everything below is importable from the package root: + +```python +from PythonMetaTrader5 import connect, Trader, Stop, Ok, Err, ErrorKind +``` + +Generated from the source and its type hints. The behaviour behind each call, +with examples, is in the [user guide](../guide.md). + +| Page | Contents | +|---|---| +| [Connecting and trading](trading.md) | `connect`, `Trader`, `RetryPolicy`, `ANY_MAGIC`, `AnyMagic` | +| [Orders and stops](orders.md) | `Side`, `Stop`, `StopKind`, `PendingKind` | +| [Results and errors](results.md) | `Result`, `Ok`, `Err`, `TradeError`, `ErrorKind`, `BatchFailure` | +| [Account state](market.md) | `Position`, `PendingOrder`, `TradeReceipt`, `Tick` | +| [2.x Broker (deprecated)](legacy.md) | `Broker` | diff --git a/docs/reference/legacy.md b/docs/reference/legacy.md new file mode 100644 index 0000000..8253b9b --- /dev/null +++ b/docs/reference/legacy.md @@ -0,0 +1,9 @@ +# 2.x Broker (deprecated) + +`Broker` keeps 2.x bots running and emits a `DeprecationWarning`. Several 2.x +behaviours were unsafe and changed; the [migration guide](../MIGRATION.md) +lists each one and maps the main `Broker` calls to `Trader`. + +::: PythonMetaTrader5.Broker + options: + members: false diff --git a/docs/reference/market.md b/docs/reference/market.md new file mode 100644 index 0000000..ab9676d --- /dev/null +++ b/docs/reference/market.md @@ -0,0 +1,11 @@ +# Account state + +Read models returned by `Trader` queries and trading calls. + +::: PythonMetaTrader5.Position + +::: PythonMetaTrader5.PendingOrder + +::: PythonMetaTrader5.TradeReceipt + +::: PythonMetaTrader5.Tick diff --git a/docs/reference/orders.md b/docs/reference/orders.md new file mode 100644 index 0000000..45ee749 --- /dev/null +++ b/docs/reference/orders.md @@ -0,0 +1,9 @@ +# Orders and stops + +::: PythonMetaTrader5.Side + +::: PythonMetaTrader5.Stop + +::: PythonMetaTrader5.StopKind + +::: PythonMetaTrader5.PendingKind diff --git a/docs/reference/results.md b/docs/reference/results.md new file mode 100644 index 0000000..213683c --- /dev/null +++ b/docs/reference/results.md @@ -0,0 +1,17 @@ +# Results and errors + +Expected failures are values, not exceptions +([ADR 0002](../adr/0002-result-at-boundaries.md)). What to do about each +`ErrorKind` is in the [user guide](../guide.md#error-kinds). + +::: PythonMetaTrader5.Result + +::: PythonMetaTrader5.Ok + +::: PythonMetaTrader5.Err + +::: PythonMetaTrader5.TradeError + +::: PythonMetaTrader5.ErrorKind + +::: PythonMetaTrader5.BatchFailure diff --git a/docs/reference/trading.md b/docs/reference/trading.md new file mode 100644 index 0000000..a95c001 --- /dev/null +++ b/docs/reference/trading.md @@ -0,0 +1,11 @@ +# Connecting and trading + +::: PythonMetaTrader5.connect + +::: PythonMetaTrader5.Trader + +::: PythonMetaTrader5.RetryPolicy + +::: PythonMetaTrader5.ANY_MAGIC + +::: PythonMetaTrader5.AnyMagic diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 0000000..c9f3ae7 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,138 @@ +# Documentation site (ADR 0013). Build: `mkdocs build --strict`. +# No custom hooks or third-party plugins beyond mkdocstrings: Zensical, the +# successor of Material for MkDocs, reads this file, and every extra plugin +# would be one more thing that blocks moving there. +site_name: PythonMetaTrader5 +site_description: Safe, typed trading layer over the official MetaTrader5 Python API +site_url: https://akinzou.github.io/MetaTrader5-Python/ +repo_url: https://github.com/Akinzou/MetaTrader5-Python +repo_name: Akinzou/MetaTrader5-Python +# The guide is the README, included: an edit link would open the stub page. +edit_uri: "" +copyright: Copyright © Wiktor Jelen · CC BY-NC 4.0 · Trading carries risk; no warranty + +theme: + name: material + icon: + repo: fontawesome/brands/github + logo: material/finance + favicon: assets/favicon.svg + features: + - navigation.tabs + - navigation.sections + - navigation.indexes + - navigation.top + - navigation.footer + - navigation.instant + - search.suggest + - search.highlight + - content.code.copy + - toc.follow + palette: + - media: "(prefers-color-scheme: light)" + scheme: default + primary: indigo + accent: teal + toggle: + icon: material/weather-night + name: Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + primary: indigo + accent: teal + toggle: + icon: material/weather-sunny + name: Light mode + +extra: + social: + - icon: fontawesome/brands/github + link: https://github.com/Akinzou/MetaTrader5-Python + - icon: fontawesome/brands/python + link: https://pypi.org/project/PythonMetaTrader5/ + - icon: fontawesome/brands/discord + link: https://discord.gg/BARYa55KS8 + +plugins: + - search + - mkdocstrings: + handlers: + python: + # Static analysis (griffe), never an import: MetaTrader5 is Windows-only + # and the package root resolves unknown names through it. + paths: [src] + options: + docstring_style: google + show_root_heading: true + show_root_full_path: false + show_source: false + show_symbol_type_heading: true + show_symbol_type_toc: true + show_signature_annotations: true + separate_signature: true + signature_crossrefs: true + merge_init_into_class: true + members_order: source + filters: ["!^_"] + # Dataclass fields carry no docstrings, and a Position without its + # fields would be useless. + show_if_no_docstring: true + +markdown_extensions: + - admonition + - attr_list + - md_in_html + - tables + - toc: + permalink: true + - pymdownx.details + - pymdownx.superfences + - pymdownx.inlinehilite + - pymdownx.highlight: + anchor_linenums: true + - pymdownx.emoji: + emoji_index: !!python/name:material.extensions.emoji.twemoji + emoji_generator: !!python/name:material.extensions.emoji.to_svg + # The guide, migration notes and changelog are included from the files + # PyPI and GitHub show, so each text has one source. A missing file fails. + - pymdownx.snippets: + base_path: ["."] + check_paths: true + +# Everything that would only warn fails under --strict: a broken link, a +# missing anchor, or a page left out of the navigation. +validation: + omitted_files: warn + absolute_links: info + unrecognized_links: warn + anchors: warn + +nav: + - Home: index.md + - User guide: guide.md + - API reference: + - reference/index.md + - reference/trading.md + - reference/orders.md + - reference/results.md + - reference/market.md + - reference/legacy.md + - Architecture: + - architecture.md + - Decisions (ADR): + - adr/index.md + - adr/0001-ports-only-at-process-boundaries.md + - adr/0002-result-at-boundaries.md + - adr/0003-bounded-retries.md + - adr/0004-no-gui-automation.md + - adr/0005-stdlib-logging.md + - adr/0006-legacy-facade.md + - adr/0007-filling-and-price-grid.md + - adr/0008-refuse-values-mt5-misreads.md + - adr/0009-one-lock-per-process.md + - adr/0010-keep-the-metatrader5-re-export.md + - adr/0011-close-all-defaults-to-own-magic.md + - adr/0012-pin-readme-links-at-publish.md + - adr/0013-documentation-site.md + - Migrating from 2.x: MIGRATION.md + - Changelog: CHANGELOG.md diff --git a/pyproject.toml b/pyproject.toml index a58d701..e4f3336 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,10 +34,22 @@ classifiers = [ dependencies = ["MetaTrader5; sys_platform == 'win32'"] [project.optional-dependencies] -dev = ["pytest>=8", "pytest-cov>=5", "ruff>=0.6", "mypy>=1.10", "build>=1.2", "twine>=5"] +# griffelib: tests/unit/test_api_reference.py reads the API the way the docs site does. +dev = [ + "pytest>=8", + "pytest-cov>=5", + "ruff>=0.6", + "mypy>=1.10", + "build>=1.2", + "twine>=5", + "griffelib>=2,<3", +] +# The documentation site (ADR 0013); `mkdocs serve` previews it. +docs = ["mkdocs-material>=9.8,<10", "mkdocstrings-python>=2.0,<3"] [project.urls] Homepage = "https://github.com/Akinzou/MetaTrader5-Python" +Documentation = "https://akinzou.github.io/MetaTrader5-Python/" "Bug Tracker" = "https://github.com/Akinzou/MetaTrader5-Python/issues" # master, not the release tag (ADR 0012): the newest CHANGELOG also lists later fixes. Changelog = "https://github.com/Akinzou/MetaTrader5-Python/blob/master/CHANGELOG.md" diff --git a/src/PythonMetaTrader5/application/execution.py b/src/PythonMetaTrader5/application/execution.py index 77f1462..46ad95e 100644 --- a/src/PythonMetaTrader5/application/execution.py +++ b/src/PythonMetaTrader5/application/execution.py @@ -20,6 +20,15 @@ @dataclass(frozen=True, slots=True) class RetryPolicy: + """How often a request the server provably did not execute is retried. + + That is a requote, a price change, no quotes or too many requests, each + answered with a fresh quote, and a missing quote before sending. + + Raises ``ValueError`` for fewer than one attempt or a negative delay. + Timeouts and lost connections are never retried, whatever the policy. + """ + attempts: int = 3 delay_seconds: float = 0.5 diff --git a/src/PythonMetaTrader5/application/trader.py b/src/PythonMetaTrader5/application/trader.py index 37de59c..d5657b1 100644 --- a/src/PythonMetaTrader5/application/trader.py +++ b/src/PythonMetaTrader5/application/trader.py @@ -27,6 +27,14 @@ class Trader: + """Trading calls on one logged-in account; get one from `connect`. + + Every trading call and query returns a `Result`. Orders carry the trader's ``magic``, and + close-all / cancel-all act only on it unless told otherwise. A context + manager: ``with trader:`` shuts the connection down on exit. Tests build one + directly from fakes of the ``Terminal`` and ``Clock`` ports. + """ + def __init__( self, terminal: Terminal, @@ -215,6 +223,7 @@ def pending_orders( magic: int | AnyMagic | None = None, kind: PendingKind | None = None, ) -> Result[list[PendingOrder], TradeError]: + """Every pending order by default, optionally only one ``kind``.""" checked = magic_filter(magic) if isinstance(checked, Err): return checked @@ -228,6 +237,7 @@ def pending_orders( return Ok(orders if kind is None else [o for o in orders if o.kind is kind]) def shutdown(self) -> None: + """Close the connection to the terminal.""" self._terminal.shutdown() def __enter__(self) -> Trader: diff --git a/src/PythonMetaTrader5/domain/errors.py b/src/PythonMetaTrader5/domain/errors.py index 980ca33..b4e3bde 100644 --- a/src/PythonMetaTrader5/domain/errors.py +++ b/src/PythonMetaTrader5/domain/errors.py @@ -11,34 +11,60 @@ class ErrorKind(Enum): + """Why a call failed. What to do about each kind is in the user guide.""" + INVALID_ARGUMENT = "invalid_argument" + """An argument MT5 would misread or refuse: checked before sending, or refused by the server.""" INVALID_VOLUME = "invalid_volume" + """The volume is outside the symbol's min/max, off its step, or above the position's.""" INVALID_PRICE = "invalid_price" + """The price is invalid, e.g. a limit on the wrong side of the market.""" INVALID_STOPS = "invalid_stops" + """A stop-loss or take-profit is zero, negative, not finite or refused by the server.""" INVALID_FILLING = "invalid_filling" + """The server refused the filling mode chosen from the symbol's flags (10030).""" NO_MONEY = "no_money" + """Not enough margin.""" MARKET_CLOSED = "market_closed" + """The market for the symbol is closed.""" TRADE_DISABLED = "trade_disabled" + """Trading is not allowed now: on the symbol or account, or in this direction.""" ALGO_TRADING_DISABLED = "algo_trading_disabled" + """Algo Trading is off in the terminal (10027) or forbidden by the server (10026).""" LIMIT_REACHED = "limit_reached" - # Only part of the volume was executed; the rest is still open/unfilled. + """A broker limit on orders, positions or volume is reached.""" PARTIAL_FILL = "partial_fill" - # The request may or may not have reached the trade server: never auto-retried. + """Only part of the volume was executed; the rest is still open or unfilled.""" OUTCOME_UNKNOWN = "outcome_unknown" + """The request may or may not have reached the server: check positions, never auto-retried.""" RETRIES_EXHAUSTED = "retries_exhausted" + """Requotes, price changes, no quotes or too many requests outlasted the `RetryPolicy`.""" REJECTED = "rejected" + """Any other refusal by the server, unknown retcodes included.""" SYMBOL_NOT_FOUND = "symbol_not_found" + """The terminal does not know the symbol.""" NO_PRICE = "no_price" + """The symbol has no quote.""" TERMINAL_ERROR = "terminal_error" - # The terminal reports symbol data that cannot price an order (a point of 0, - # a NaN tick size, a volume step of 0). Unlike TERMINAL_ERROR it does not - # clear on a resend, so it has its own kind: a bot must escalate, not retry. + """A terminal call failed before anything reached the trade server.""" BROKEN_SYMBOL_DATA = "broken_symbol_data" + """The terminal's symbol data cannot price an order (point 0, NaN tick size, step 0). + + Unlike TERMINAL_ERROR it does not clear on a resend, so it has its own kind: + a bot must escalate, not retry. + """ CONNECTION_FAILED = "connection_failed" + """The terminal did not start or the login failed.""" @dataclass(frozen=True, slots=True) class TradeError: + """An expected failure: its `ErrorKind`, a message and the broker's answer if any. + + ``receipt`` is the broker's raw answer when there was one; ``ticket`` names + the position or order when the failure concerns one item of a batch. + """ + kind: ErrorKind message: str retcode: int | None = None diff --git a/src/PythonMetaTrader5/domain/inputs.py b/src/PythonMetaTrader5/domain/inputs.py index 258b4b9..339e4ee 100644 --- a/src/PythonMetaTrader5/domain/inputs.py +++ b/src/PythonMetaTrader5/domain/inputs.py @@ -67,6 +67,7 @@ class AnyMagic(Enum): # magic, and a None read from a missing config key must not widen them to the # whole account (ADR 0011). ANY_MAGIC: Final = AnyMagic.ANY +"""Pass as ``magic=`` to act on every magic number, manual trades included.""" # MT5 stores magic as a ulong; a larger value would overflow in order_send. _MAX_MAGIC: Final = 2**64 - 1 diff --git a/src/PythonMetaTrader5/domain/market.py b/src/PythonMetaTrader5/domain/market.py index a3e02fe..81dfe54 100644 --- a/src/PythonMetaTrader5/domain/market.py +++ b/src/PythonMetaTrader5/domain/market.py @@ -11,19 +11,25 @@ @dataclass(frozen=True, slots=True) class Tick: + """The current quote of a symbol.""" + bid: float ask: float def entry_price(self, side: Side) -> float: + """The price a market order on ``side`` fills at: ask to buy, bid to sell.""" return self.ask if side is Side.BUY else self.bid def exit_price(self, side: Side) -> float: + """The price that closes a ``side`` position: bid for a long, ask for a short.""" # Closing a long sells at bid, closing a short buys at ask. return self.entry_price(side.opposite) @dataclass(frozen=True, slots=True) class Position: + """An open position. ``sl`` and ``tp`` are ``None`` when not set.""" + ticket: int symbol: str side: Side @@ -48,12 +54,15 @@ class Position: external_id: str def to_dict(self) -> dict[str, Any]: + """The fields as a dict, with ``side`` as its string value.""" data = asdict(self) data["side"] = self.side.value return data class PendingKind(Enum): + """The type of a pending order.""" + LIMIT = "limit" STOP = "stop" STOP_LIMIT = "stop_limit" @@ -61,6 +70,8 @@ class PendingKind(Enum): @dataclass(frozen=True, slots=True) class PendingOrder: + """A pending order waiting on the server.""" + ticket: int symbol: str side: Side diff --git a/src/PythonMetaTrader5/domain/orders.py b/src/PythonMetaTrader5/domain/orders.py index 6e4fc4b..7b7c46e 100644 --- a/src/PythonMetaTrader5/domain/orders.py +++ b/src/PythonMetaTrader5/domain/orders.py @@ -11,19 +11,24 @@ class Side(Enum): + """Trade direction. Calls also accept ``"buy"``, ``"sell"``, ``"long"``, ``"short"``.""" + BUY = "buy" SELL = "sell" @property def opposite(self) -> Side: + """The side that closes a position of this side.""" return Side.SELL if self is Side.BUY else Side.BUY @property def sign(self) -> int: + """``1`` for BUY, ``-1`` for SELL: the direction in which profit grows.""" return 1 if self is Side.BUY else -1 @classmethod def parse(cls, value: Side | str) -> Result[Side, TradeError]: + """A `Side`, or ``Err(INVALID_ARGUMENT)`` for an unknown name.""" if isinstance(value, Side): return Ok(value) name = _SIDE_ALIASES.get(str(value).strip().lower()) diff --git a/src/PythonMetaTrader5/domain/stops.py b/src/PythonMetaTrader5/domain/stops.py index 6e7d3df..ec461e5 100644 --- a/src/PythonMetaTrader5/domain/stops.py +++ b/src/PythonMetaTrader5/domain/stops.py @@ -13,12 +13,21 @@ class StopKind(Enum): + """How a `Stop` value is read: an absolute price or a distance in points.""" + PRICE = "price" POINTS = "points" @dataclass(frozen=True, slots=True) class Stop: + """A stop-loss or take-profit level, as a price or as a distance in points. + + Build one with `Stop.at_price`, `Stop.points` or, for a value that may be + bad at runtime, `Stop.parse`. A stop of zero, a negative price or a value + that is not finite cannot exist: MT5 would read 0 as "no stop". + """ + value: float kind: StopKind @@ -34,6 +43,11 @@ def __post_init__(self) -> None: @classmethod def parse(cls, value: object, kind: StopKind) -> Result[Stop, TradeError]: + """Build a stop, or return ``Err(INVALID_STOPS)`` for a bad value instead of raising. + + A ``kind`` that is not a `StopKind` is a programming error and still + raises ``TypeError``. + """ checked = _checked(value, kind) if isinstance(checked, Err): return checked @@ -41,20 +55,28 @@ def parse(cls, value: object, kind: StopKind) -> Result[Stop, TradeError]: @classmethod def at_price(cls, price: float) -> Stop: + """A stop at an absolute ``price``; raises ``ValueError`` unless positive and finite.""" return cls(price, StopKind.PRICE) @classmethod def points(cls, distance: float) -> Stop: + """A stop ``distance`` points from the entry price; the sign is ignored. + + Raises ``ValueError`` for zero or a value that is not finite; use + `Stop.parse` for a value that may be bad at runtime. + """ return cls(distance, StopKind.POINTS) def stop_loss( self, side: Side, reference: float, spec: SymbolSpec ) -> Result[float, TradeError]: + """The stop-loss price for a ``side`` trade entered at ``reference``, on the tick grid.""" return self._resolve(-side.sign, reference, spec, "sl") def take_profit( self, side: Side, reference: float, spec: SymbolSpec ) -> Result[float, TradeError]: + """The take-profit price for a ``side`` trade entered at ``reference``, on the tick grid.""" return self._resolve(side.sign, reference, spec, "tp") def _resolve( diff --git a/src/PythonMetaTrader5/legacy/broker.py b/src/PythonMetaTrader5/legacy/broker.py index 096363f..e5fba04 100644 --- a/src/PythonMetaTrader5/legacy/broker.py +++ b/src/PythonMetaTrader5/legacy/broker.py @@ -30,6 +30,11 @@ class Broker: + """Deprecated 2.x API, kept so existing bots run; use `connect` instead. + + Read the migration guide before upgrading a bot that trades real money. + """ + RetCodes: ClassVar[dict[int, str]] = { 10027: "Enable Algo Trading in MetaTrader5 app", 10018: "Market closed", diff --git a/src/PythonMetaTrader5/result.py b/src/PythonMetaTrader5/result.py index 4038831..c922973 100644 --- a/src/PythonMetaTrader5/result.py +++ b/src/PythonMetaTrader5/result.py @@ -16,26 +16,35 @@ @dataclass(frozen=True, slots=True) class Ok(Generic[T]): + """A call that succeeded, carrying its ``value``.""" + value: T def is_ok(self) -> bool: + """Always ``True``; prefer ``match`` or ``isinstance`` to narrow the type.""" return True def is_err(self) -> bool: + """Always ``False``.""" return False @dataclass(frozen=True, slots=True) class Err(Generic[E]): + """A call that failed in an expected way, carrying its ``error``.""" + error: E def is_ok(self) -> bool: + """Always ``False``.""" return False def is_err(self) -> bool: + """Always ``True``; prefer ``match`` or ``isinstance`` to narrow the type.""" return True # Union (not PEP 604 `|`) because a generic alias built with `|` cannot be # subscripted at runtime on Python 3.10. Result = Union[Ok[T], Err[E]] # noqa: UP007 +"""Either ``Ok(value)`` or ``Err(error)``; every trading call returns one.""" diff --git a/tests/unit/test_api_reference.py b/tests/unit/test_api_reference.py new file mode 100644 index 0000000..48ce371 --- /dev/null +++ b/tests/unit/test_api_reference.py @@ -0,0 +1,64 @@ +"""The published API reference covers every public name, each with a docstring. + +Read through griffe, the library the docs site renders with, so the test sees +what a reader sees: a `#` comment above a member counts for nothing there. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import griffe + +import PythonMetaTrader5 + +ROOT = Path(__file__).resolve().parents[2] +REFERENCE = ROOT / "docs" / "reference" +DIRECTIVE = re.compile(r"^::: PythonMetaTrader5\.(\w+)\s*$", re.MULTILINE) +# The deprecated 2.x facade is documented as a class only and points readers +# to the migration guide: its 2.x method names are no API to learn anew. +MEMBERS_NOT_DOCUMENTED = {"Broker"} + + +def documented_names() -> list[str]: + return [ + name + for page in sorted(REFERENCE.glob("*.md")) + for name in DIRECTIVE.findall(page.read_text(encoding="utf-8")) + ] + + +def package() -> griffe.Module: + return griffe.load("PythonMetaTrader5", search_paths=[str(ROOT / "src")]) + + +def test_every_public_name_has_exactly_one_reference_entry() -> None: + names = documented_names() + assert sorted(names) == sorted(PythonMetaTrader5._OWN_NAMES) + + +def test_every_public_name_has_a_docstring() -> None: + pkg = package() + missing = [name for name in PythonMetaTrader5._OWN_NAMES if not pkg[name].docstring] + assert missing == [] + + +def test_every_public_method_has_a_docstring() -> None: + pkg = package() + missing = [] + for name in PythonMetaTrader5._OWN_NAMES: + obj = pkg[name] + if not obj.is_class or name in MEMBERS_NOT_DOCUMENTED: + continue + for member_name, member in obj.members.items(): + callable_ = member.is_function or "property" in member.labels + if callable_ and not member_name.startswith("_") and not member.docstring: + missing.append(f"{name}.{member_name}") + assert missing == [] + + +def test_every_error_kind_says_what_it_means() -> None: + kinds = package()["ErrorKind"] + missing = [n for n, m in kinds.members.items() if m.is_attribute and not m.docstring] + assert missing == []