diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..cc23192 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto eol=lf +*.bat text eol=crlf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8e4bb4a --- /dev/null +++ b/.github/workflows/ci.yml @@ -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/* diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index 59494e3..e0ac010 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -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' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b240fa3 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..df2ca96 --- /dev/null +++ b/CHANGELOG.md @@ -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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..17fc111 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000..6c1b027 --- /dev/null +++ b/MIGRATION.md @@ -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) +``` diff --git a/README.md b/README.md index ac89db3..9fe4941 100644 --- a/README.md +++ b/README.md @@ -1,254 +1,183 @@ -# PythonMetaTrader5 [![PyPI Publish](https://github.com/Akinzou/MetaTrader5-Python/actions/workflows/python-publish.yml/badge.svg)](https://github.com/Akinzou/MetaTrader5-Python/actions/workflows/python-publish.yml) ![PyPI](https://img.shields.io/pypi/v/pythonmetatrader5) ![Python](https://img.shields.io/badge/python-3.6%2B-blue?logo=python&logoColor=white) ![License](https://img.shields.io/badge/license-CC_BY--NC_4.0-lightgrey.svg) [![PyPI Downloads](https://static.pepy.tech/badge/pythonmetatrader5)](https://pepy.tech/projects/pythonmetatrader5) - -[![Discord](https://img.shields.io/badge/Join_us_on-Discord-5865F2?logo=discord&logoColor=white&style=for-the-badge)](https://discord.gg/BARYa55KS8) - - -# MetaTrader5 Python Broker Helper - -Minimal, production‑ready helper around the official **MetaTrader5** Python package, -with a single market-entry function and clean handling of **SL/TP as absolute prices or offsets in POINTS**. -Includes utilities to read positions, close them, and manage pending orders. - -> Works with: `MetaTrader5`, `loguru`, `pyautogui` - ---- - -## Features - -* **Unified Execution Engine**: Single core function to open market positions (`OpenPosition(...)`). -* **Dynamic Risk Management**: SL/TP can be passed as **absolute prices** or flexible **offsets in POINTS**. -* **Input Sanitization**: Automatic price normalization to the correct instrument `digits`, preventing API rejection. -* **Robust Telemetry**: Consistent error handling with common MT5 `retcodes` mapped to readable messages. -* **Backward Compatibility**: Seamless wrappers for legacy integration (`Buy`, `Sell`, `BuySL`, `SellSL`). -* **State Helpers**: Efficient querying tools for current market exposure (`GetPositions`, `GetPosition`, `GetPositionsBySymbol`). -* **Lifecycle Management**: Complete control over active and pending trades (`Close`, `SellLimit`, `BuyLimit`, `CancelOrders`). - ---- - -## Installation - -```bash -pip install PythonMetaTrader5 -``` - -> Ensure your MetaTrader 5 terminal is running, logged in, and **Algo Trading** is enabled. - ---- - -## Quick Start - -```python -from PythonMetaTrader5 import Broker -import time - -# Login to your account -broker = Broker(96540048, "PASSWORD", "MetaQuotes-Demo") -time.sleep(1) # small grace period after login - -# Open BUY with SL/TP given as OFFSETS IN POINTS -r = broker.OpenPosition( - "EURUSD", "buy", 0.10, - sl=1000, sl_type="offset", # 1000 points (≈ 100 pips on 5-digit symbol) - tp=1500, tp_type="offset" -) - -# Read positions for a symbol -xau_positions = broker.GetPositionsBySymbol("XAUUSD", as_dict=True) - -# Close all positions on a symbol -broker.Close("EURUSD") - -# Cancel pending limit orders on a symbol -broker.CancelOrders("EURUSD") - -# Graceful shutdown -broker.Disconnect() -``` - ---- - -## SL/TP Semantics (Important) - -- `sl_type` / `tp_type`: - - `"absolute"` → you pass **absolute prices** (e.g., `1.23456`) - - `"offset"` → you pass **offsets in POINTS** (converted using `symbol_info(symbol).point`) - -- Offsets are applied from the **current tick price** (`ask` for BUY, `bid` for SELL): - - BUY : `SL = ask - |sl|*point`, `TP = ask + |tp|*point` - - SELL: `SL = bid + |sl|*point`, `TP = bid - |tp|*point` - -- All calculated prices (including absolute inputs) are normalized to the instrument `digits`. - -> If you get `Wrong SL (10016)`, check `symbol_info(symbol).stops_level` and multiply by `point` to know the minimal allowed distance. - ---- - -## API Reference - -### `class Broker` - -#### `__init__(self, log, password, server)` -Initialize MT5, attempt login, and print account info on success. - -- **log**: login number (int or str) -- **password**: account password (str) -- **server**: broker server name (str) - -#### `login(self, ToEffect=False) -> bool` -Retrying login loop. If `ToEffect` is `False`, returns immediately on failure. - ---- - -### Market Entry - -#### `OpenPosition(self, symbol, side, volume, *, sl=None, tp=None, price=None, comment=None, ticket=None, sl_type="absolute", tp_type="absolute")` -Open a market position. - -- **symbol**: e.g., `"EURUSD"` -- **side**: `"buy" | "sell" | "long" | "short"` -- **volume**: lot size (float) -- **sl**/**tp**: number (see `sl_type`/`tp_type`) -- **sl_type**/**tp_type**: `"absolute"` (prices) or `"offset"` (**POINTS**) -- **price**: optional direct price; if `None`, uses current tick (ask/bid) and retries on transient errors -- **comment**: optional MT5 order comment -- **ticket**: existing position id if needed (rarely used for market entry) - -**Returns**: result of `order_send` (MT5 `TradeResult`) - -**Examples**: -```python -# Absolute prices -broker.OpenPosition("XAUUSD", "sell", 0.10, sl=2400.0, tp=2380.0, sl_type="absolute", tp_type="absolute") - -# Offsets in POINTS -broker.OpenPosition("EURUSD", "buy", 0.10, sl=1000, tp=1500, sl_type="offset", tp_type="offset") -``` - ---- - -### Backward‑Compat Wrappers - -#### `Buy(self, symbol, volume, price=None, *, comment=None, ticket=None)` -Market BUY via `OpenPosition`. - -#### `Sell(self, symbol, volume, price=None, *, comment=None, ticket=None)` -Market SELL via `OpenPosition`. - -#### `BuySL(self, symbol, volume, sl, price=None, *, comment=None, ticket=None, sl_type="absolute")` -BUY with SL specified (absolute or offset in points). - -#### `SellSL(self, symbol, volume, sl, price=None, *, comment=None, ticket=None, sl_type="absolute")` -SELL with SL specified (absolute or offset in points). - ---- - -### Close & Pending Orders - -#### `Close(self, symbol, *, comment=None, ticket=None) -> bool` -Iteratively closes all positions for a **ticket** or for a **symbol** (same filtering semantics as `positions_get`). Returns `False` if nothing to close. - -#### `SellLimit(self, symbol, volume, stoplimit, price=None, comment=None, ticket=None)` -Create a SELL LIMIT order at `stoplimit`. If current `bid >= stoplimit`, executes a market SELL immediately for consistency. - -#### `BuyLimit(self, symbol, volume, stoplimit, price=None, comment=None, ticket=None)` -Create a BUY LIMIT order at `stoplimit`. If current `ask <= stoplimit`, executes a market BUY immediately. - -#### `CancelOrders(self, symbol)` -Cancel all BUY/SELL LIMIT pending orders on the given symbol. - -#### `Disconnect(self)` -Shutdown MT5 connection. - ---- - -### Positions Helpers - -#### `GetPositionsBySymbol(self, symbol: str, as_dict: bool = False) -> list` -Return all open positions for a symbol. If `as_dict=True`, returns a list of plain dictionaries (ready for JSON/GUI). - -#### `GetPositions(self, symbol=None, *, ticket=None, as_dict: bool = False) -> list` -Return positions with the same filter style as `Close()`: -- `ticket` provided → that single position -- else `symbol` provided → all for that symbol -- else → all positions - -#### `GetPosition(self, symbol=None, *, ticket=None, as_dict: bool = False)` -Return the first matching position (or `None`). Useful when at most one position is expected. - -**Example**: -```python -p = broker.GetPosition(symbol="XAUUSD", as_dict=True) -if p: - print("Ticket:", p["ticket"], "Type:", "BUY" if p["type"] == 0 else "SELL", "Profit:", p["profit"]) -``` - ---- - -## Error Handling & Retcodes - -- Known retcodes are mapped in `RetCodes`: - - `10027`: Enable Algo Trading in MetaTrader5 app - - `10018`: Market closed - - `10016`: Wrong SL - -- For `10027`, a `Ctrl+E` hotkey is issued via `pyautogui` to toggle Algo Trading. -- For `10016`, retries are **not** attempted (invalid SL/TP). - ---- - -## Advanced Examples - -```python -# 1) BUY with SL absolute price, TP as offset in points -broker.OpenPosition( - "US500", "buy", 1.0, - sl=5780.0, sl_type="absolute", - tp=200, tp_type="offset" -) - -# 2) SELL with both offsets in points -broker.OpenPosition( - "EURUSD", "sell", 0.2, - sl=800, tp=1200, - sl_type="offset", tp_type="offset" -) - -# 3) Get all positions as dicts and filter by profit -pos = broker.GetPositions(as_dict=True) -winners = [p for p in pos if p["profit"] > 0] - -# 4) Close by ticket -p = broker.GetPosition(symbol="XAUUSD") -if p: - broker.Close("XAUUSD", ticket=p.ticket) - -# 5) Pending orders -broker.BuyLimit("EURUSD", 0.10, stoplimit=1.10000) -broker.SellLimit("EURUSD", 0.10, stoplimit=1.12000) -broker.CancelOrders("EURUSD") -``` - ---- - -## Notes - -- Ensure the symbol is visible/active in MT5 Market Watch. -- Check `stops_level`/`freeze_level` on your broker if SL/TP are rejected: - ```python - info = symbol_info("EURUSD") - print(info.point, info.digits, info.stops_level, info.freeze_level, info.volume_min, info.volume_step) - ``` -- `volume` must respect broker `volume_min`/`volume_step`. - ---- - -## License - -CC-BY-NC 4.0 - - - - - - - +# PythonMetaTrader5 + +[![CI](https://github.com/Akinzou/MetaTrader5-Python/actions/workflows/ci.yml/badge.svg)](https://github.com/Akinzou/MetaTrader5-Python/actions/workflows/ci.yml) +[![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) +[![PyPI Downloads](https://static.pepy.tech/badge/pythonmetatrader5)](https://pepy.tech/projects/pythonmetatrader5) +[![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/BARYa55KS8) + +A safe, typed trading layer over the official +[`MetaTrader5`](https://pypi.org/project/MetaTrader5/) Python package. + +Built for bots (webhook executors, signal followers) where a trading call must +**never hang, never retry blindly, and never fail silently**: + +- **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. + (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 + are refused before sending: `sl=0` ("no stop"), `ticket=0` (possibly "no + filter"), `volume=True` (one lot), NaN and infinities. +- **No double fills.** Timeouts and lost connections are never auto-retried: + the order may already be live. +- **Typed results.** `Ok(receipt)` or `Err(TradeError)` with an `ErrorKind` + (`MARKET_CLOSED`, `NO_MONEY`, `INVALID_STOPS`, ...) instead of magic numbers. +- **Correct prices and lots.** Prices snap to the symbol's tick grid, volumes + are checked against min/max/step, the filling mode is chosen from the symbol. +- **Magic numbers.** Tag your bot's trades and close/cancel only those. +- **SL/TP as prices or distances in points.** +- **2.x compatible.** The old `Broker` class still works (deprecated). + +> One connection per process: the official package keeps a single global +> terminal session, so a second `connect()` (or its failed login) affects the +> first. Run one process per account. +> +> Thread-safe within the library: every terminal call holds one process-wide +> lock, so a threaded webhook server can share a `Trader`. The MT5 functions +> re-exported through `PythonMetaTrader5` hold it for each single call (a pair +> such as `order_send` + `last_error` is not atomic). Calls you make to the +> `MetaTrader5` module directly bypass it. +> +> Requires Windows with a MetaTrader 5 terminal installed (the official +> `MetaTrader5` package is Windows-only). Enable **Algo Trading** in the terminal. + +## Installation + +```bash +pip install PythonMetaTrader5 +``` + +## Quick start + +```python +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", magic=1001) # only this bot's positions +``` + +## API + +`connect(login, password, server, *, path=None, timeout_ms=60000, magic=0, +deviation=10, retry=None) -> Result[Trader, TradeError]` + +`login` must be a positive integer or a string of ASCII digits; `True`, +`12345678.9` and similar values are rejected rather than coerced. + +| `Trader` method | Returns | +|---|---| +| `open_position(symbol, side, volume, *, sl=None, tp=None, price=None, comment=None)` | `Result[TradeReceipt, TradeError]` | +| `place_limit_order(symbol, side, volume, price, *, sl=None, tp=None, comment=None)` | `Result[TradeReceipt, TradeError]` | +| `close_positions(symbol=None, *, ticket=None, magic=None, comment=None)` | `Result[list[TradeReceipt], BatchFailure]` | +| `cancel_pending_orders(symbol=None, *, magic=None, kind=None)` | `Result[list[TradeReceipt], BatchFailure]` | +| `positions(symbol=None, *, ticket=None, magic=None)` | `Result[list[Position], TradeError]` | +| `pending_orders(symbol=None, *, magic=None, kind=None)` | `Result[list[PendingOrder], TradeError]` | +| `shutdown()` | `None` | + +- `side`: `Side.BUY` / `Side.SELL`, or the strings `"buy"`, `"sell"`, `"long"`, `"short"`. +- `sl` / `tp`: a float is an **absolute price**; `Stop.points(n)` is a distance + of `n` points from the entry price (`Stop.at_price(p)` is the explicit form). + For limit orders the distance is measured from the limit price, and for a + market order with an explicit `price` from that price. A float stop that is + zero, negative or not finite is rejected (`INVALID_STOPS`); pass `None` for + no stop. `Stop.points()` / `Stop.at_price()` raise `ValueError` unless the + value is a positive finite number (bool and str included; a zero stop would + mean "no stop" to MT5); the sign of a points distance is ignored. A `kind` + that is not a `StopKind` raises `TypeError`. A stop that resolves outside + the tick grid's range, or to zero or below, is `INVALID_STOPS` when the + order is built. For a value that may be bad at runtime, such as + an ATR that is NaN during warm-up, use + `Stop.parse(value, StopKind.POINTS)`, which returns `Ok(stop)` / + `Err(INVALID_STOPS)`. +- Amounts may be `int`, `float`, `Decimal` or numpy scalars; `bool` and strings + are refused (the deprecated `Broker` still converts numeric strings). +- `price` (market orders): send at this price once instead of the live quote. +- `comment`: at most 31 characters (the terminal's limit). Longer comments are + rejected, not truncated. +- **`close_positions()` and `cancel_pending_orders()` without arguments act on + the whole account**, including manual trades. A bot should always pass its + `magic` (and a symbol); an empty string `""` is rejected. +- `BatchFailure.errors` names every position/order that failed + (`TradeError.ticket`). `BatchFailure.succeeded` holds the receipts of the + ones that worked; their `order` / `deal` are the IDs of the closing deal, not + the position ticket. +- `ticket` must be a positive integer; `0`, `True` or `"7"` are rejected. + +### Errors + +`TradeError(kind, message, retcode=None, receipt=None, ticket=None)`. The +`receipt` carries the broker's raw answer when there was one. Retry policy: + +| Server answer | What happens | +|---|---| +| market deal (entry or close): done | `Ok(receipt)` | +| pending order: placed or done | `Ok(receipt)` | +| market deal: partial fill | `PARTIAL_FILL` with the receipt; part of the deal exists, never re-sent | +| market deal: placed (queued, not executed) | `OUTCOME_UNKNOWN` with the receipt, never re-sent | +| requote, price changed, no quotes, too many requests | retried with a fresh quote, up to `RetryPolicy.attempts` (default 3, 0.5 s apart), then `RETRIES_EXHAUSTED` | +| timeout, no connection, or `order_send` lost in IPC | `OUTCOME_UNKNOWN`, never retried: check `positions()` first | +| anything else | the matching `ErrorKind`, returned at once | +| refused before sending: the terminal's symbol data cannot price an order (point 0, NaN tick size, volume step 0, ...) | `BROKEN_SYMBOL_DATA`, the same on every resend: escalate, don't retry. Closing still works on such symbols | + +```python +from PythonMetaTrader5 import RetryPolicy, connect + +connect(..., retry=RetryPolicy(attempts=5, delay_seconds=0.2)) +``` + +### Logging + +The library logs through the standard `logging` module under the +`PythonMetaTrader5` logger and never configures handlers itself. Without any +logging configuration, warnings and errors still reach stderr. + +## Migrating from 2.x + +`from PythonMetaTrader5 import Broker` keeps working and emits a +`DeprecationWarning`. `from PythonMetaTrader5 import *` still brings in the +`MetaTrader5` functions and constants, as in 2.x. Several 2.x behaviours were unsafe and changed: see +[MIGRATION.md](MIGRATION.md). + +## Development + +```bash +python -m venv .venv && .venv\Scripts\activate +pip install -e ".[dev]" +ruff check src tests scripts && ruff format --check src tests scripts +mypy +pytest --cov +``` + +`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 +`MT5_LOGIN`, `MT5_PASSWORD` and `MT5_SERVER` are set (they refuse to run on a +live account): `pytest -m integration`. + +Architecture and decisions: [docs/architecture.md](docs/architecture.md), +[docs/adr](docs/adr). + +## License + +[CC BY-NC 4.0](LICENSE). Trading carries risk; this software comes without any +warranty. diff --git a/docs/adr/0001-ports-only-at-process-boundaries.md b/docs/adr/0001-ports-only-at-process-boundaries.md new file mode 100644 index 0000000..879fd09 --- /dev/null +++ b/docs/adr/0001-ports-only-at-process-boundaries.md @@ -0,0 +1,24 @@ +# ADR 0001: Ports only at process boundaries + +- Status: accepted (3.0.0) + +## Context + +2.x called `MetaTrader5` functions from one 535-line class, so every rule +(price rounding, stop maths, retry decisions) needed a live terminal to test. + +## Decision + +Two ports, `Terminal` and `Clock`, one per process boundary. Everything that +does no I/O is a plain function or a method on a domain object. + +We chose one port per boundary over one port per concern (e.g. separate +`PriceFeed` and `OrderGateway`). Both concerns go over the same IPC channel to +one terminal process. Splitting them would let tests fake an impossible state +(quotes from one terminal, orders sent to another) and would hide that a single +`shutdown()` ends both. + +## Consequences + +- Unit tests run on any OS against `FakeTerminal`. +- The MT5 adapter is the only module that knows MT5 request dictionaries. diff --git a/docs/adr/0002-result-at-boundaries.md b/docs/adr/0002-result-at-boundaries.md new file mode 100644 index 0000000..394c610 --- /dev/null +++ b/docs/adr/0002-result-at-boundaries.md @@ -0,0 +1,25 @@ +# ADR 0002: Result values at boundaries, exceptions for programming errors + +- Status: accepted (3.0.0) + +## Context + +Most trading failures are expected (market closed, no money, requote). 2.x +mixed `None`, `False`, raw MT5 results and endless loops. + +## Decision + +Use cases and ports return `Ok(value)` or `Err(error)`. `TradeError` carries an +`ErrorKind`, the retcode and the broker's receipt. Batch operations return a +`BatchFailure` with the outcome of each ticket. Exceptions are raised only for +programming errors, such as an invalid `RetryPolicy`. + +We chose a small in-house `Result` over the `returns` library because that +library would add a runtime dependency and a mypy plugin to every user's +project for the sake of two dataclasses. We chose it over exceptions because +an unhandled `MarketClosedError` in a webhook handler silently drops the signal. + +## Consequences + +- Callers have to look at the outcome; `match` statements read naturally. +- A batch close never reports "done" while some positions are still open. diff --git a/docs/adr/0003-bounded-retries.md b/docs/adr/0003-bounded-retries.md new file mode 100644 index 0000000..04ee7fb --- /dev/null +++ b/docs/adr/0003-bounded-retries.md @@ -0,0 +1,44 @@ +# ADR 0003: Bounded retries, never on an unknown outcome + +- Status: accepted (3.0.0) + +## Context + +2.x retried every unknown retcode forever, 0.5 s apart. A bot that hit +NO_MONEY or MARKET_CLOSED blocked indefinitely and kept sending orders. + +## Decision + +Retry only the codes where the server provably did not execute the request: +REQUOTE (10004), PRICE_CHANGED (10020), PRICE_OFF (10021) and +TOO_MANY_REQUESTS (10024). The default is 3 attempts, 0.5 s apart. Each attempt +rebuilds the request from a fresh quote. An explicit `price` is sent only once. + +TIMEOUT (10012) and CONNECTION (10031) come back as `OUTCOME_UNKNOWN` and are +never retried. We chose "report it and let the caller check positions" over +"retry" because a retry after a request that did reach the server opens a +second position without any error. + +The same rule applies when `order_send` itself returns `None`. Only the +`last_error()` codes that prove the request never left the process (invalid +arguments, no IPC link, terminal refused) become `TERMINAL_ERROR`. Send, +receive and IPC-timeout failures become `OUTCOME_UNKNOWN`. + +A missing quote while the request is being built (`NO_PRICE`) is retried, +because nothing has been sent yet. A symbol that was just added to Market Watch +has no quote for a moment. + +Only DONE proves that a market deal (an entry or a close) executed in full. +DONE_PARTIAL becomes `PARTIAL_FILL` and PLACED becomes `OUTCOME_UNKNOWN`, both +carrying the receipt and neither retried, because part of the deal may already +exist. An earlier draft returned `Ok` for a partial entry. We dropped that +because a bot asking for 1 lot would believe it held 1 lot while holding 0.3. +For pending orders, PLACED is the normal success. + +## Consequences + +- Every trading request returns within `attempts × (delay + round trip)`; a + batch close or cancel takes that per position or order. The deprecated + `Broker.login(ToEffect=True)` is the exception: it retries until the login + works, because 2.x documented exactly that. +- Callers that handle `OUTCOME_UNKNOWN` must reconcile with `positions()`. diff --git a/docs/adr/0004-no-gui-automation.md b/docs/adr/0004-no-gui-automation.md new file mode 100644 index 0000000..7952ec5 --- /dev/null +++ b/docs/adr/0004-no-gui-automation.md @@ -0,0 +1,22 @@ +# ADR 0004: No GUI automation for Algo Trading + +- Status: accepted (3.0.0) + +## Context + +On retcode 10027 (AutoTrading disabled by the client), 2.x pressed Ctrl+E +through `pyautogui`. + +## Decision + +Return `ALGO_TRADING_DISABLED` with an instruction, and never send keystrokes. + +We chose an explicit error over the hotkey because Ctrl+E *toggles* the +setting (a second call switches it off again). The keystroke also goes to +whichever window has focus, so on a desktop it typed into the user's editor or +browser. + +## Consequences + +- `pyautogui` is no longer a dependency, and the library works headless. +- Users have to enable Algo Trading once in the terminal. diff --git a/docs/adr/0005-stdlib-logging.md b/docs/adr/0005-stdlib-logging.md new file mode 100644 index 0000000..8dfbdd0 --- /dev/null +++ b/docs/adr/0005-stdlib-logging.md @@ -0,0 +1,24 @@ +# ADR 0005: Standard logging, no NullHandler + +- Status: accepted (3.0.0) + +## Context + +2.x logged with `loguru`, which writes to a global sink that the application +does not control. It also logged the full `account_info()`, including the +owner's name and balance. + +## Decision + +Use `logging.getLogger("PythonMetaTrader5")`, configure nothing, and log only +the login and server on connect. + +We chose not to add the customary `NullHandler`. With it, an unconfigured +script swallows every ERROR record, so a failed order would leave no trace. +Without it, Python's last-resort handler still prints warnings and errors to +stderr. + +## Consequences + +- Applications control format and destination with standard tooling. +- 2.x users lose info-level console output unless they configure logging. diff --git a/docs/adr/0006-legacy-facade.md b/docs/adr/0006-legacy-facade.md new file mode 100644 index 0000000..ee27d53 --- /dev/null +++ b/docs/adr/0006-legacy-facade.md @@ -0,0 +1,31 @@ +# ADR 0006: Keep a 2.x `Broker` facade (star re-export: superseded by ADR 0010) + +- Status: accepted (3.0.0). The star re-export decision is superseded by + [ADR 0010](0010-keep-the-metatrader5-re-export.md). + +## Context + +The package has tens of thousands of downloads, and existing scripts call +`Broker(...)` and its CamelCase methods. 2.x also ran +`from MetaTrader5 import *` in its `__init__`, which re-exported the whole MT5 +namespace. + +## Decision + +`PythonMetaTrader5.Broker` keeps the 2.x names, arguments and return shapes. +It delegates to `Trader` and emits a `DeprecationWarning`. The unsafe 2.x +behaviours are not reproduced (see MIGRATION.md). The star re-export is removed. + +We chose a facade over keeping the 2.x code because the old code is exactly +the code that loops forever. We chose it over removing `Broker` because an +unattended bot upgraded by `pip install -U` would crash at import instead of +running safely. We dropped the re-export because shadowing MT5's namespace made +every new MT5 symbol part of our public API without any review. + +## Consequences + +- Old scripts keep running. Scripts that relied on re-exported MT5 names must + import `MetaTrader5` directly. +- 2.x returned raw MT5 objects, so "the same return shapes" means named + tuples (`LegacyPosition`, `LegacyReceipt`) with MT5's field names and field + order. `tests/contract` checks them against the installed package. diff --git a/docs/adr/0007-filling-and-price-grid.md b/docs/adr/0007-filling-and-price-grid.md new file mode 100644 index 0000000..95dafb3 --- /dev/null +++ b/docs/adr/0007-filling-and-price-grid.md @@ -0,0 +1,31 @@ +# ADR 0007: Filling mode from the symbol, prices on the tick grid + +- Status: accepted (3.0.0); to be confirmed on more brokers with the demo tests + +## Context + +2.x sent FOK for entries and IOC for closes regardless of the symbol, and it +rounded prices to `digits`. + +## Decision + +Market orders use the first mode the symbol allows, in the order +FOK > IOC > RETURN. Pending orders follow the same rule, except on +exchange-execution symbols, where they use RETURN: there it is the only mode +that lets a limit order rest in the book. Prices snap to `trade_tick_size` +(falling back to `point`) and are then rounded to `digits`. + +An earlier draft used a fixed RETURN for pending orders. We dropped it because +MQL5 documents RETURN as not allowed in Market execution mode, so on those +brokers every limit order would have been refused with 10030, while the IOC +that 2.x sent was accepted. + +We prefer FOK over IOC because IOC can fill only part of the requested volume +and still report success, leaving a bot with a position size it never asked +for. Prices snap to the tick grid because rounding to `digits` produces prices +like 5780.13 on a 0.25-tick index, which the server rejects. + +## Consequences + +- Brokers that do not allow FOK no longer reject every order with 10030. +- A partial IOC fill is a `PARTIAL_FILL` error carrying the receipt (see ADR 0003). diff --git a/docs/adr/0008-refuse-values-mt5-misreads.md b/docs/adr/0008-refuse-values-mt5-misreads.md new file mode 100644 index 0000000..3189cd2 --- /dev/null +++ b/docs/adr/0008-refuse-values-mt5-misreads.md @@ -0,0 +1,79 @@ +# ADR 0008: Refuse input that MT5 would quietly read as something else + +- Status: accepted (3.0.0) + +## Context + +Webhook payloads are loosely typed JSON. Several values that a missing or +malformed field produces have a valid but unintended meaning in MT5: + +- `sl=0` / `tp=0` is "no stop", so the position opens unprotected and the call + reports success. +- `ticket=0` may be read as "no filter" by `positions_get`, which in a close + would close the whole account. +- `volume=True` is the number 1, so it trades one lot. +- NaN and infinities crashed with `ValueError` / `OverflowError` deep inside + price rounding, which broke the "every boundary returns a `Result`" rule. + +The empty symbol `""` was already refused for the same reason. + +## Decision + +Refuse these values at the application boundary, before any terminal call: + +- Volume and prices must be positive finite real numbers. Bools are excluded. + `numbers.Real` is used rather than `float`, so numpy scalars from + pandas-based bots still pass. `Decimal`, which is not a `Real`, is accepted + explicitly. +- `Stop` enforces the same rule on itself in `__post_init__`: it stores a + positive finite float, and a points distance drops its sign. It raises + `ValueError` on 0, bool, NaN, infinities and strings, because such a `Stop` + cannot exist. Plain floats passed as `sl` / `tp` are checked without raising + (`stop_input`) and come back as `INVALID_STOPS`. The number rule itself lives + once, in `domain/amounts.py`. An earlier draft stored the raw value and + checked it only in `stop_input`. We dropped it because it left `Stop` + without invariants, `Stop.points(-1000) != Stop.points(1000)`, and every + other consumer of `Stop` would have needed its own check. +- The price is checked inside `validate_entry`, before the symbol lookup and + after the side, comment and stops. A bad price never costs a terminal round + trip, and a bad side is still the first error reported. +- The legacy `BuyLimit` / `SellLimit` check the level before comparing it + with the quote. Otherwise a level of 0 would "cross" the market and be sent + as a market order. +- A stop is `None` (no stop), a positive finite price or a `Stop`. A stop that + resolves to zero or below after tick-grid rounding is refused too. +- A ticket is `None` or a positive integer. + +The rules live in `domain/inputs.py` as plain functions, not a port, because +they do no I/O. The legacy `Broker` converts numeric strings with `float()` +first, as 2.x did. It does not convert bools, so `True` is refused there as +well. + +## Consequences + +- 2.x scripts that passed `sl=0` to mean "no stop" now get `None` and an + error log instead of a trade. MIGRATION.md says so, and `None` is the way + to ask for no stop. +- `Stop.points(0)` raises `ValueError` when it is built, instead of the server + rejecting it with 10016. +- On the `Result` paths (`sl` / `tp` floats, volume, prices, `Stop.parse`), + signalling-NaN Decimals and ints too large for a float are refused without + raising. `float(Decimal("sNaN"))` and `float(10**400)` both raise, so + `positive_float` handles both. Large but finite floats (`1e305`) pass that + rule, but they overflow on the tick grid (`1e305 / 1e-5` is `inf`). + `SymbolSpec.price_on_grid` is the one place every caller-supplied level is + put on the grid, and it refuses those as well as levels that snap to 0. + Quote prices come from the terminal already on the grid. The `Stop` + constructors raise `ValueError` on any invalid value. +- Broken data from the terminal is the same problem on the other side. A + point of 0 put a points stop on the entry price, and a point or tick size + of inf priced orders at NaN. These are the broker's fault and do not clear + on a resend, so they come back as `BROKEN_SYMBOL_DATA`. `INVALID_*` would + blame the caller, and `TERMINAL_ERROR` means "never sent, safe to resend" + (ADR 0003), which would loop. Every entry calls `SymbolSpec.check_tradable()` (tick size, step, + digits, volume limits), including market orders without stops. + `points_to_price` also checks `point`, which only points stops need. The + adapter refuses NaN and infinite quotes as `NO_PRICE`. Closing never runs + these checks. We rejected an invariant on the whole `SymbolSpec`: it made a + position on such a symbol impossible to close, although closing needs only + the filling flags. diff --git a/docs/adr/0009-one-lock-per-process.md b/docs/adr/0009-one-lock-per-process.md new file mode 100644 index 0000000..2d07218 --- /dev/null +++ b/docs/adr/0009-one-lock-per-process.md @@ -0,0 +1,33 @@ +# ADR 0009: One lock per process around terminal calls + +- Status: accepted (3.0.0) + +## Context + +After a failed `order_send`, the adapter reads `last_error()` to decide +between `TERMINAL_ERROR` (never sent, safe to resend) and `OUTCOME_UNKNOWN` +(may have reached the server). `last_error()` is process-global. In a threaded +webhook server, thread B's call can overwrite the error before thread A reads +it. A's lost order could then be labelled "never sent", and resending it +would open a duplicate position. + +## Decision + +`adapters/mt5_terminal.py` holds a module-level `threading.RLock`. Every +public adapter method runs under it, so a call and the error read that +explains it are atomic. + +We rejected a lock per adapter. `connect()` builds a new adapter each time, +and every adapter in a process talks to the same global MT5 session, so +separate locks would not exclude each other. + +## Consequences + +- Terminal calls from different threads run one at a time. MT5 serves one + session per process anyway, so no parallelism is lost. +- A slow call (a login waiting for `timeout_ms`) delays the other threads + for that long. +- Functions re-exported through `PythonMetaTrader5` (ADR 0010) run under the + lock too. The lock lives in `adapters/mt5_session.py`. Calls that user code + makes to the `MetaTrader5` module directly are outside it, and the README + says so. diff --git a/docs/adr/0010-keep-the-metatrader5-re-export.md b/docs/adr/0010-keep-the-metatrader5-re-export.md new file mode 100644 index 0000000..95996b7 --- /dev/null +++ b/docs/adr/0010-keep-the-metatrader5-re-export.md @@ -0,0 +1,69 @@ +# ADR 0010: Keep re-exporting the MetaTrader5 namespace, lazily + +- Status: accepted (3.0.0). Supersedes the "drop the star re-export" part + of [ADR 0006](0006-legacy-facade.md). + +## Context + +ADR 0006 removed the `from MetaTrader5 import *` that 2.x ran in its +`__init__`. Its reason was that every new MT5 name became part of our public +API without review. But 2.x's own README called `symbol_info("EURUSD")` after +`from PythonMetaTrader5 import *`, so scripts written from that README would +fail with `NameError` after a plain `pip install -U`. The package owner +asked to keep the names. + +## Decision + +The package defines a module `__getattr__` (PEP 562). Our own names are +regular module attributes and always win, e.g. `Tick` (ours is the quote +model, MT5's is its tick struct). Any other public name is looked up in +`MetaTrader5` on first use. A star import asks for `__all__` through the same +hook and gets our names plus MT5's. + +- **Lazy.** We rejected the first draft, which ran `from MetaTrader5 import *` + eagerly in `__init__`. It made every `import PythonMetaTrader5` (even of + the pure domain types) pay for MT5 and numpy, and fail with them: a numpy + ABI mismatch would have broken the import itself. +- **Missing vs broken.** "Not installed" (the normal case outside Windows) + means MT5 contributes no names. An installed package that fails to import + (a missing DLL or dependency, a numpy ABI mismatch raising ValueError or + AttributeError) is turned into an `ImportError` with the cause. The star + import then keeps our names and emits a `RuntimeWarning`, an MT5 name raises + `AttributeError` carrying the cause (so `hasattr` and IDEs keep working), + and `connect()` returns `Err(CONNECTION_FAILED)`. A raised `ImportError` + would crash the star import even for scripts that only use `connect`. + `adapters/mt5_session.import_metatrader5` is the one import site, shared + with the adapter. +- **Locked.** Re-exported functions run under the adapter's process-wide + session lock (ADR 0009). Otherwise a direct `last_error()` could run + between the adapter's `order_send` and its own `last_error()` read, and a + lost order would be reported as "never sent". +- `time`, loguru's `logger` and `pyautogui`, which 2.x also leaked, are not + restored. The last two are no longer dependencies, and leaking a stdlib + module is not an API. + +## Consequences + +- New MT5 releases add names to our namespace, as ADR 0006 warned. The cost is + bounded: our names win, and nothing in the library uses the re-exports. +- An MT5 name that equals one of our submodules (`result`, `connection`, ...) + resolves to the submodule. None does today. +- For type checkers, the module `__getattr__` returns `Any`, so + `from PythonMetaTrader5 import symbol_info` type-checks, but so does a typo + like `PythonMetaTrader5.Trder`. Our own names keep their real types. +- Re-exported functions are wrappers: `__wrapped__` is the MT5 original. They + are resolved on every access (no cache), so `pkg.symbol_info is + pkg.symbol_info` is False, and each access costs a few microseconds. The + lock covers one call, not a sequence of a script's own calls. +- Known debt: + - Neither resolved names nor the import outcome (missing or broken) are + cached. Tools that probe many attributes repeat the import lookup, and on + a broken install they re-run the failing import each time. + - On a broken install, `hasattr` / `getattr(pkg, name, None)` give + False / None without a warning; the cause is only in `__cause__` of the + AttributeError. Star imports and `dir()` warn instead, and they raise + under `-W error`. A 2.x script that uses an MT5 name after the star + import still ends in a NameError; the RuntimeWarning beforehand names the + cause. +- `tests/unit/test_mt5_namespace.py` covers the wiring with the fake module, + and `tests/contract` covers the real one. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..11eab54 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,64 @@ +# Architecture + +Clean Architecture with Ports & Adapters. Dependencies point inwards only: + +``` +legacy/ (Broker facade) ─┐ +connection.py (connect) ─┼─► application/ ─► domain/ ─► result.py +adapters/ ───────────────┘ ▲ + (implement the ports) ─────────┘ +``` + +| Layer | Package | Knows about | I/O | +|---|---|---|---| +| Domain | `domain/` | trading rules only: sides, stops, symbol specs, retcode meaning, requests, read models | none | +| Application | `application/` | use cases (`Trader`), retry loop, batch reporting, **ports** | only through ports | +| Adapters | `adapters/` | the `MetaTrader5` package, `time.sleep` | yes | +| Composition | `connection.py` | wires adapters into a `Trader` | through adapters | +| Compatibility | `legacy/` | the 2.x `Broker` API mapped onto `Trader` | through `Trader`; builds the default adapters itself when none are injected | + +## Ports + +There are exactly two, one per process boundary +([ADR 0001](adr/0001-ports-only-at-process-boundaries.md)): + +- `Terminal`: the MetaTrader 5 terminal (IPC to `terminal64.exe`). +- `Clock`: waiting between retries. + +Pure logic (price normalisation, stop resolution, retcode classification, +volume checks) is plain functions and methods on domain objects, not ports. + +## Request flow: `open_position` + +1. Validate side, comment, stops and volume (`domain/inputs.py`: positive, + finite, no bools, no zero stops), then the symbol spec + (`application/entries.py`). Errors return before any order is sent. +2. Build the request from the **current** quote (`Tick.entry_price`), or from + the explicit `price`, resolving `Stop.points` against that price. A stop that + resolves to zero or below is refused. +3. `execute()` sends it and classifies the retcode + ([ADR 0003](adr/0003-bounded-retries.md)): success → `Ok`; retryable → + sleep and rebuild with a fresh quote; anything else → `Err` with the receipt. + +## Concurrency + +`last_error()` in the `MetaTrader5` package is process-global, so the adapter +holds one module-level lock around every terminal call and the error read that +explains it ([ADR 0009](adr/0009-one-lock-per-process.md)). The lock and the +single `MetaTrader5` import live in `adapters/mt5_session.py`, shared with the +lazy 2.x namespace re-export ([ADR 0010](adr/0010-keep-the-metatrader5-re-export.md)). + +## Errors + +Expected failures travel as `Result` values +([ADR 0002](adr/0002-result-at-boundaries.md)). Exceptions are reserved for +programming errors (e.g. `RetryPolicy(attempts=0)`). + +## Testing + +- `tests/unit`: fakes for both ports (`fakes.py`) and for the `MetaTrader5` + module (`fake_mt5.py`); runs on any OS. +- `tests/contract`: the fakes compared with the installed `MetaTrader5` + package (constant values, result field names and order); skipped where the + package is missing. CI runs it on Windows against the real wheel. +- `tests/integration`: a real terminal on a demo account, opt-in via `MT5_*`. diff --git a/pyproject.toml b/pyproject.toml index 9c439c4..ff65d72 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,39 +1,85 @@ -[build-system] -requires = ["setuptools>=61.0", "wheel"] -build-backend = "setuptools.build_meta" - -[project] -name = "PythonMetaTrader5" -version = "2.3.2" -description = "Connect MT5 with Python" -readme = "README.md" -requires-python = ">=3.6" -license = {text = "CC BY-NC 4.0"} - -authors = [{ name = "Wiktor Jelen", email = "wiktorjn@gmail.com" }] - -classifiers = [ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: MIT License", - "Operating System :: OS Independent" -] - -dependencies = [ - "MetaTrader5", - "loguru", - "pyautogui" -] - -[project.urls] -Homepage = "https://github.com/Akinzou/MetaTrader5-Python" -"Bug Tracker" = "https://github.com/Akinzou/MetaTrader5-Python/issues" - -[tool.setuptools.packages.find] -where = ["src"] - - - - - - - +[build-system] +# setuptools>=77 is the first release that accepts a PEP 639 SPDX `license` string; +# older versions would silently publish the wrong license metadata again. +requires = ["setuptools>=77", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "PythonMetaTrader5" +version = "3.0.0" +description = "Safe, typed trading layer over the official MetaTrader5 Python API" +readme = "README.md" +requires-python = ">=3.10" +license = "CC-BY-NC-4.0" +license-files = ["LICENSE"] +authors = [{ name = "Wiktor Jelen", email = "wiktorjn@gmail.com" }] +keywords = ["metatrader5", "mt5", "trading", "forex", "algotrading"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Financial and Insurance Industry", + "Operating System :: Microsoft :: Windows", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Office/Business :: Financial :: Investment", + "Typing :: Typed", +] +# The official MetaTrader5 package ships Windows wheels only. The marker keeps the +# package installable on Linux/macOS (CI, type checking, unit tests against fakes) +# instead of failing the whole install. +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"] + +[project.urls] +Homepage = "https://github.com/Akinzou/MetaTrader5-Python" +"Bug Tracker" = "https://github.com/Akinzou/MetaTrader5-Python/issues" +Changelog = "https://github.com/Akinzou/MetaTrader5-Python/blob/master/CHANGELOG.md" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.package-data] +PythonMetaTrader5 = ["py.typed"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-ra --strict-markers" +markers = ["integration: needs a running MetaTrader 5 terminal and MT5_* credentials"] + +[tool.coverage.run] +source = ["PythonMetaTrader5"] +branch = true + +[tool.coverage.report] +fail_under = 95 +show_missing = true +exclude_also = ["if TYPE_CHECKING:", "raise AssertionError"] + +[tool.ruff] +line-length = 100 +target-version = "py310" + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "N", "S", "PL", "C4", "PT", "RET"] +# N999: the import name `PythonMetaTrader5` predates this rewrite; renaming it to +# snake_case would break every existing `from PythonMetaTrader5 import Broker`. +ignore = ["PLR0913", "N999"] + +[tool.ruff.lint.per-file-ignores] +# The 2.x public method names (Buy, GetPositions, ToEffect...) are the compatibility contract. +# PLR0917: BuyLimit/SellLimit accepted price, comment and ticket positionally in 2.x. +"src/PythonMetaTrader5/legacy/*.py" = ["N802", "N803", "N815", "PLR0917"] +# S106: tests use throwaway fake credentials. +"tests/**/*.py" = ["S101", "S106", "PLR2004"] + +[tool.mypy] +strict = true +python_version = "3.10" +mypy_path = "src" +packages = ["PythonMetaTrader5"] diff --git a/scripts/check_file_length.py b/scripts/check_file_length.py new file mode 100644 index 0000000..0395dc9 --- /dev/null +++ b/scripts/check_file_length.py @@ -0,0 +1,34 @@ +"""Fail when a tracked, hand-written text file exceeds the project's line limit.""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path + +MAX_LINES = 300 +# Binary or third-party verbatim files; nothing generated is tracked. +EXEMPT_SUFFIXES = {".png", ".jpg", ".ico", ".whl"} + + +def tracked_files() -> list[Path]: + # S603: the command is a constant, no untrusted input reaches the process. + command = ["git", "ls-files"] + output = subprocess.run(command, check=True, capture_output=True, text=True).stdout # noqa: S603 + return [Path(line) for line in output.splitlines() if line] + + +def main() -> int: + offenders = [] + for path in tracked_files(): + if path.suffix in EXEMPT_SUFFIXES or not path.is_file(): + continue + count = len(path.read_text(encoding="utf-8", errors="replace").splitlines()) + if count > MAX_LINES: + offenders.append(f"{path}: {count} lines (limit {MAX_LINES})") + print("\n".join(offenders) or f"all tracked files have <= {MAX_LINES} lines") + return 1 if offenders else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/PythonMetaTrader5.egg-info/PKG-INFO b/src/PythonMetaTrader5.egg-info/PKG-INFO deleted file mode 100644 index a4d9385..0000000 --- a/src/PythonMetaTrader5.egg-info/PKG-INFO +++ /dev/null @@ -1,111 +0,0 @@ -Metadata-Version: 2.1 -Name: PythonMetaTrader5 -Version: 1.0.9 -Summary: Connect MT5 with Python -Home-page: https://github.com/Akinzou/MetaTrader5-Python -Author: Wiktor Jelen -Author-email: wiktorjn@gmail.com -Project-URL: Bug Tracker, https://github.com/Akinzou/MetaTrader5-Python/issues -Classifier: Programming Language :: Python :: 3 -Classifier: License :: OSI Approved :: MIT License -Classifier: Operating System :: OS Independent -Requires-Python: >=3.6 -Description-Content-Type: text/markdown - -# Python Library for MetaTrader 5 Connection - -![MetaTrader 5] -This Python library enables you to connect with the MetaTrader 5 trading platform and interact with its features using Python. It allows executing trading operations, fetching market data, receiving notifications, and more. - -## Requirements - -To use this library, you need: - -Python 3.x -MetaTrader 5 trading platform installed -MetaTrader 5 Python API (MetaTrader5 module) -colorama - -## Installation - -To install the library, use `pip`: - -```bash -pip install MetaTrader5 -pip install PythonMetaTrader5 -``` -# Getting Started - -Import the library in your Python script: - -``` -from MetaTrader5 import * -``` - -Initialize the MetaTrader 5 library by calling the initialize() function. - -Create an instance of the Broker class by providing your MetaTrader 5 login credentials and server: - -``` -broker = Broker(log=your_mt5_login, password="your_mt5_password", server="your_mt5_server") -``` -### After successful login, you can perform trading operations such as placing orders and managing positions. - - -## Available Functions: -### Placing Orders: - -``Buy(symbol, volume, price=None, *, comment=None, ticket=None):`` Places a Buy market order or limit order if price is specified. - -``BuySL(symbol, volume, sl, price=None, *, comment=None, ticket=None):`` Places a Buy market order or limit order with a Stop Loss (SL) price if price is specified. - -``Sell(symbol, volume, price=None, *, comment=None, ticket=None):`` Places a Sell market order or limit order if price is specified. - -``SellSL(symbol, volume, sl, price=None, *, comment=None, ticket=None):`` Places a Sell market order or limit order with a Stop Loss (SL) price if price is specified. - -``BuyLimit(symbol, volume, stoplimit, price=None, comment=None, ticket=None):`` Places a Buy limit order with the specified stoplimit price. - -``SellLimit(symbol, volume, stoplimit, price=None, comment=None, ticket=None):`` Places a Sell limit order with the specified stoplimit price. - - -### Managing Positions: -``Close(symbol, *, comment=None, ticket=None):`` Closes all positions for the specified symbol or a specific position indicated by ticket. - -``CancelOrders(symbol):`` Cancels all pending orders for the specified symbol. - - -### Miscellaneous: -``Disconnect():`` Closes the connection to the MetaTrader 5 trading platform. - - -## Example Usage: -``` -from MetaTrader5 import * - -# Initialize the MetaTrader 5 library -initialize() - -# Create a broker instance and log in -broker = Broker(log=your_mt5_login, password="your_mt5_password", server="your_mt5_server") - -# Place a Buy market order for 0.1 lot of EURUSD -broker.Buy("EURUSD", 0.1) - -# Place a limit order for gold (if price is lower than 1900 it will be execute immediately -broker.BuyLimit("XAUUSD", 0.01, 1900) - -# Close all positions for EURUSD -broker.Close("EURUSD") - -# Cancel all pending orders for EURUSD -broker.CancelOrders("EURUSD") - -# Disconnect from the MetaTrader 5 platform -broker.Disconnect() -``` - - -## Note: -It is important to have the MetaTrader 5 trading platform running and logged in with the provided credentials before using this library. -This library is provided "as is" without any warranty. Use it at your own risk. -Before using this library in a live trading environment, thoroughly test it on a demo account to ensure its correctness and reliability. diff --git a/src/PythonMetaTrader5.egg-info/SOURCES.txt b/src/PythonMetaTrader5.egg-info/SOURCES.txt deleted file mode 100644 index bc1a45d..0000000 --- a/src/PythonMetaTrader5.egg-info/SOURCES.txt +++ /dev/null @@ -1,8 +0,0 @@ -README.md -pyproject.toml -setup.cfg -src/PythonMetaTrader5/__init__.py -src/PythonMetaTrader5.egg-info/PKG-INFO -src/PythonMetaTrader5.egg-info/SOURCES.txt -src/PythonMetaTrader5.egg-info/dependency_links.txt -src/PythonMetaTrader5.egg-info/top_level.txt \ No newline at end of file diff --git a/src/PythonMetaTrader5.egg-info/dependency_links.txt b/src/PythonMetaTrader5.egg-info/dependency_links.txt deleted file mode 100644 index 8b13789..0000000 --- a/src/PythonMetaTrader5.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/PythonMetaTrader5.egg-info/top_level.txt b/src/PythonMetaTrader5.egg-info/top_level.txt deleted file mode 100644 index 5c542ee..0000000 --- a/src/PythonMetaTrader5.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -PythonMetaTrader5 diff --git a/src/PythonMetaTrader5/__init__.py b/src/PythonMetaTrader5/__init__.py index 777557f..f133f6b 100644 --- a/src/PythonMetaTrader5/__init__.py +++ b/src/PythonMetaTrader5/__init__.py @@ -1,535 +1,69 @@ -import time -from MetaTrader5 import * -from loguru import logger -import pyautogui - - -class Broker: - RetCodes = { - 10027: "Enable Algo Trading in MetaTrader5 app", - 10018: "Market closed", - 10016: "Wrong SL", - } - - log = None - password = None - server = None - - def __init__(self, log, password, server): - self.log = log - self.password = str(password) - self.server = str(server) - - initialize() - if login(self.log, self.password, server=self.server): - logger.success("Login succes") - acc_info = account_info() - logger.info(str(acc_info)) - else: - logger.error(f"Login failed: {self.log}") - - def login(self, ToEffect=False): - while True: - logger.info(f"Login on: {self.log}") - if login(self.log, self.password, server=self.server): - logger.success("OK") - time.sleep(0.5) - return True - if ToEffect is False: - logger.error("ERROR") - return False - - # -------------------- Symbol meta & normalization -------------------- - - def _symbol_meta(self, symbol): - """ - Returns (point, digits). - point -> minimal price step (MT5) - digits -> number of decimal places - """ - info = symbol_info(symbol) - if info is None: - logger.error(f"{self.log}: symbol_info({symbol}) returned None") - return None, None - point = float(info.point) - digits = int(info.digits) - return point, digits - - def _normalize(self, price, digits): - if price is None: - return None - step = 10 ** (-digits) - return round(float(price) / step) * step - - # -------------------- Low-level senders -------------------- - - def _RawOrderClose(self, order_type, symbol, volume, price, comment=None, ticket=None): - order = { - "action": TRADE_ACTION_DEAL, - "symbol": symbol, - "volume": float(volume), - "type": order_type, - "price": float(price), - "deviation": 10, - "type_filling": ORDER_FILLING_IOC, - } - if comment is not None: - order["comment"] = comment - if ticket is not None: - order["position"] = ticket - return order_send(order) - - def _RawOrder(self, order_type, symbol, volume, price, sl=None, tp=None, comment=None, ticket=None): - volume = float(volume) - - # normalize prices to instrument digits before sending - info = symbol_info(symbol) - if info: - digits = int(info.digits) - price = self._normalize(price, digits) - sl = self._normalize(sl, digits) if sl is not None else None - tp = self._normalize(tp, digits) if tp is not None else None - - order = { - "action": TRADE_ACTION_DEAL, - "symbol": symbol, - "volume": volume, - "type": order_type, - "price": price, - "deviation": 10, - "type_filling": ORDER_FILLING_FOK, - } - if comment is not None: - order["comment"] = comment - if ticket is not None: - order["position"] = ticket - if sl is not None: - order["sl"] = float(sl) - if tp is not None: - order["tp"] = float(tp) - return order_send(order) - - def _RawOrderLimit(self, order_type, symbol, volume, price, limit, comment=None, ticket=None): - # MT5 uses 'price' for the pending level; keep signature consistent - info = symbol_info(symbol) - digits = int(info.digits) if info else 5 - limit = self._normalize(limit, digits) - - order = { - "action": TRADE_ACTION_PENDING, - "symbol": symbol, - "volume": float(volume), - "type": order_type, - "price": float(limit), - "deviation": 10, - "type_filling": ORDER_FILLING_IOC, - } - if comment is not None: - order["comment"] = comment - if ticket is not None: - order["position"] = ticket - return order_send(order) - - # -------------------- Positions I/O -------------------- - - def _pos_to_dict(self, p): - """Serialize MT5 position to a dict (for as_dict=True).""" - if p is None: - return None - return { - "ticket": p.ticket, - "symbol": p.symbol, - "type": p.type, # ORDER_TYPE_BUY / ORDER_TYPE_SELL - "volume": float(p.volume), - "price_open": float(p.price_open), - "sl": float(p.sl) if p.sl else None, - "tp": float(p.tp) if p.tp else None, - "price_current": float(p.price_current), - "profit": float(p.profit), - "time": int(p.time), # epoch - "magic": int(p.magic), - "comment": p.comment, - } - - # -------------------- Positions by symbol -------------------- - - def GetPositionsBySymbol(self, symbol: str, as_dict: bool = False): - """ - Return all open positions for the given symbol. - If as_dict=True -> list of dictionaries. - """ - try: - positions = positions_get(symbol=symbol) - except Exception as e: - logger.error(f"{self.log}: GetPositionsBySymbol exception: {e}") - return [] - - positions = list(positions) if positions else [] - if as_dict: - return [self._pos_to_dict(p) for p in positions] - return positions - - def GetPositions(self, symbol=None, *, ticket=None, as_dict: bool = False): - """ - Return positions with the same filtering semantics as Close(): - - if ticket is provided -> only that position - - elif symbol is provided -> all positions for that symbol - - else -> all open positions - """ - try: - if ticket is not None: - pos = positions_get(ticket=ticket) - elif symbol is not None: - pos = positions_get(symbol=symbol) - else: - pos = positions_get() - except Exception as e: - logger.error(f"{self.log}: GetPositions exception: {e}") - return [] - - pos = list(pos) if pos else [] - if as_dict: - return [self._pos_to_dict(p) for p in pos] - return pos - - def GetPosition(self, symbol=None, *, ticket=None, as_dict: bool = False): - """ - Return the first matching position or None. - Convenient when you expect at most one. - """ - pos_list = self.GetPositions(symbol=symbol, ticket=ticket, as_dict=False) - if not pos_list: - return None if not as_dict else None - return self._pos_to_dict(pos_list[0]) if as_dict else pos_list[0] - - # -------------------- SL/TP computation: absolute or offset IN POINTS -------------------- - - def _compute_sl_tp(self, order_type, symbol, sl, tp, sl_type: str, tp_type: str): - """ - Return (sl_val, tp_val) as absolute prices. - - 'absolute' -> values are prices (e.g., 1.12345), only normalized - - 'offset' -> values are POINTS away from the current price: - BUY : SL = ask - |sl|*point, TP = ask + |tp|*point - SELL: SL = bid + |sl|*point, TP = bid - |tp|*point - """ - sl_val = float(sl) if sl is not None else None - tp_val = float(tp) if tp is not None else None - sl_type = (sl_type or "absolute").lower() - tp_type = (tp_type or "absolute").lower() - - info_tick = symbol_info_tick(symbol) - if info_tick is None: - logger.error(f"{self.log}: symbol_info_tick({symbol}) returned None (SL/TP compute)") - return None, None - - point, digits = self._symbol_meta(symbol) - if point is None: - return None, None - - is_buy = (order_type == ORDER_TYPE_BUY) - ref_price = info_tick.ask if is_buy else info_tick.bid - - if sl_val is not None: - if sl_type == "absolute": - pass - elif sl_type == "offset": - sl_val = ref_price - abs(sl_val) * point if is_buy else ref_price + abs(sl_val) * point - else: - logger.error(f"{self.log}: invalid sl_type '{sl_type}' (use 'absolute'|'offset')") - return None, None - - if tp_val is not None: - if tp_type == "absolute": - pass - elif tp_type == "offset": - tp_val = ref_price + abs(tp_val) * point if is_buy else ref_price - abs(tp_val) * point - else: - logger.error(f"{self.log}: invalid tp_type '{tp_type}' (use 'absolute'|'offset')") - return None, None - - sl_val = self._normalize(sl_val, digits) if sl_val is not None else None - tp_val = self._normalize(tp_val, digits) if tp_val is not None else None - return sl_val, tp_val - - # -------------------- Single market-entry function -------------------- - - def OpenPosition( - self, - symbol, - side, - volume, - *, - sl=None, - tp=None, - price=None, - comment=None, - ticket=None, - sl_type: str = "absolute", # 'absolute' (price) or 'offset' (POINTS) - tp_type: str = "absolute", # 'absolute' (price) or 'offset' (POINTS) - ): - """ - Open a market position. - side: "buy"/"sell" (also accepts "long"/"short") - SL/TP: - - sl_type/tp_type == 'absolute': pass absolute prices - - sl_type/tp_type == 'offset' : pass POINTS from current price - price: if None -> use current ask/bid and retry on known transient errors - """ - side = str(side).lower() - if side not in ("buy", "sell", "long", "short"): - logger.error(f"{self.log}: invalid side '{side}' (use 'buy'/'sell')") - return None - - order_type = ORDER_TYPE_BUY if side in ("buy", "long") else ORDER_TYPE_SELL - - sl_val, tp_val = self._compute_sl_tp(order_type, symbol, sl, tp, sl_type, tp_type) - - # direct-price mode - if price is not None: - return self._RawOrder(order_type, symbol, volume, price, sl_val, tp_val, comment, ticket) - - # current-tick mode with retries - while True: - info = symbol_info_tick(symbol) - if info is None: - logger.error(f"{self.log}: symbol_info_tick({symbol}) returned None") - return None - - curr_price = info.ask if order_type == ORDER_TYPE_BUY else info.bid - r = self._RawOrder(order_type, symbol, volume, curr_price, sl_val, tp_val, comment, ticket) - - if r is None: - logger.error(f"{self.log}: order_send returned None") - return None - - if r.retcode == TRADE_RETCODE_DONE or r.retcode == 10009: - action = "long" if order_type == ORDER_TYPE_BUY else "short" - details = [] - if sl_val is not None: - details.append(f"SL {sl_val}") - if tp_val is not None: - details.append(f"TP {tp_val}") - suffix = f" ({', '.join(details)})" if details else "" - logger.success(f"{self.log}: {action} {symbol}{suffix}") - return r - - if r.retcode in self.RetCodes: - action = "long" if order_type == ORDER_TYPE_BUY else "short" - logger.error(f"ERROR CAN NOT OPEN {self.log}: {action} {symbol}") - logger.error(self.RetCodes[r.retcode]) - if r.retcode == 10027: - logger.info(f"Enabling algotrading {self.log} {symbol}") - time.sleep(1) - pyautogui.hotkey("ctrl", "e") - if r.retcode == 10016: - return r - time.sleep(0.5) - else: - action = "long" if order_type == ORDER_TYPE_BUY else "short" - logger.error(f"ERROR CAN NOT OPEN TRYING AGAIN {self.log}: {action} {symbol}") - logger.info(f"RetCode: {r.retcode}") - logger.info(f"Comment: {r.comment}") - time.sleep(0.5) - - # -------------------- Backward-compat wrappers -------------------- - - def Buy(self, symbol, volume, price=None, *, comment=None, ticket=None): - return self.OpenPosition(symbol, "buy", volume, price=price, comment=comment, ticket=ticket) - - def BuySL(self, symbol, volume, sl, price=None, *, comment=None, ticket=None, sl_type: str = "absolute"): - return self.OpenPosition( - symbol, "buy", volume, sl=sl, price=price, comment=comment, ticket=ticket, sl_type=sl_type - ) - - def Sell(self, symbol, volume, price=None, *, comment=None, ticket=None): - return self.OpenPosition(symbol, "sell", volume, price=price, comment=comment, ticket=ticket) - - def SellSL(self, symbol, volume, sl, price=None, *, comment=None, ticket=None, sl_type: str = "absolute"): - return self.OpenPosition( - symbol, "sell", volume, sl=sl, price=price, comment=comment, ticket=ticket, sl_type=sl_type - ) - - # -------------------- Closing logic -------------------- - - def Close(self, symbol, *, comment=None, ticket=None): - close = False - if ticket is not None: - positions = positions_get(ticket=ticket) - else: - positions = positions_get(symbol=symbol) - - lenpositions = len(positions) - if positions: - while True: - for pos in positions: - if pos.type == ORDER_TYPE_BUY or pos.type == ORDER_TYPE_SELL: - for _ in range(10): - info = symbol_info_tick(symbol) - if info is None: - return None - if pos.type == ORDER_TYPE_BUY: - r = self._RawOrderClose( - ORDER_TYPE_SELL, symbol, pos.volume, info.bid, comment, pos.ticket - ) - close = True - else: - r = self._RawOrderClose( - ORDER_TYPE_BUY, symbol, pos.volume, info.ask, comment, pos.ticket - ) - close = True - if r is None: - return None - if r.retcode != TRADE_RETCODE_REQUOTE and r.retcode != TRADE_RETCODE_PRICE_OFF: - if r.retcode == TRADE_RETCODE_DONE: - logger.info(f"{self.log}: closing all {symbol}") - lenpositions -= 1 - break - if r.retcode in self.RetCodes: - logger.error(f"ERROR CAN NOT CLOSE {self.log} {symbol}") - logger.error(self.RetCodes[r.retcode]) - time.sleep(0.5) - if not lenpositions: - break - if r.retcode == 10027: - logger.info(f"Enabling algotrading {self.log} {symbol}") - time.sleep(1) - pyautogui.hotkey("ctrl", "e") - - if not close: - logger.info(f"{self.log}: there is no orders to close") - return False - - # -------------------- Pending orders -------------------- - - def SellLimit(self, symbol, volume, stoplimit, price=None, comment=None, ticket=None): - OpenedInstantly = False - if price is not None: - logger.error("Price have to be none") - return - - while True: - info = symbol_info_tick(symbol) - if float(info.bid) >= float(stoplimit): - r = self._RawOrder(ORDER_TYPE_SELL, symbol, float(volume), info.bid, comment=comment, ticket=ticket) - OpenedInstantly = True - else: - r = self._RawOrderLimit( - ORDER_TYPE_SELL_LIMIT, symbol, float(volume), info.bid, float(stoplimit), comment, ticket - ) - OpenedInstantly = False - - if r.retcode == 10009: - if OpenedInstantly: - logger.success(f"{self.log}: opened short on: {symbol} beacues of ask is > or = limit price") - else: - logger.success(f"{self.log}: opened short limit on: {symbol} price: {stoplimit}") - break - else: - if r.retcode in self.RetCodes: - logger.error(f"ERROR CAN NOT OPEN {self.log} sell limit on: {symbol} price: {stoplimit}") - logger.error(self.RetCodes[r.retcode]) - if r.retcode == 10027: - logger.info(f"Enabling algotrading {self.log} {symbol}") - time.sleep(1) - pyautogui.hotkey("ctrl", "e") - time.sleep(0.5) - else: - logger.error( - f"ERROR CAN NOT OPEN TRYING AGAIN {self.log} sell limit on: {symbol} price: {stoplimit}" - ) - logger.info(f"RetCode: {r.retcode}") - logger.info(f"Comment: {r.comment}") - time.sleep(0.5) - return r - - def BuyLimit(self, symbol, volume, stoplimit, price=None, comment=None, ticket=None): - OpenedInstantly = False - if price is not None: - logger.error("Price have to be none") - return - - while True: - info = symbol_info_tick(symbol) - if float(info.ask) <= float(stoplimit): - r = self._RawOrder(ORDER_TYPE_BUY, symbol, float(volume), info.ask, comment=comment, ticket=ticket) - OpenedInstantly = True - else: - r = self._RawOrderLimit( - ORDER_TYPE_BUY_LIMIT, symbol, float(volume), info.ask, float(stoplimit), comment, ticket - ) - OpenedInstantly = False - - if r.retcode == 10009: - if OpenedInstantly: - logger.success(f"{self.log}: opened long on: {symbol} beacues of ask is < or = limit price") - else: - logger.success(f"{self.log}: opened long limit on: {symbol} price: {stoplimit}") - break - else: - if r.retcode in self.RetCodes: - logger.error(f"ERROR CAN NOT OPEN {self.log} long limit on: {symbol} price: {stoplimit}") - logger.error(self.RetCodes[r.retcode]) - if r.retcode == 10027: - logger.info(f"Enabling algotrading {self.log} {symbol}") - time.sleep(1) - pyautogui.hotkey("ctrl", "e") - time.sleep(0.5) - else: - logger.error( - f"ERROR CAN NOT OPEN TRYING AGAIN {self.log} long limit on: {symbol} price: {stoplimit}" - ) - logger.info(f"RetCode: {r.retcode}") - logger.info(f"Comment: {r.comment}") - time.sleep(0.5) - return r - - # -------------------- Cancel pending orders -------------------- - - def _RawCancelOrder(self, order_number): - request = { - "action": TRADE_ACTION_REMOVE, - "order": order_number, - "comment": "Order Removed", - } - return order_send(request) - - def CancelOrders(self, symbol): - orders = orders_get() - limit_orders = [ - order - for order in orders - if order.type == ORDER_TYPE_BUY_LIMIT or order.type == ORDER_TYPE_SELL_LIMIT - ] - lenpositions = len(limit_orders) - - while True: - r = None - for order in limit_orders: - if order.symbol == symbol: - r = self._RawCancelOrder(order.ticket) - - if r.retcode != TRADE_RETCODE_REQUOTE and r.retcode != TRADE_RETCODE_PRICE_OFF: - if r.retcode == TRADE_RETCODE_DONE: - logger.info(f"{self.log}: order have been just cancelled on: {symbol}") - lenpositions -= 1 - break - if r.retcode in self.RetCodes: - logger.error(f"ERROR CAN NOT CLOSE {self.log} {symbol}") - logger.error(self.RetCodes[r.retcode]) - time.sleep(0.5) - - if not lenpositions: - break - if r is not None and r.retcode == 10027: - logger.info(f"Enabling algotrading {self.log} {symbol}") - time.sleep(1) - pyautogui.hotkey("ctrl", "e") - - if not len(limit_orders): - logger.info(f"{self.log}: there is no orders to cancel") - - # -------------------- Disconnect -------------------- - - def Disconnect(self): - shutdown() - logger.info("Disconnected from MT5") +"""PythonMetaTrader5: a safe, typed trading layer over the MetaTrader5 package. + +from PythonMetaTrader5 import connect, Stop, Ok, Err + +match connect(12345678, "password", "MetaQuotes-Demo", magic=1001): + case Ok(trader): + trader.open_position("EURUSD", "buy", 0.1, sl=Stop.points(1000)) + case Err(error): + print(error) +""" + +from typing import Any + +# `X as X`: explicit re-exports, because __all__ is computed (see __getattr__). +from PythonMetaTrader5.application.batch import BatchFailure as BatchFailure +from PythonMetaTrader5.application.execution import RetryPolicy as RetryPolicy +from PythonMetaTrader5.application.trader import Trader as Trader +from PythonMetaTrader5.connection import connect as connect +from PythonMetaTrader5.domain.errors import ErrorKind as ErrorKind +from PythonMetaTrader5.domain.errors import TradeError as TradeError +from PythonMetaTrader5.domain.market import PendingKind as PendingKind +from PythonMetaTrader5.domain.market import PendingOrder as PendingOrder +from PythonMetaTrader5.domain.market import Position as Position +from PythonMetaTrader5.domain.market import Tick as Tick +from PythonMetaTrader5.domain.market import TradeReceipt as TradeReceipt +from PythonMetaTrader5.domain.orders import Side as Side +from PythonMetaTrader5.domain.stops import Stop as Stop +from PythonMetaTrader5.domain.stops import StopKind as StopKind +from PythonMetaTrader5.legacy import mt5_namespace as _mt5_namespace +from PythonMetaTrader5.legacy.broker import Broker as Broker +from PythonMetaTrader5.result import Err as Err +from PythonMetaTrader5.result import Ok as Ok +from PythonMetaTrader5.result import Result as Result + +_OWN_NAMES = ( + "BatchFailure", + "Broker", + "Err", + "ErrorKind", + "Ok", + "PendingKind", + "PendingOrder", + "Position", + "Result", + "RetryPolicy", + "Side", + "Stop", + "StopKind", + "Tick", + "TradeError", + "TradeReceipt", + "Trader", + "connect", +) + + +def __getattr__(name: str) -> Any: + # 2.x re-exported the whole MetaTrader5 namespace and its README relied on it + # (`symbol_info("EURUSD")` after a star import), so those names resolve here, + # lazily (ADR 0010). A star import asks for __all__ through this hook too. + # Names defined in this module always win, e.g. our Tick over MT5's struct. + if name == "__all__": + mt5_names = _mt5_namespace.public_names() + return [*_OWN_NAMES, *(n for n in mt5_names if n not in globals())] + return _mt5_namespace.resolve(name) + + +def __dir__() -> list[str]: + return sorted({*globals(), *__getattr__("__all__")}) diff --git a/src/PythonMetaTrader5/adapters/__init__.py b/src/PythonMetaTrader5/adapters/__init__.py new file mode 100644 index 0000000..8373d81 --- /dev/null +++ b/src/PythonMetaTrader5/adapters/__init__.py @@ -0,0 +1 @@ +"""Implementations of the application ports for the real world.""" diff --git a/src/PythonMetaTrader5/adapters/mt5_mapping.py b/src/PythonMetaTrader5/adapters/mt5_mapping.py new file mode 100644 index 0000000..cfcefde --- /dev/null +++ b/src/PythonMetaTrader5/adapters/mt5_mapping.py @@ -0,0 +1,92 @@ +"""Translation between MetaTrader5's raw result objects and domain models. + +Split out of mt5_terminal.py (300-line limit). Pure functions: they read fields +of MT5 objects but never call the terminal, so they need no session lock. +""" + +from __future__ import annotations + +from typing import Any + +from PythonMetaTrader5.domain.market import PendingKind, PendingOrder, Position, TradeReceipt +from PythonMetaTrader5.domain.orders import Side + +OrderTypes = dict[tuple[Side, PendingKind | None], int] + + +def order_type_table(mt5: Any) -> OrderTypes: + return { + (Side.BUY, None): mt5.ORDER_TYPE_BUY, + (Side.SELL, None): mt5.ORDER_TYPE_SELL, + (Side.BUY, PendingKind.LIMIT): mt5.ORDER_TYPE_BUY_LIMIT, + (Side.SELL, PendingKind.LIMIT): mt5.ORDER_TYPE_SELL_LIMIT, + (Side.BUY, PendingKind.STOP): mt5.ORDER_TYPE_BUY_STOP, + (Side.SELL, PendingKind.STOP): mt5.ORDER_TYPE_SELL_STOP, + (Side.BUY, PendingKind.STOP_LIMIT): mt5.ORDER_TYPE_BUY_STOP_LIMIT, + (Side.SELL, PendingKind.STOP_LIMIT): mt5.ORDER_TYPE_SELL_STOP_LIMIT, + } + + +def receipt(result: Any) -> TradeReceipt: + return TradeReceipt( + retcode=int(result.retcode), + deal=int(result.deal), + order=int(result.order), + volume=float(result.volume), + price=float(result.price), + bid=float(result.bid), + ask=float(result.ask), + comment=str(result.comment), + request_id=int(result.request_id), + retcode_external=int(result.retcode_external), + ) + + +def position(p: Any, position_buy: int) -> Position: + return Position( + ticket=int(p.ticket), + symbol=str(p.symbol), + side=Side.BUY if p.type == position_buy else Side.SELL, + volume=float(p.volume), + price_open=float(p.price_open), + # MT5 encodes "no stop" as 0.0, which is also a (useless) price. + sl=float(p.sl) or None, + tp=float(p.tp) or None, + price_current=float(p.price_current), + profit=float(p.profit), + time=int(p.time), + magic=int(p.magic), + comment=str(p.comment), + swap=float(p.swap), + identifier=int(p.identifier), + reason=int(p.reason), + time_msc=int(p.time_msc), + time_update=int(p.time_update), + time_update_msc=int(p.time_update_msc), + external_id=str(p.external_id), + ) + + +def pending_orders( + raw: tuple[Any, ...], by_type: dict[int, tuple[Side, PendingKind]] +) -> list[PendingOrder]: + orders = [] + for o in raw: + key = by_type.get(int(o.type)) + # Market orders still being processed and close-by orders are not resting orders. + if key is None: + continue + side, kind = key + orders.append( + PendingOrder( + ticket=int(o.ticket), + symbol=str(o.symbol), + side=side, + kind=kind, + volume=float(o.volume_current), + price=float(o.price_open), + magic=int(o.magic), + comment=str(o.comment), + ) + ) + return orders diff --git a/src/PythonMetaTrader5/adapters/mt5_session.py b/src/PythonMetaTrader5/adapters/mt5_session.py new file mode 100644 index 0000000..bf5099b --- /dev/null +++ b/src/PythonMetaTrader5/adapters/mt5_session.py @@ -0,0 +1,48 @@ +"""The one MetaTrader5 session of a process: how it is imported and locked. + +Shared by the adapter and the 2.x namespace re-export, so both import the +package the same way and every call through either holds the same lock. +""" + +from __future__ import annotations + +import functools +import importlib +import threading +from collections.abc import Callable +from types import ModuleType +from typing import ParamSpec, TypeVar + +# last_error() is process-global, so a call and the error read that explains it +# must not interleave with another thread's call. Module-level, not per adapter: +# connect() builds a new adapter each time, and every adapter and re-exported +# function in a process talks to the one MT5 session (ADR 0009). +SESSION = threading.RLock() +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +def serialized(function: Callable[_P, _R]) -> Callable[_P, _R]: + @functools.wraps(function) + def locked(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with SESSION: + return function(*args, **kwargs) + + return locked + + +def import_metatrader5() -> ModuleType | None: + """The MetaTrader5 module, or None when it is not installed. + + Only "not installed" becomes None: it is the normal case outside Windows. A + package that is installed but fails to import raises ImportError, whatever + it raised itself: a numpy ABI mismatch can surface as ValueError or + AttributeError, and an AttributeError leaking out of the package + __getattr__ would read as "no such name" and silently empty the star import. + """ + try: + return importlib.import_module("MetaTrader5") + except Exception as error: + if isinstance(error, ModuleNotFoundError) and error.name == "MetaTrader5": + return None + raise ImportError(f"MetaTrader5 is installed but cannot be imported: {error}") from error diff --git a/src/PythonMetaTrader5/adapters/mt5_terminal.py b/src/PythonMetaTrader5/adapters/mt5_terminal.py new file mode 100644 index 0000000..d2ee095 --- /dev/null +++ b/src/PythonMetaTrader5/adapters/mt5_terminal.py @@ -0,0 +1,224 @@ +"""Terminal port implemented with the official `MetaTrader5` package. + +This is the only module that knows MT5's request dictionaries, numeric order +types and the shape of its result objects. +""" + +from __future__ import annotations + +import math +from typing import Any + +from PythonMetaTrader5.adapters import mt5_mapping +from PythonMetaTrader5.adapters.mt5_session import import_metatrader5, serialized +from PythonMetaTrader5.application.ports import Credentials +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.market import PendingOrder, Position, Tick, TradeReceipt +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest +from PythonMetaTrader5.domain.symbol import Filling, SymbolSpec +from PythonMetaTrader5.result import Err, Ok, Result + +# last_error() codes for which order_send provably never left this process +# (bad arguments, no IPC link, terminal refused). Any other failure (send, +# receive, timeout) may have reached the server, so its outcome is unknown. +_NOT_SENT_CODES = ( + "RES_E_INVALID_PARAMS", + "RES_E_NO_MEMORY", + "RES_E_NOT_FOUND", + "RES_E_INVALID_VERSION", + "RES_E_AUTH_FAILED", + "RES_E_UNSUPPORTED", + "RES_E_INTERNAL_FAIL_INIT", + "RES_E_INTERNAL_FAIL_CONNECT", +) + + +class MetaTrader5Terminal: + def __init__(self, mt5: Any) -> None: + # `Any`: the MetaTrader5 package ships no type information. + self._mt5 = mt5 + self._order_types = mt5_mapping.order_type_table(mt5) + self._pending_by_type = { + code: (side, kind) + for (side, kind), code in self._order_types.items() + if kind is not None + } + self._fillings = { + Filling.FOK: mt5.ORDER_FILLING_FOK, + Filling.IOC: mt5.ORDER_FILLING_IOC, + Filling.RETURN: mt5.ORDER_FILLING_RETURN, + } + # Every constant is read here, not at first use, so building the adapter + # against a new MetaTrader5 release fails at once if one was renamed. + self._deal = mt5.TRADE_ACTION_DEAL + self._pending = mt5.TRADE_ACTION_PENDING + self._remove = mt5.TRADE_ACTION_REMOVE + self._good_till_cancel = mt5.ORDER_TIME_GTC + self._position_buy = mt5.POSITION_TYPE_BUY + self._exchange_execution = mt5.SYMBOL_TRADE_EXECUTION_EXCHANGE + self._not_sent = frozenset(getattr(mt5, name) for name in _NOT_SENT_CODES) + self._auto_trading_disabled = mt5.RES_E_AUTO_TRADING_DISABLED + # MT5 reports "nothing found" and "call failed" both as None; only a + # last_error() of RES_S_OK tells "nothing found" apart. + self._ok = mt5.RES_S_OK + + @classmethod + def load(cls) -> Result[MetaTrader5Terminal, TradeError]: + try: + module = import_metatrader5() + except ImportError as error: + # import_metatrader5 already says "installed but cannot be imported". + return Err(TradeError(ErrorKind.CONNECTION_FAILED, str(error))) + if module is None: + return Err( + TradeError( + ErrorKind.CONNECTION_FAILED, + "the MetaTrader5 package is not installed (it is available on Windows only)", + ) + ) + return Ok(cls(module)) + + @serialized + def connect(self, credentials: Credentials) -> Result[None, TradeError]: + args = (credentials.path,) if credentials.path else () + if self._mt5.initialize( + *args, + login=credentials.login, + password=credentials.password, + server=credentials.server, + timeout=credentials.timeout_ms, + ): + return Ok(None) + error = self._last_error() + # Always released: MT5 has one session per process, so after a failed login + # it is unusable for everyone, and a half-open one makes every later + # initialize() fail (login(ToEffect=True) could never recover). A per-adapter + # "keep the live session" flag was tried and dropped: connect() builds a + # new adapter each time, so the flag protected nothing. + self._mt5.shutdown() + return Err( + TradeError( + ErrorKind.CONNECTION_FAILED, + f"login {credentials.login}@{credentials.server} failed: {error}", + ) + ) + + @serialized + def shutdown(self) -> None: + self._mt5.shutdown() + + @serialized + def symbol(self, name: str) -> Result[SymbolSpec, TradeError]: + info = self._mt5.symbol_info(name) + if info is None: + return Err(TradeError(ErrorKind.SYMBOL_NOT_FOUND, f"unknown symbol {name!r}")) + # Hidden symbols have no quotes; 2.x left users to fix Market Watch by hand. + if not info.visible and not self._mt5.symbol_select(name, True): + return Err( + TradeError( + ErrorKind.SYMBOL_NOT_FOUND, + f"{name!r} cannot be added to Market Watch: {self._last_error()}", + ) + ) + return Ok( + SymbolSpec( + name=info.name, + digits=int(info.digits), + point=float(info.point), + tick_size=float(info.trade_tick_size), + volume_min=float(info.volume_min), + volume_max=float(info.volume_max), + volume_step=float(info.volume_step), + filling_flags=int(info.filling_mode), + exchange_execution=int(info.trade_exemode) == self._exchange_execution, + ) + ) + + @serialized + def tick(self, name: str) -> Result[Tick, TradeError]: + tick = self._mt5.symbol_info_tick(name) + # A zero side means no quote yet; trading at price 0 must never be attempted. + # NaN and inf are refused too: `nan <= 0` is False and would send price NaN. + if tick is None or not all(math.isfinite(p) and p > 0 for p in (tick.bid, tick.ask)): + return Err(TradeError(ErrorKind.NO_PRICE, f"no quote for {name!r}")) + return Ok(Tick(bid=float(tick.bid), ask=float(tick.ask))) + + @serialized + def send(self, request: OrderRequest | CancelRequest) -> Result[TradeReceipt, TradeError]: + payload = self._payload(request) + result = self._mt5.order_send(payload) + if result is None: + return Err(self._send_failure()) + return Ok(mt5_mapping.receipt(result)) + + @serialized + def positions( + self, *, symbol: str | None = None, ticket: int | None = None + ) -> Result[list[Position], TradeError]: + query: dict[str, object] = {} + if ticket is not None: + query["ticket"] = ticket + elif symbol is not None: + query["symbol"] = symbol + raw = self._listing(self._mt5.positions_get(**query), "positions_get") + if isinstance(raw, Err): + return raw + found = [mt5_mapping.position(p, self._position_buy) for p in raw.value] + # MT5 ignores `symbol` once `ticket` is given; the port promises both apply. + return Ok([p for p in found if symbol is None or p.symbol == symbol]) + + @serialized + def pending_orders( + self, *, symbol: str | None = None + ) -> Result[list[PendingOrder], TradeError]: + query = {"symbol": symbol} if symbol is not None else {} + raw = self._listing(self._mt5.orders_get(**query), "orders_get") + if isinstance(raw, Err): + return raw + return Ok(mt5_mapping.pending_orders(raw.value, self._pending_by_type)) + + # ------------------------------------------------------------------ helpers + + def _payload(self, request: OrderRequest | CancelRequest) -> dict[str, Any]: + if isinstance(request, CancelRequest): + return {"action": self._remove, "order": request.order} + payload: dict[str, Any] = { + "action": self._deal if request.pending is None else self._pending, + "symbol": request.symbol, + "volume": request.volume, + "type": self._order_types[(request.side, request.pending)], + "price": request.price, + "deviation": request.deviation, + "magic": request.magic, + "comment": request.comment, + "type_filling": self._fillings[request.filling], + "type_time": self._good_till_cancel, + } + optional = {"sl": request.sl, "tp": request.tp, "position": request.position} + payload.update({key: value for key, value in optional.items() if value is not None}) + return payload + + def _listing(self, raw: Any, call: str) -> Result[tuple[Any, ...], TradeError]: + if raw is not None: + return Ok(tuple(raw)) + code, _ = self._mt5.last_error() + if code == self._ok: + return Ok(()) + return Err(TradeError(ErrorKind.TERMINAL_ERROR, f"{call} failed: {self._last_error()}")) + + def _send_failure(self) -> TradeError: + code, text = self._error() + if code == self._auto_trading_disabled: + kind = ErrorKind.ALGO_TRADING_DISABLED + elif code in self._not_sent: + kind = ErrorKind.TERMINAL_ERROR + else: + kind = ErrorKind.OUTCOME_UNKNOWN + return TradeError(kind, f"order_send failed: {text}") + + def _last_error(self) -> str: + return self._error()[1] + + def _error(self) -> tuple[int, str]: + code, message = self._mt5.last_error() + return code, f"[{code}] {message}" diff --git a/src/PythonMetaTrader5/adapters/system_clock.py b/src/PythonMetaTrader5/adapters/system_clock.py new file mode 100644 index 0000000..b56d19c --- /dev/null +++ b/src/PythonMetaTrader5/adapters/system_clock.py @@ -0,0 +1,10 @@ +"""Wall-clock adapter for the Clock port.""" + +from __future__ import annotations + +import time + + +class SystemClock: + def sleep(self, seconds: float) -> None: + time.sleep(seconds) diff --git a/src/PythonMetaTrader5/application/__init__.py b/src/PythonMetaTrader5/application/__init__.py new file mode 100644 index 0000000..c356dd4 --- /dev/null +++ b/src/PythonMetaTrader5/application/__init__.py @@ -0,0 +1 @@ +"""Use cases and the ports they need from the outside world.""" diff --git a/src/PythonMetaTrader5/application/batch.py b/src/PythonMetaTrader5/application/batch.py new file mode 100644 index 0000000..0fde847 --- /dev/null +++ b/src/PythonMetaTrader5/application/batch.py @@ -0,0 +1,57 @@ +"""Applying one trade action to many positions/orders and reporting per item.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from dataclasses import dataclass, replace +from typing import Protocol, TypeVar + +from PythonMetaTrader5.domain.errors import TradeError +from PythonMetaTrader5.domain.market import TradeReceipt +from PythonMetaTrader5.result import Err, Ok, Result + + +class _Ticketed(Protocol): + @property + def ticket(self) -> int: ... + + @property + def magic(self) -> int: ... + + +_T = TypeVar("_T", bound=_Ticketed) + + +@dataclass(frozen=True, slots=True) +class BatchFailure: + """Some items of a batch (close all / cancel all) failed; others may have succeeded.""" + + succeeded: tuple[TradeReceipt, ...] + errors: tuple[TradeError, ...] + + def __str__(self) -> str: + return f"{len(self.errors)} failed, {len(self.succeeded)} succeeded: " + "; ".join( + str(e) for e in self.errors + ) + + +def run_batch( + items: Iterable[_T], action: Callable[[_T], Result[TradeReceipt, TradeError]] +) -> Result[list[TradeReceipt], BatchFailure]: + # Every item is attempted even after a failure: stopping at the first error + # would leave the remaining positions open while reporting only one problem. + succeeded: list[TradeReceipt] = [] + errors: list[TradeError] = [] + for item in items: + match action(item): + case Ok(receipt): + succeeded.append(receipt) + case Err(error): + errors.append(replace(error, ticket=item.ticket)) + if errors: + return Err(BatchFailure(tuple(succeeded), tuple(errors))) + return Ok(succeeded) + + +def with_magic(items: list[_T], magic: int | None) -> list[_T]: + return items if magic is None else [item for item in items if item.magic == magic] diff --git a/src/PythonMetaTrader5/application/entries.py b/src/PythonMetaTrader5/application/entries.py new file mode 100644 index 0000000..d4eb121 --- /dev/null +++ b/src/PythonMetaTrader5/application/entries.py @@ -0,0 +1,163 @@ +"""Validated entry parameters shared by market and pending entries. + +Split out of trader.py (300-line limit): this is the only place that turns raw +caller input into an entry request, so every check runs before any send. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from PythonMetaTrader5.application.ports import Terminal +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.inputs import positive_number, stop_input +from PythonMetaTrader5.domain.market import PendingKind +from PythonMetaTrader5.domain.orders import Side, validate_comment +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest +from PythonMetaTrader5.domain.stops import Stop, StopKind +from PythonMetaTrader5.domain.symbol import SymbolSpec +from PythonMetaTrader5.result import Err, Ok, Result + +StopInput = Stop | float | None + + +@dataclass(frozen=True, slots=True) +class Entry: + spec: SymbolSpec + side: Side + volume: float + comment: str + stop_loss: Stop | None + take_profit: Stop | None + # The caller's price on the symbol's tick grid; None means "use the quote". + price: float | None + + def request( + self, + quote: float | None = None, + *, + pending: PendingKind | None, + deviation: int, + magic: int, + ) -> Result[OrderRequest | CancelRequest, TradeError]: + reference = self.price if self.price is not None else quote + if reference is None: + return Err(TradeError(ErrorKind.NO_PRICE, f"no price for {self.spec.name}")) + spec, side = self.spec, self.side + sl = self.stop_loss.stop_loss(side, reference, spec) if self.stop_loss else Ok(None) + if isinstance(sl, Err): + return sl + tp = self.take_profit.take_profit(side, reference, spec) if self.take_profit else Ok(None) + if isinstance(tp, Err): + return tp + return Ok( + OrderRequest( + symbol=spec.name, + side=side, + volume=self.volume, + price=reference, + filling=spec.market_filling() if pending is None else spec.pending_filling(), + deviation=deviation, + magic=magic, + comment=self.comment, + sl=sl.value, + tp=tp.value, + pending=pending, + ) + ) + + +def validate_entry( + terminal: Terminal, + symbol: str, + side: Side | str, + volume: float, + *, + comment: str | None, + sl: StopInput, + tp: StopInput, + price: object = None, + price_required: bool = False, +) -> Result[Entry, TradeError]: + # Every check that needs no terminal, the price included, runs before the + # symbol lookup, which costs a round trip and may add the symbol to Market + # Watch. + values = _caller_values(side, comment, sl, tp, price, price_required=price_required) + if isinstance(values, Err): + return values + amount = positive_number(volume, ErrorKind.INVALID_VOLUME, "volume") + if isinstance(amount, Err): + return amount + spec = _tradable_spec(terminal, symbol) + if isinstance(spec, Err): + return spec + lots = spec.value.validate_volume(amount.value) + if isinstance(lots, Err): + return lots + parsed_side, text, stop_loss, take_profit, level = values.value + on_grid = _quote_free_levels(spec.value, level, stop_loss, take_profit) + if isinstance(on_grid, Err): + return on_grid + return Ok( + Entry(spec.value, parsed_side, lots.value, text, stop_loss, take_profit, on_grid.value) + ) + + +def _tradable_spec(terminal: Terminal, symbol: str) -> Result[SymbolSpec, TradeError]: + # Checked right after the lookup, before any caller value is judged against + # the spec: broken broker data must not come back as the caller's + # INVALID_VOLUME. It covers market orders without stops too, which never + # reach price_on_grid. Closing never calls this. + spec = terminal.symbol(symbol) + if isinstance(spec, Err): + return spec + tradable = spec.value.check_tradable() + return tradable if isinstance(tradable, Err) else spec + + +def _quote_free_levels( + spec: SymbolSpec, price: float | None, sl: Stop | None, tp: Stop | None +) -> Result[float | None, TradeError]: + # Absolute stops do not depend on the quote, so they are checked here, before + # the first tick request: otherwise a stop that can never be valid would sit + # through the NO_PRICE retries of a symbol without quotes first. + # The price first, so a bad price is still reported before a bad stop. + level = None if price is None else spec.price_on_grid(price, ErrorKind.INVALID_PRICE, "price") + if isinstance(level, Err): + return level + for name, stop in (("sl", sl), ("tp", tp)): + if stop is not None and stop.kind is StopKind.PRICE: + checked = spec.price_on_grid(stop.value, ErrorKind.INVALID_STOPS, name) + if isinstance(checked, Err): + return checked + return Ok(None if level is None else level.value) + + +def _caller_values( + side: Side | str, + comment: str | None, + sl: StopInput, + tp: StopInput, + price: object, + *, + price_required: bool, +) -> Result[tuple[Side, str, Stop | None, Stop | None, float | None], TradeError]: + parsed_side = Side.parse(side) + if isinstance(parsed_side, Err): + return parsed_side + text = validate_comment(comment) + if isinstance(text, Err): + return text + stop_loss, take_profit = stop_input(sl, "sl"), stop_input(tp, "tp") + if isinstance(stop_loss, Err): + return stop_loss + if isinstance(take_profit, Err): + return take_profit + level = ( + positive_number(price, ErrorKind.INVALID_PRICE, "price") + if price is not None or price_required + else Ok(None) + ) + if isinstance(level, Err): + return level + return Ok((parsed_side.value, text.value, stop_loss.value, take_profit.value, level.value)) diff --git a/src/PythonMetaTrader5/application/execution.py b/src/PythonMetaTrader5/application/execution.py new file mode 100644 index 0000000..77f1462 --- /dev/null +++ b/src/PythonMetaTrader5/application/execution.py @@ -0,0 +1,108 @@ +"""Sending a request with a bounded, outcome-aware retry loop.""" + +from __future__ import annotations + +import logging +from collections.abc import Callable +from dataclasses import dataclass, replace + +from PythonMetaTrader5.application.ports import Clock, Terminal +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.market import TradeReceipt +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest +from PythonMetaTrader5.domain.retcodes import DONE, DONE_PARTIAL, Outcome, classify, error_for +from PythonMetaTrader5.result import Err, Ok, Result + +log = logging.getLogger("PythonMetaTrader5") + +RequestFactory = Callable[[], Result[OrderRequest | CancelRequest, TradeError]] + + +@dataclass(frozen=True, slots=True) +class RetryPolicy: + attempts: int = 3 + delay_seconds: float = 0.5 + + def __post_init__(self) -> None: + # Misconfiguration is a programming error, not a market outcome, so it + # fails loudly at construction instead of travelling as a Result. + if self.attempts < 1 or self.delay_seconds < 0: + raise ValueError(f"invalid retry policy: {self}") + + +def execute( + terminal: Terminal, clock: Clock, build: RequestFactory, policy: RetryPolicy +) -> Result[TradeReceipt, TradeError]: + """Rebuild and send the request until it succeeds, fails, or attempts run out. + + The request is rebuilt on every attempt so a requote is answered with the + current price instead of re-sending the stale one. + """ + last: TradeReceipt | None = None + for attempt in range(1, policy.attempts + 1): + request = build() + if isinstance(request, Err): + # Nothing was sent, so waiting is safe; a symbol just added to Market + # Watch typically has no quote for the first few hundred milliseconds. + if request.error.kind is ErrorKind.NO_PRICE and attempt < policy.attempts: + clock.sleep(policy.delay_seconds) + continue + return request + sent = terminal.send(request.value) + if isinstance(sent, Err): + return sent + last = sent.value + outcome = classify(last.retcode) + if outcome is Outcome.SUCCESS: + return _confirm(request.value, last) + if outcome is Outcome.FAIL: + return Err(replace(error_for(last.retcode), receipt=last)) + log.warning("retcode %s on attempt %s/%s", last.retcode, attempt, policy.attempts) + if attempt < policy.attempts: + clock.sleep(policy.delay_seconds) + if last is None: # pragma: no cover - range(1, attempts + 1) is never empty + raise AssertionError("retry loop ran zero times") + return Err( + TradeError( + ErrorKind.RETRIES_EXHAUSTED, + f"gave up after {policy.attempts} attempts: {error_for(last.retcode).message}", + retcode=last.retcode, + receipt=last, + ) + ) + + +def _confirm( + request: OrderRequest | CancelRequest, receipt: TradeReceipt +) -> Result[TradeReceipt, TradeError]: + """Only DONE proves a market deal (entry or close) executed in full. + + PARTIAL leaves volume unfilled (an entry is smaller than asked, a close leaves + a remainder open) and PLACED means queued, not executed. Both come back as + errors carrying the receipt, and neither is retried: part of the deal may + already exist, so re-sending could double it. + """ + if ( + not isinstance(request, OrderRequest) + or request.pending is not None + or receipt.retcode == DONE + ): + return Ok(receipt) + if receipt.retcode == DONE_PARTIAL: + return Err( + TradeError( + ErrorKind.PARTIAL_FILL, + f"executed {receipt.volume} of {request.volume} lots; with RETURN " + "filling the rest may still be working as an order", + retcode=receipt.retcode, + receipt=receipt, + ) + ) + return Err( + TradeError( + ErrorKind.OUTCOME_UNKNOWN, + "accepted but not executed yet; check positions before re-sending", + retcode=receipt.retcode, + receipt=receipt, + ) + ) diff --git a/src/PythonMetaTrader5/application/ports.py b/src/PythonMetaTrader5/application/ports.py new file mode 100644 index 0000000..e70c9d9 --- /dev/null +++ b/src/PythonMetaTrader5/application/ports.py @@ -0,0 +1,75 @@ +"""The only two process boundaries of the library: the MT5 terminal and time.""" + +from __future__ import annotations + +import operator +from dataclasses import dataclass, field +from typing import Protocol + +from PythonMetaTrader5.domain.errors import TradeError +from PythonMetaTrader5.domain.market import PendingOrder, Position, Tick, TradeReceipt +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest +from PythonMetaTrader5.domain.symbol import SymbolSpec +from PythonMetaTrader5.result import Result + + +@dataclass(frozen=True, slots=True) +class Credentials: + login: int + # repr=False keeps the password out of logs, tracebacks and debugger dumps. + password: str = field(repr=False) + server: str + path: str | None = None + timeout_ms: int = 60_000 + + def __post_init__(self) -> None: + # The type itself enforces the login rule, so no construction path can + # hand MT5 True or a float that it would turn into another account. + if parse_login(self.login) != self.login: + raise ValueError(f"login must be a positive integer, got {self.login!r}") + + +def parse_login(login: object) -> int | None: + """Account number from an int-like value or an ASCII digit string, else None. + + int() is deliberately avoided: int(True) == 1 and int(12345678.9) == 12345678 + would log into another account without any error, and int() accepts + non-ASCII digits such as "\u0661\u0662\u0663". + """ + if isinstance(login, bool): + return None + if isinstance(login, str): + text = login.strip() + number = int(text) if text.isascii() and text.isdecimal() else 0 + else: + try: + number = operator.index(login) # type: ignore[arg-type] + except TypeError: + return None + return number if number > 0 else None + + +class Terminal(Protocol): + def connect(self, credentials: Credentials) -> Result[None, TradeError]: ... + + def shutdown(self) -> None: ... + + def symbol(self, name: str) -> Result[SymbolSpec, TradeError]: ... + + def tick(self, name: str) -> Result[Tick, TradeError]: ... + + def send(self, request: OrderRequest | CancelRequest) -> Result[TradeReceipt, TradeError]: + """Err only when the request could not be delivered; broker refusals are receipts.""" + ... + + def positions( + self, *, symbol: str | None = None, ticket: int | None = None + ) -> Result[list[Position], TradeError]: ... + + def pending_orders( + self, *, symbol: str | None = None + ) -> Result[list[PendingOrder], TradeError]: ... + + +class Clock(Protocol): + def sleep(self, seconds: float) -> None: ... diff --git a/src/PythonMetaTrader5/application/trader.py b/src/PythonMetaTrader5/application/trader.py new file mode 100644 index 0000000..2cd5add --- /dev/null +++ b/src/PythonMetaTrader5/application/trader.py @@ -0,0 +1,226 @@ +"""Trading use cases: open, close, place and cancel orders, query state.""" + +from __future__ import annotations + +from dataclasses import replace +from types import TracebackType + +from PythonMetaTrader5.application.batch import BatchFailure, run_batch, with_magic +from PythonMetaTrader5.application.entries import StopInput, validate_entry +from PythonMetaTrader5.application.execution import RetryPolicy, execute +from PythonMetaTrader5.application.ports import Clock, Terminal +from PythonMetaTrader5.domain.errors import TradeError +from PythonMetaTrader5.domain.inputs import symbol_filter, ticket_filter +from PythonMetaTrader5.domain.market import PendingKind, PendingOrder, Position, TradeReceipt +from PythonMetaTrader5.domain.orders import Side, validate_comment +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest +from PythonMetaTrader5.domain.symbol import SymbolSpec +from PythonMetaTrader5.result import Err, Ok, Result + + +class Trader: + def __init__( + self, + terminal: Terminal, + clock: Clock, + *, + magic: int = 0, + deviation: int = 10, + retry: RetryPolicy | None = None, + ) -> None: + self._terminal = terminal + self._clock = clock + self._magic = magic + self._deviation = deviation + self._retry = retry or RetryPolicy() + + # ------------------------------------------------------------------ entries + + def open_position( + self, + symbol: str, + side: Side | str, + volume: float, + *, + sl: StopInput = None, + tp: StopInput = None, + price: float | None = None, + comment: str | None = None, + ) -> Result[TradeReceipt, TradeError]: + """Open a market position; ``sl``/``tp`` floats are prices, ``Stop.points`` distances. + + Without ``price`` the current quote is used and requotes are retried with a + fresh quote. An explicit ``price`` is sent once: re-sending the same price + after a requote cannot succeed. + """ + entry = validate_entry( + self._terminal, symbol, side, volume, comment=comment, sl=sl, tp=tp, price=price + ) + if isinstance(entry, Err): + return entry + e = entry.value + + def build() -> Result[OrderRequest | CancelRequest, TradeError]: + quote = None + if e.price is None: + tick = self._terminal.tick(symbol) + if isinstance(tick, Err): + return tick + quote = tick.value.entry_price(e.side) + return e.request(quote, pending=None, deviation=self._deviation, magic=self._magic) + + policy = self._retry if e.price is None else replace(self._retry, attempts=1) + return execute(self._terminal, self._clock, build, policy) + + def place_limit_order( + self, + symbol: str, + side: Side | str, + volume: float, + price: float, + *, + sl: StopInput = None, + tp: StopInput = None, + comment: str | None = None, + ) -> Result[TradeReceipt, TradeError]: + """Place a BUY/SELL LIMIT at ``price``; point stops are measured from that level. + + A limit on the wrong side of the market is refused by the server + (INVALID_PRICE) rather than converted into a market order. + """ + entry = validate_entry( + self._terminal, + symbol, + side, + volume, + comment=comment, + sl=sl, + tp=tp, + price=price, + price_required=True, + ) + if isinstance(entry, Err): + return entry + request = entry.value.request( + pending=PendingKind.LIMIT, deviation=self._deviation, magic=self._magic + ) + if isinstance(request, Err): + return request + return execute(self._terminal, self._clock, lambda: request, self._retry) + + # ------------------------------------------------------------------- exits + + def close_positions( + self, + symbol: str | None = None, + *, + ticket: int | None = None, + magic: int | None = None, + comment: str | None = None, + ) -> Result[list[TradeReceipt], BatchFailure]: + """Close matching positions; ``ticket`` takes precedence over ``symbol``. + + With neither ``symbol``, ``ticket`` nor ``magic`` this closes EVERY position + on the account, manual ones included. Pass ``magic`` to touch only your own. + """ + text = validate_comment(comment) + if isinstance(text, Err): + return Err(BatchFailure((), (text.error,))) + listed = self.positions(None if ticket is not None else symbol, ticket=ticket, magic=magic) + if isinstance(listed, Err): + return Err(BatchFailure((), (listed.error,))) + # One spec lookup per symbol, not per position: close-all is time-critical. + specs: dict[str, Result[SymbolSpec, TradeError]] = {} + + def close(position: Position) -> Result[TradeReceipt, TradeError]: + if position.symbol not in specs: + specs[position.symbol] = self._terminal.symbol(position.symbol) + return self._close_one(position, specs[position.symbol], text.value) + + return run_batch(listed.value, close) + + def cancel_pending_orders( + self, + symbol: str | None = None, + *, + magic: int | None = None, + kind: PendingKind | None = None, + ) -> Result[list[TradeReceipt], BatchFailure]: + listed = self.pending_orders(symbol, magic=magic, kind=kind) + if isinstance(listed, Err): + return Err(BatchFailure((), (listed.error,))) + return run_batch(listed.value, self._cancel_one) + + # ----------------------------------------------------------------- queries + + def positions( + self, symbol: str | None = None, *, ticket: int | None = None, magic: int | None = None + ) -> Result[list[Position], TradeError]: + for check in (symbol_filter(symbol), ticket_filter(ticket)): + if isinstance(check, Err): + return check + listed = self._terminal.positions(symbol=symbol, ticket=ticket) + return listed if isinstance(listed, Err) else Ok(with_magic(listed.value, magic)) + + def pending_orders( + self, + symbol: str | None = None, + *, + magic: int | None = None, + kind: PendingKind | None = None, + ) -> Result[list[PendingOrder], TradeError]: + checked = symbol_filter(symbol) + if isinstance(checked, Err): + return checked + listed = self._terminal.pending_orders(symbol=symbol) + if isinstance(listed, Err): + return listed + orders = with_magic(listed.value, magic) + return Ok(orders if kind is None else [o for o in orders if o.kind is kind]) + + def shutdown(self) -> None: + self._terminal.shutdown() + + def __enter__(self) -> Trader: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.shutdown() + + # ----------------------------------------------------------------- helpers + + def _close_one( + self, position: Position, spec: Result[SymbolSpec, TradeError], comment: str + ) -> Result[TradeReceipt, TradeError]: + if isinstance(spec, Err): + return spec + filling = spec.value.market_filling() + + def build() -> Result[OrderRequest | CancelRequest, TradeError]: + tick = self._terminal.tick(position.symbol) + if isinstance(tick, Err): + return tick + return Ok( + OrderRequest( + symbol=position.symbol, + side=position.side.opposite, + volume=position.volume, + price=tick.value.exit_price(position.side), + filling=filling, + deviation=self._deviation, + magic=self._magic, + comment=comment, + position=position.ticket, + ) + ) + + return execute(self._terminal, self._clock, build, self._retry) + + def _cancel_one(self, order: PendingOrder) -> Result[TradeReceipt, TradeError]: + request = CancelRequest(order=order.ticket) + return execute(self._terminal, self._clock, lambda: Ok(request), self._retry) diff --git a/src/PythonMetaTrader5/connection.py b/src/PythonMetaTrader5/connection.py new file mode 100644 index 0000000..f01cc8a --- /dev/null +++ b/src/PythonMetaTrader5/connection.py @@ -0,0 +1,48 @@ +"""Composition root: wires the real adapters into a Trader.""" + +from __future__ import annotations + +import logging + +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.adapters.system_clock import SystemClock +from PythonMetaTrader5.application.execution import RetryPolicy +from PythonMetaTrader5.application.ports import Credentials, parse_login +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.result import Err, Ok, Result + +log = logging.getLogger("PythonMetaTrader5") + + +def connect( + login: int | str, + password: str, + server: str, + *, + path: str | None = None, + timeout_ms: int = 60_000, + magic: int = 0, + deviation: int = 10, + retry: RetryPolicy | None = None, +) -> Result[Trader, TradeError]: + """Start (or attach to) the MT5 terminal, log in, and return a ready Trader.""" + account = parse_login(login) + if account is None: + return Err( + TradeError( + ErrorKind.INVALID_ARGUMENT, f"login must be a positive integer, got {login!r}" + ) + ) + loaded = MetaTrader5Terminal.load() + if isinstance(loaded, Err): + return loaded + terminal = loaded.value + credentials = Credentials(account, str(password), str(server), path, timeout_ms) + connected = terminal.connect(credentials) + if isinstance(connected, Err): + return connected + # Login and server only: account_info() also carries the owner's name and + # balance, which do not belong in application logs. + log.info("connected to %s as %s", server, account) + return Ok(Trader(terminal, SystemClock(), magic=magic, deviation=deviation, retry=retry)) diff --git a/src/PythonMetaTrader5/domain/__init__.py b/src/PythonMetaTrader5/domain/__init__.py new file mode 100644 index 0000000..532eb87 --- /dev/null +++ b/src/PythonMetaTrader5/domain/__init__.py @@ -0,0 +1 @@ +"""Pure trading rules: no I/O, no MetaTrader5 import.""" diff --git a/src/PythonMetaTrader5/domain/amounts.py b/src/PythonMetaTrader5/domain/amounts.py new file mode 100644 index 0000000..84c53cf --- /dev/null +++ b/src/PythonMetaTrader5/domain/amounts.py @@ -0,0 +1,33 @@ +"""The one rule for "a positive finite number", shared by Stop and the input checks.""" + +from __future__ import annotations + +import math +from decimal import Decimal +from numbers import Real + + +def positive_float(value: object, *, unsigned: bool = False) -> float | None: + """``value`` as a positive finite float, or None when it is not one. + + numbers.Real rather than float, so numpy scalars from pandas-based bots + pass, plus Decimal (not a Real) for bots that keep money as Decimal. bool + is excluded because it is a Real (True == 1) and would trade one lot. + NaN Decimals are refused before float(): float(Decimal("sNaN")) raises. + ``unsigned`` drops the sign first (a distance), after the NaN check, because + abs(Decimal("sNaN")) raises too. + """ + if isinstance(value, bool) or not isinstance(value, (Real, Decimal)): + return None + if isinstance(value, Decimal) and value.is_nan(): + return None + try: + number = abs(float(value)) if unsigned else float(value) + except ArithmeticError: + # None rather than raising: a number outside float range (10**400, or a + # numpy longdouble under np.seterr(over="raise")) is bad input like NaN, + # and raising would break the Result boundary. ValueError/TypeError are + # not caught: they are bugs in the caller's own type and must keep + # their traceback. + return None + return number if math.isfinite(number) and number > 0 else None diff --git a/src/PythonMetaTrader5/domain/errors.py b/src/PythonMetaTrader5/domain/errors.py new file mode 100644 index 0000000..980ca33 --- /dev/null +++ b/src/PythonMetaTrader5/domain/errors.py @@ -0,0 +1,53 @@ +"""Typed failure vocabulary shared by every layer.""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from PythonMetaTrader5.domain.market import TradeReceipt + + +class ErrorKind(Enum): + INVALID_ARGUMENT = "invalid_argument" + INVALID_VOLUME = "invalid_volume" + INVALID_PRICE = "invalid_price" + INVALID_STOPS = "invalid_stops" + INVALID_FILLING = "invalid_filling" + NO_MONEY = "no_money" + MARKET_CLOSED = "market_closed" + TRADE_DISABLED = "trade_disabled" + ALGO_TRADING_DISABLED = "algo_trading_disabled" + LIMIT_REACHED = "limit_reached" + # Only part of the volume was executed; the rest is still open/unfilled. + PARTIAL_FILL = "partial_fill" + # The request may or may not have reached the trade server: never auto-retried. + OUTCOME_UNKNOWN = "outcome_unknown" + RETRIES_EXHAUSTED = "retries_exhausted" + REJECTED = "rejected" + SYMBOL_NOT_FOUND = "symbol_not_found" + NO_PRICE = "no_price" + 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. + BROKEN_SYMBOL_DATA = "broken_symbol_data" + CONNECTION_FAILED = "connection_failed" + + +@dataclass(frozen=True, slots=True) +class TradeError: + kind: ErrorKind + message: str + retcode: int | None = None + # Kept so callers (and the 2.x facade) can inspect the broker's raw answer. + receipt: TradeReceipt | None = None + # Set when the failure concerns one position/order of a batch operation. + ticket: int | None = None + + def __str__(self) -> str: + code = f" (retcode {self.retcode})" if self.retcode is not None else "" + ticket = f" [ticket {self.ticket}]" if self.ticket is not None else "" + return f"{self.kind.value}: {self.message}{code}{ticket}" diff --git a/src/PythonMetaTrader5/domain/inputs.py b/src/PythonMetaTrader5/domain/inputs.py new file mode 100644 index 0000000..27533fc --- /dev/null +++ b/src/PythonMetaTrader5/domain/inputs.py @@ -0,0 +1,55 @@ +"""Checks on raw caller input that MT5 would otherwise misread without an error. + +Webhook payloads arrive as loosely typed JSON. Each value below has a reading +in MT5 that is valid but almost never meant: ``sl=0`` is "no stop", +``ticket=0`` may be "no filter", ``volume=True`` is one lot. They are refused +here instead of being passed on. +""" + +from __future__ import annotations + +from dataclasses import replace +from numbers import Integral + +from PythonMetaTrader5.domain.amounts import positive_float +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.stops import Stop, StopKind +from PythonMetaTrader5.result import Err, Ok, Result + + +def positive_number(value: object, kind: ErrorKind, what: str) -> Result[float, TradeError]: + number = positive_float(value) + if number is None: + return Err(TradeError(kind, f"{what} must be a positive finite number, got {value!r}")) + return Ok(number) + + +def stop_input(value: object, what: str) -> Result[Stop | None, TradeError]: + """``None`` means no stop; a float is a price; zero is refused, never "no stop".""" + if value is None or isinstance(value, Stop): + return Ok(value) # a Stop validated itself when it was built + parsed = Stop.parse(value, StopKind.PRICE) + if isinstance(parsed, Err): + return Err(replace(parsed.error, message=f"{what}: {parsed.error.message}")) + return Ok(parsed.value) + + +def ticket_filter(ticket: object) -> Result[int | None, TradeError]: + if ticket is None: + return Ok(None) + if isinstance(ticket, bool) or not isinstance(ticket, Integral) or ticket <= 0: + return Err( + TradeError( + ErrorKind.INVALID_ARGUMENT, f"ticket must be a positive integer, got {ticket!r}" + ) + ) + return Ok(int(ticket)) + + +def symbol_filter(symbol: str | None) -> Result[str | None, TradeError]: + # "" is rejected rather than passed on: a missing webhook field arrives as "" + # and is easily mistaken for "no filter" (2.x and the first 3.0 draft both + # dropped falsy filters), which would act on the whole account. + if symbol == "": + return Err(TradeError(ErrorKind.INVALID_ARGUMENT, "symbol must not be empty")) + return Ok(symbol) diff --git a/src/PythonMetaTrader5/domain/market.py b/src/PythonMetaTrader5/domain/market.py new file mode 100644 index 0000000..a3e02fe --- /dev/null +++ b/src/PythonMetaTrader5/domain/market.py @@ -0,0 +1,91 @@ +"""Read models returned by the terminal: quotes, positions, orders, receipts.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from enum import Enum +from typing import Any + +from PythonMetaTrader5.domain.orders import Side + + +@dataclass(frozen=True, slots=True) +class Tick: + bid: float + ask: float + + def entry_price(self, side: Side) -> float: + return self.ask if side is Side.BUY else self.bid + + def exit_price(self, side: Side) -> float: + # 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: + ticket: int + symbol: str + side: Side + volume: float + price_open: float + sl: float | None + tp: float | None + price_current: float + profit: float + time: int + magic: int + comment: str + # Kept although the 3.x API does not use them: 2.x returned the raw MT5 + # object, so its users may read any of them (swap for P&L, identifier on + # netting accounts). + swap: float + identifier: int + reason: int + time_msc: int + time_update: int + time_update_msc: int + external_id: str + + def to_dict(self) -> dict[str, Any]: + data = asdict(self) + data["side"] = self.side.value + return data + + +class PendingKind(Enum): + LIMIT = "limit" + STOP = "stop" + STOP_LIMIT = "stop_limit" + + +@dataclass(frozen=True, slots=True) +class PendingOrder: + ticket: int + symbol: str + side: Side + kind: PendingKind + volume: float + price: float + magic: int + comment: str + + +@dataclass(frozen=True, slots=True) +class TradeReceipt: + """Broker answer to a trade request. + + Field names mirror MetaTrader5's ``OrderSendResult`` on purpose, so 2.x code + reading ``result.retcode`` / ``result.comment`` keeps working unchanged. + """ + + retcode: int + deal: int + order: int + volume: float + price: float + bid: float + ask: float + comment: str + request_id: int + retcode_external: int diff --git a/src/PythonMetaTrader5/domain/orders.py b/src/PythonMetaTrader5/domain/orders.py new file mode 100644 index 0000000..338dd2d --- /dev/null +++ b/src/PythonMetaTrader5/domain/orders.py @@ -0,0 +1,51 @@ +"""Trade direction and the order requests sent through the terminal port.""" + +from __future__ import annotations + +from enum import Enum + +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.result import Err, Ok, Result + +_SIDE_ALIASES = {"buy": "BUY", "long": "BUY", "sell": "SELL", "short": "SELL"} + + +class Side(Enum): + BUY = "buy" + SELL = "sell" + + @property + def opposite(self) -> Side: + return Side.SELL if self is Side.BUY else Side.BUY + + @property + def sign(self) -> int: + return 1 if self is Side.BUY else -1 + + @classmethod + def parse(cls, value: Side | str) -> Result[Side, TradeError]: + if isinstance(value, Side): + return Ok(value) + name = _SIDE_ALIASES.get(str(value).strip().lower()) + if name is None: + return Err( + TradeError(ErrorKind.INVALID_ARGUMENT, f"unknown side {value!r}; use buy/sell") + ) + return Ok(cls[name]) + + +# The terminal stores at most 31 characters and answers longer comments with an +# "Invalid comment argument" error instead of trimming them. +MAX_COMMENT_LENGTH = 31 + + +def validate_comment(comment: str | None) -> Result[str, TradeError]: + text = comment or "" + if len(text) > MAX_COMMENT_LENGTH: + return Err( + TradeError( + ErrorKind.INVALID_ARGUMENT, + f"comment is {len(text)} characters; the terminal accepts {MAX_COMMENT_LENGTH}", + ) + ) + return Ok(text) diff --git a/src/PythonMetaTrader5/domain/requests.py b/src/PythonMetaTrader5/domain/requests.py new file mode 100644 index 0000000..fe903eb --- /dev/null +++ b/src/PythonMetaTrader5/domain/requests.py @@ -0,0 +1,32 @@ +"""Trade requests in domain terms; the terminal adapter translates them to MT5.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from PythonMetaTrader5.domain.market import PendingKind +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.symbol import Filling + + +@dataclass(frozen=True, slots=True) +class OrderRequest: + symbol: str + side: Side + volume: float + price: float + filling: Filling + deviation: int + magic: int + comment: str = "" + sl: float | None = None + tp: float | None = None + # Ticket of the position being closed; None opens a new position. + position: int | None = None + # None means a market deal; a kind means a pending order at `price`. + pending: PendingKind | None = None + + +@dataclass(frozen=True, slots=True) +class CancelRequest: + order: int diff --git a/src/PythonMetaTrader5/domain/retcodes.py b/src/PythonMetaTrader5/domain/retcodes.py new file mode 100644 index 0000000..573a103 --- /dev/null +++ b/src/PythonMetaTrader5/domain/retcodes.py @@ -0,0 +1,81 @@ +"""What a MetaTrader 5 trade-server return code means for the caller. + +Codes are integers from the MQL5 "Trade Server Return Codes" table; they are +duplicated here so the domain never imports the MetaTrader5 package. +""" + +from __future__ import annotations + +from enum import Enum + +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError + + +class Outcome(Enum): + SUCCESS = "success" + RETRY = "retry" + FAIL = "fail" + + +# PLACED is how the server confirms a pending order; 2.x only accepted DONE and +# therefore re-sent limit orders that had already been placed. +PLACED = 10008 +DONE = 10009 +DONE_PARTIAL = 10010 +_SUCCESS = frozenset({PLACED, DONE, DONE_PARTIAL}) + +# Only codes where the server provably did NOT execute the request. TIMEOUT and +# CONNECTION are deliberately absent: the order may already be live, and an +# automatic retry would open a second position. +_RETRY = frozenset({10004, 10020, 10021, 10024}) + +_FAILURES: dict[int, tuple[ErrorKind, str]] = { + 10004: (ErrorKind.REJECTED, "requote"), + 10006: (ErrorKind.REJECTED, "request rejected by the server"), + 10007: (ErrorKind.REJECTED, "request cancelled by the trader"), + 10011: (ErrorKind.REJECTED, "request processing error"), + 10012: (ErrorKind.OUTCOME_UNKNOWN, "request timed out; check positions before retrying"), + 10013: (ErrorKind.INVALID_ARGUMENT, "invalid request"), + 10014: (ErrorKind.INVALID_VOLUME, "invalid volume"), + 10015: (ErrorKind.INVALID_PRICE, "invalid price"), + 10016: (ErrorKind.INVALID_STOPS, "invalid stops; too close to the price or wrong side"), + 10017: (ErrorKind.TRADE_DISABLED, "trading is disabled"), + 10018: (ErrorKind.MARKET_CLOSED, "market is closed"), + 10019: (ErrorKind.NO_MONEY, "not enough money"), + 10020: (ErrorKind.REJECTED, "prices changed"), + 10021: (ErrorKind.NO_PRICE, "no quotes to process the request"), + 10022: (ErrorKind.INVALID_ARGUMENT, "invalid order expiration"), + 10024: (ErrorKind.REJECTED, "too many requests"), + 10026: (ErrorKind.ALGO_TRADING_DISABLED, "autotrading disabled by the server"), + 10027: (ErrorKind.ALGO_TRADING_DISABLED, "enable Algo Trading in the MetaTrader 5 terminal"), + 10028: (ErrorKind.REJECTED, "request locked for processing"), + 10029: (ErrorKind.REJECTED, "order or position frozen"), + 10030: (ErrorKind.INVALID_FILLING, "filling mode not supported by the symbol"), + 10031: (ErrorKind.OUTCOME_UNKNOWN, "no connection to the trade server; check positions"), + 10032: (ErrorKind.TRADE_DISABLED, "operation allowed only on live accounts"), + 10033: (ErrorKind.LIMIT_REACHED, "pending orders limit reached"), + 10034: (ErrorKind.LIMIT_REACHED, "volume limit for the symbol reached"), + 10035: (ErrorKind.INVALID_ARGUMENT, "invalid or prohibited order type"), + 10036: (ErrorKind.REJECTED, "position already closed"), + 10038: (ErrorKind.INVALID_VOLUME, "close volume exceeds position volume"), + 10039: (ErrorKind.REJECTED, "a close order for this position already exists"), + 10040: (ErrorKind.LIMIT_REACHED, "open positions limit reached"), + 10041: (ErrorKind.REJECTED, "pending order activation rejected"), + 10042: (ErrorKind.TRADE_DISABLED, "only long positions are allowed"), + 10043: (ErrorKind.TRADE_DISABLED, "only short positions are allowed"), + 10044: (ErrorKind.TRADE_DISABLED, "only position closing is allowed"), + 10045: (ErrorKind.REJECTED, "FIFO rule: close older positions first"), +} + + +def classify(retcode: int) -> Outcome: + if retcode in _SUCCESS: + return Outcome.SUCCESS + if retcode in _RETRY: + return Outcome.RETRY + return Outcome.FAIL + + +def error_for(retcode: int) -> TradeError: + kind, message = _FAILURES.get(retcode, (ErrorKind.REJECTED, "unrecognised server retcode")) + return TradeError(kind, message, retcode=retcode) diff --git a/src/PythonMetaTrader5/domain/stops.py b/src/PythonMetaTrader5/domain/stops.py new file mode 100644 index 0000000..6e7d3df --- /dev/null +++ b/src/PythonMetaTrader5/domain/stops.py @@ -0,0 +1,85 @@ +"""Stop-loss / take-profit given either as a price or as a distance in points.""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum + +from PythonMetaTrader5.domain.amounts import positive_float +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.symbol import SymbolSpec +from PythonMetaTrader5.result import Err, Ok, Result + + +class StopKind(Enum): + PRICE = "price" + POINTS = "points" + + +@dataclass(frozen=True, slots=True) +class Stop: + value: float + kind: StopKind + + def __post_init__(self) -> None: + # The invariant lives here, so every Stop is valid wherever it is built. + # Raised, not returned: a Stop of 0 cannot exist (MT5 would read it as "no + # stop"). Code holding a value that may be bad (an ATR that is NaN during + # warm-up) uses Stop.parse, which returns a Result instead. + parsed = _checked(self.value, self.kind) + if isinstance(parsed, Err): + raise ValueError(parsed.error.message) + object.__setattr__(self, "value", parsed.value) + + @classmethod + def parse(cls, value: object, kind: StopKind) -> Result[Stop, TradeError]: + checked = _checked(value, kind) + if isinstance(checked, Err): + return checked + return Ok(cls(checked.value, kind)) + + @classmethod + def at_price(cls, price: float) -> Stop: + return cls(price, StopKind.PRICE) + + @classmethod + def points(cls, distance: float) -> Stop: + return cls(distance, StopKind.POINTS) + + def stop_loss( + self, side: Side, reference: float, spec: SymbolSpec + ) -> Result[float, TradeError]: + return self._resolve(-side.sign, reference, spec, "sl") + + def take_profit( + self, side: Side, reference: float, spec: SymbolSpec + ) -> Result[float, TradeError]: + return self._resolve(side.sign, reference, spec, "tp") + + def _resolve( + self, direction: int, reference: float, spec: SymbolSpec, what: str + ) -> Result[float, TradeError]: + # Resolved without a sign check here: price_on_grid is the single place a + # level below zero (a long points distance) or off the grid is refused. + level = self.value + if self.kind is StopKind.POINTS: + distance = spec.points_to_price(self.value) + if isinstance(distance, Err): + return distance + level = reference + direction * distance.value + return spec.price_on_grid(level, ErrorKind.INVALID_STOPS, what) + + +def _checked(value: object, kind: StopKind) -> Result[float, TradeError]: + # A wrong kind is a programming error, raised for every value alike (also by + # Stop.parse), rather than read as a price. + if not isinstance(kind, StopKind): + raise TypeError(f"kind must be a StopKind, got {kind!r}") + # A points distance drops its sign: direction comes from the trade side, so + # `-1000` and `1000` both mean "1000 points on the losing side". + number = positive_float(value, unsigned=kind is StopKind.POINTS) + if number is None: + message = f"{kind.value} stop must be a positive finite number, got {value!r}" + return Err(TradeError(ErrorKind.INVALID_STOPS, message)) + return Ok(number) diff --git a/src/PythonMetaTrader5/domain/symbol.py b/src/PythonMetaTrader5/domain/symbol.py new file mode 100644 index 0000000..f457dc3 --- /dev/null +++ b/src/PythonMetaTrader5/domain/symbol.py @@ -0,0 +1,158 @@ +"""Instrument specification and the rules that depend only on it.""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from enum import Enum + +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.result import Err, Ok, Result + +# Bit flags of SYMBOL_FILLING_MODE as documented in MQL5. The Python package does +# not export them, so they are defined here rather than guessed at call sites. +_FILLING_FOK_FLAG = 1 +_FILLING_IOC_FLAG = 2 + +# Tolerances for float checks: volumes are entered as decimal literals (0.07) +# that are not exactly representable in binary floating point, so an exact +# comparison would reject valid lots. +_EPSILON = 1e-9 +_STEP_TOLERANCE = 1e-6 +# Volume precision sent to the server; well below any broker's volume_step. +_VOLUME_DECIMALS = 8 + + +class Filling(Enum): + FOK = "fok" + IOC = "ioc" + RETURN = "return" + + +@dataclass(frozen=True, slots=True) +class SymbolSpec: + name: str + digits: int + point: float + tick_size: float + volume_min: float + volume_max: float + volume_step: float + filling_flags: int + # Required on purpose: a default would quietly treat an exchange symbol as + # market execution and send limits that cancel instead of resting. + exchange_execution: bool + + # Broken terminal data (a point of 0 or inf, a NaN tick size, a volume step + # of 0) is reported as BROKEN_SYMBOL_DATA: it is the broker's fault, so a bot + # must not file it as a bad signal, nor resend as after a TERMINAL_ERROR. + # It is checked on use rather than refused for the whole spec, because + # closing a position needs only filling_flags and must keep working on such + # a symbol (a constructor invariant was tried and dropped for exactly that). + # Entries call check_tradable() first. + + def check_tradable(self) -> Result[None, TradeError]: + problem = self._pricing_problem() or self._volume_problem() + return Ok(None) if problem is None else Err(self._data_error(problem)) + + def price_on_grid(self, price: float, kind: ErrorKind, what: str) -> Result[float, TradeError]: + """``price`` on the tick grid, refused if it is not a usable positive level. + + Every caller-supplied level (an explicit entry price, sl, tp) goes through + here; quote prices come from the terminal already on the grid. The two + ways a positive finite input still goes wrong are checked once: 1e305 / + 1e-5 overflows to inf (round(inf) raises), and 1e-6 snaps to 0.0, which + MT5 reads as "no stop" or "fill at the market". + """ + problem = self._pricing_problem() + if problem is not None: + return Err(self._data_error(problem)) + # A price must sit on the tick grid, not merely have `digits` decimals: + # index CFDs often have tick 0.25 with 2 digits and reject 5780.13. + step = self._step + if not math.isfinite(price / step): + return Err(TradeError(kind, f"{what} {price} is out of range for {self.name}")) + level = round(round(price / step) * step, self.digits) + if level <= 0: + return Err(TradeError(kind, f"{what} {price} snaps to {level} on {self.name}")) + return Ok(level) + + def points_to_price(self, points: float) -> Result[float, TradeError]: + # Only points stops need `point`: a symbol with a valid tick size and a + # point of 0 still trades absolute prices. + if not _usable(self.point): + return Err(self._data_error(f"point {self.point!r} cannot measure a points stop")) + return Ok(points * self.point) + + def validate_volume(self, volume: float) -> Result[float, TradeError]: + problem = self._volume_problem() + if problem is not None: + return Err(self._data_error(problem)) + if volume < self.volume_min - _EPSILON or volume > self.volume_max + _EPSILON: + return Err(self._volume_error(volume, "outside")) + steps = (volume - self.volume_min) / self.volume_step + if abs(steps - round(steps)) > _STEP_TOLERANCE: + return Err(self._volume_error(volume, "not a multiple of the step within")) + snapped = self.volume_min + round(steps) * self.volume_step + return Ok(round(snapped, _VOLUME_DECIMALS)) + + @property + def _step(self) -> float: + # A tick size of 0 means the terminal did not report one; point is used. + return self.tick_size if self.tick_size > 0 else self.point + + def _pricing_problem(self) -> str | None: + # Checked before _step is used: a NaN or negative tick size would + # otherwise fall back to point without anyone noticing. + if not (self.tick_size == 0 or _usable(self.tick_size)): + return f"tick size {self.tick_size!r} is neither 0 nor positive and finite" + if not _usable(self._step): + return f"no usable tick size or point (point {self.point!r})" + if self.digits < 0: + return f"digits {self.digits} is negative" + return None + + def _volume_problem(self) -> str | None: + limits = (self.volume_min, self.volume_max, self.volume_step) + if not all(_usable(x) for x in limits): + return f"volume min/max/step {limits} are not all positive and finite" + if self.volume_max < self.volume_min: + return f"volume_max {self.volume_max} is below volume_min {self.volume_min}" + return None + + def _data_error(self, problem: str) -> TradeError: + return TradeError(ErrorKind.BROKEN_SYMBOL_DATA, f"{self.name}: {problem}") + + def market_filling(self) -> Filling: + # FOK first: a webhook bot asking for 1 lot must get 1 lot or nothing. + # IOC could silently leave it with a partial fill it never asked for. + if self.filling_flags & _FILLING_FOK_FLAG: + return Filling.FOK + if self.filling_flags & _FILLING_IOC_FLAG: + return Filling.IOC + return Filling.RETURN + + def pending_filling(self) -> Filling: + # Exchange-execution symbols (stocks, futures) only let a limit rest in the + # book with RETURN; FOK/IOC there would cancel it unless instantly fillable. + # Elsewhere the market rule applies: RETURN is refused by many + # market-execution brokers (10030) that accepted the IOC sent by 2.x. + return Filling.RETURN if self.exchange_execution else self.market_filling() + + def _volume_error(self, volume: float, reason: str) -> TradeError: + return TradeError( + ErrorKind.INVALID_VOLUME, + f"{self.name}: volume {volume} is {reason} " + f"[{self.volume_min}, {self.volume_max}] step {self.volume_step}", + ) + + +def _usable(value: float) -> bool: + # The type check keeps a hand-built spec (point=None, point=True) on the + # Result path instead of raising TypeError from math.isfinite. + return ( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(value) + and value > 0 + ) diff --git a/src/PythonMetaTrader5/legacy/__init__.py b/src/PythonMetaTrader5/legacy/__init__.py new file mode 100644 index 0000000..7a1e60f --- /dev/null +++ b/src/PythonMetaTrader5/legacy/__init__.py @@ -0,0 +1 @@ +"""Deprecated 2.x API kept so existing scripts run unchanged on 3.x.""" diff --git a/src/PythonMetaTrader5/legacy/arguments.py b/src/PythonMetaTrader5/legacy/arguments.py new file mode 100644 index 0000000..167fc5c --- /dev/null +++ b/src/PythonMetaTrader5/legacy/arguments.py @@ -0,0 +1,52 @@ +"""2.x argument conventions translated into 3.x values. + +Split out of broker.py (300-line limit); everything here is pure. +""" + +from __future__ import annotations + +import logging +from typing import Any + +from PythonMetaTrader5.domain.stops import Stop, StopKind +from PythonMetaTrader5.result import Err, Ok, Result + +log = logging.getLogger("PythonMetaTrader5.legacy") + + +def number(value: Any) -> Any: + """Convert numeric strings with float() as 2.x did, raising on garbage as it did. + + Only strings are converted: float(True) would turn a stray bool into one + lot, so every other type goes on unchanged and is checked by the Trader. + """ + return float(value) if isinstance(value, str) else value + + +def legacy_stop(value: Any, kind: str) -> Result[Stop | None, str]: + if value is None: + return Ok(None) + match (kind or "absolute").lower(): + case "absolute": + stop_kind = StopKind.PRICE + case "offset": + stop_kind = StopKind.POINTS + case other: + # 2.x opened the position with neither SL nor TP here. + log.error("invalid stop type %r (use 'absolute' or 'offset')", other) + return Err(other) + parsed = Stop.parse(value, stop_kind) + if isinstance(parsed, Err): + # sl=0 meant "no stop" to MT5 in 2.x; refusing it beats an unprotected entry. + log.error("%s", parsed.error) + return Err(parsed.error.message) + return Ok(parsed.value) + + +def no_ticket(ticket: int | None) -> bool: + if ticket is None: + return True + # 2.x forwarded it as `position` on an opening deal, which on hedging + # accounts turns an opposite-side entry into a close of that position. + log.error("the ticket argument is not supported for entries; use Close(ticket=...)") + return False diff --git a/src/PythonMetaTrader5/legacy/broker.py b/src/PythonMetaTrader5/legacy/broker.py new file mode 100644 index 0000000..3c04018 --- /dev/null +++ b/src/PythonMetaTrader5/legacy/broker.py @@ -0,0 +1,283 @@ +"""2.x `Broker` facade over the 3.x Trader. + +Names, arguments and return shapes follow 2.x so old scripts keep running. The +behaviour that made 2.x dangerous is NOT preserved: no endless retry loops and +no Ctrl+E keystrokes into whichever window has focus. See MIGRATION.md. +""" + +from __future__ import annotations + +import logging +import warnings +from typing import Any, ClassVar + +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.adapters.system_clock import SystemClock +from PythonMetaTrader5.application.ports import Clock, Credentials, Terminal, parse_login +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.inputs import positive_number +from PythonMetaTrader5.domain.market import PendingKind, TradeReceipt +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.legacy import views +from PythonMetaTrader5.legacy.arguments import legacy_stop, no_ticket, number +from PythonMetaTrader5.legacy.views import LegacyReceipt +from PythonMetaTrader5.result import Err, Ok, Result + +log = logging.getLogger("PythonMetaTrader5.legacy") + +_RELOGIN_DELAY_SECONDS = 1.0 + + +class Broker: + RetCodes: ClassVar[dict[int, str]] = { + 10027: "Enable Algo Trading in MetaTrader5 app", + 10018: "Market closed", + 10016: "Wrong SL", + } + + def __init__( + self, + log: int | str, + password: Any, + server: Any, + *, + terminal: Terminal | None = None, + clock: Clock | None = None, + ) -> None: + warnings.warn( + "Broker is deprecated; use PythonMetaTrader5.connect() (see MIGRATION.md)", + DeprecationWarning, + stacklevel=2, + ) + self.log = log + self.server = str(server) + account = parse_login(log) + if account is None: + # Programming error, raised as 2.x did for non-numeric logins; silently + # coercing True or 12345678.9 would trade on another account. + raise ValueError(f"login must be a positive integer, got {log!r}") + self._credentials = Credentials(account, str(password), self.server) + self._clock = clock or SystemClock() + self._terminal = terminal or _load_terminal() + self._trader = Trader(self._terminal, self._clock) if self._terminal else None + self._connected = self.login() + + def login(self, ToEffect: bool = False) -> bool: + """Log in once, or keep trying every second until it works when ``ToEffect``.""" + if self._terminal is None: + return False + while True: + result = self._terminal.connect(self._credentials) + if isinstance(result, Ok): + log.info("%s: logged in to %s", self.log, self.server) + self._connected = True + return True + # The adapter released the session, so nothing may trade until a login works. + self._connected = False + log.error("%s: %s", self.log, result.error) + if not ToEffect: + return False + self._clock.sleep(_RELOGIN_DELAY_SECONDS) + + # ---------------------------------------------------------------- queries + + def GetPositionsBySymbol(self, symbol: str, as_dict: bool = False) -> list[Any]: + return self.GetPositions(symbol, as_dict=as_dict) + + def GetPositions( + self, symbol: str | None = None, *, ticket: int | None = None, as_dict: bool = False + ) -> list[Any]: + trader = self._ready() + if trader is None: + return [] + # 2.x: a ticket selects that position whatever symbol was passed. + listed = trader.positions(None if ticket is not None else symbol, ticket=ticket) + if isinstance(listed, Err): + log.error("%s: %s", self.log, listed.error) + return [] + convert = views.as_dict if as_dict else views.as_object + return [convert(p) for p in listed.value] + + def GetPosition( + self, symbol: str | None = None, *, ticket: int | None = None, as_dict: bool = False + ) -> Any: + found = self.GetPositions(symbol, ticket=ticket, as_dict=as_dict) + return found[0] if found else None + + # ---------------------------------------------------------------- entries + + def OpenPosition( + self, + symbol: str, + side: str, + volume: float, + *, + sl: float | None = None, + tp: float | None = None, + price: float | None = None, + comment: str | None = None, + ticket: int | None = None, + sl_type: str = "absolute", + tp_type: str = "absolute", + ) -> LegacyReceipt | None: + trader = self._ready() + if trader is None or not no_ticket(ticket): + return None + stops = legacy_stop(number(sl), sl_type), legacy_stop(number(tp), tp_type) + if any(isinstance(stop, Err) for stop in stops): + return None + stop_loss, take_profit = (s.value for s in stops if isinstance(s, Ok)) + result = trader.open_position( + symbol, + side, + number(volume), + sl=stop_loss, + tp=take_profit, + price=number(price), + comment=comment, + ) + return self._receipt(result, f"{side} {symbol}") + + def Buy(self, symbol: str, volume: float, price: float | None = None, **kw: Any) -> Any: + return self.OpenPosition(symbol, "buy", volume, price=price, **kw) + + def BuySL( + self, symbol: str, volume: float, sl: float, price: float | None = None, **kw: Any + ) -> Any: + return self.OpenPosition(symbol, "buy", volume, sl=sl, price=price, **kw) + + def Sell(self, symbol: str, volume: float, price: float | None = None, **kw: Any) -> Any: + return self.OpenPosition(symbol, "sell", volume, price=price, **kw) + + def SellSL( + self, symbol: str, volume: float, sl: float, price: float | None = None, **kw: Any + ) -> Any: + return self.OpenPosition(symbol, "sell", volume, sl=sl, price=price, **kw) + + def BuyLimit( + self, + symbol: str, + volume: float, + stoplimit: float, + price: float | None = None, + comment: str | None = None, + ticket: int | None = None, + ) -> LegacyReceipt | None: + return self._limit( + Side.BUY, symbol, volume, stoplimit, price=price, comment=comment, ticket=ticket + ) + + def SellLimit( + self, + symbol: str, + volume: float, + stoplimit: float, + price: float | None = None, + comment: str | None = None, + ticket: int | None = None, + ) -> LegacyReceipt | None: + return self._limit( + Side.SELL, symbol, volume, stoplimit, price=price, comment=comment, ticket=ticket + ) + + # ------------------------------------------------------------------ exits + + def Close( + self, symbol: str | None, *, comment: str | None = None, ticket: int | None = None + ) -> bool: + """True when at least one position closed and none failed.""" + trader = self._ready() + if trader is None: + return False + if symbol is None and ticket is None: + # 2.x crashed here without closing anything; 3.x would close the account. + log.error("%s: Close needs a symbol or ticket", self.log) + return False + result = trader.close_positions(symbol, ticket=ticket, comment=comment) + if isinstance(result, Err): + log.error("%s: closing %s: %s", self.log, symbol, result.error) + return False + if not result.value: + log.info("%s: there are no positions to close on %s", self.log, symbol) + return bool(result.value) + + def CancelOrders(self, symbol: str) -> None: + trader = self._ready() + if trader is None: + return + if not symbol: + # 2.x matched orders against the symbol and so cancelled nothing here. + log.error("%s: CancelOrders needs a symbol", self.log) + return + # 2.x only ever cancelled limit orders; stop orders stay untouched. + result = trader.cancel_pending_orders(symbol, kind=PendingKind.LIMIT) + if isinstance(result, Err): + log.error("%s: cancelling orders on %s: %s", self.log, symbol, result.error) + + def Disconnect(self) -> None: + if self._trader is not None: + self._trader.shutdown() + self._connected = False + log.info("Disconnected from MT5") + + # ---------------------------------------------------------------- helpers + + def _limit( + self, + side: Side, + symbol: str, + volume: float, + stoplimit: float, + *, + price: float | None, + comment: str | None, + ticket: int | None, + ) -> LegacyReceipt | None: + trader = self._ready() + if trader is None or self._terminal is None or not no_ticket(ticket): + return None + volume = number(volume) + if price is not None: + log.error("%s: price has to be None for limit orders", self.log) + return None + # Checked before the crossing test below: a level of 0 always "crosses" + # for a sell and would become a market order. + level = positive_number(number(stoplimit), ErrorKind.INVALID_PRICE, "stoplimit") + if isinstance(level, Err): + log.error("%s: %s", self.log, level.error) + return None + stoplimit = level.value + tick = self._terminal.tick(symbol) + if isinstance(tick, Err): + log.error("%s: %s", self.log, tick.error) + return None + quote = tick.value.entry_price(side) + # 2.x semantics: a limit already reached by the market is filled at market. + crossed = quote <= stoplimit if side is Side.BUY else quote >= stoplimit + if crossed: + result = trader.open_position(symbol, side, volume, comment=comment) + else: + result = trader.place_limit_order(symbol, side, volume, stoplimit, comment=comment) + return self._receipt(result, f"{side.value} limit {symbol} @ {stoplimit}") + + def _ready(self) -> Trader | None: + if self._trader is None or not self._connected: + log.error("%s: not connected to MetaTrader 5; call login()", self.log) + return None + return self._trader + + def _receipt(self, result: Result[TradeReceipt, TradeError], what: str) -> LegacyReceipt | None: + if isinstance(result, Ok): + log.info("%s: %s done", self.log, what) + return views.as_receipt(result.value) + log.error("%s: %s failed: %s", self.log, what, result.error) + return views.as_receipt(result.error.receipt) + + +def _load_terminal() -> Terminal | None: + loaded = MetaTrader5Terminal.load() + if isinstance(loaded, Err): + log.error("%s", loaded.error) + return None + return loaded.value diff --git a/src/PythonMetaTrader5/legacy/mt5_namespace.py b/src/PythonMetaTrader5/legacy/mt5_namespace.py new file mode 100644 index 0000000..7b5bef1 --- /dev/null +++ b/src/PythonMetaTrader5/legacy/mt5_namespace.py @@ -0,0 +1,56 @@ +"""The MetaTrader5 namespace, re-exported lazily for 2.x scripts (ADR 0010). + +2.x ran ``from MetaTrader5 import *`` in its ``__init__``, and its own README +called ``symbol_info("EURUSD")`` after ``from PythonMetaTrader5 import *``. +The package ``__getattr__`` (PEP 562) delegates here, so MetaTrader5 is +imported only when one of its names is first used: importing the library, or +only its domain types, never depends on the MT5 wheel. +""" + +from __future__ import annotations + +import warnings +from types import ModuleType + +from PythonMetaTrader5.adapters.mt5_session import import_metatrader5, serialized + + +def public_names() -> list[str]: + module = _module_or_warn() + if module is None: + return [] + return sorted(n for n in dir(module) if not n.startswith("_")) + + +def resolve(name: str) -> object: + """One MT5 name; functions are wrapped to hold the adapter's session lock. + + Without the lock a direct ``last_error()`` from a 2.x-style script could run + between the adapter's ``order_send`` and its own ``last_error()`` read, and + a lost order would be reported as "never sent" (ADR 0009). Only names not + defined by the package reach this: a module __getattr__ runs on misses only. + """ + try: + module = None if name.startswith("_") else import_metatrader5() + except ImportError as error: + # AttributeError, not ImportError: hasattr(), getattr(.., default) and + # IDE tooling must keep working on a broken install; the cause is kept. + raise AttributeError(f"PythonMetaTrader5 has no attribute {name!r}: {error}") from error + if module is None or not hasattr(module, name): + raise AttributeError(f"module 'PythonMetaTrader5' has no attribute {name!r}") + value = getattr(module, name) + if callable(value) and not isinstance(value, type): + return serialized(value) + return value + + +def _module_or_warn() -> ModuleType | None: + try: + return import_metatrader5() + except ImportError as error: + # A star import of a broken install keeps our own names (connect() then + # reports the failure as Err) and says loudly why the MT5 names are gone. + # stacklevel 4: past this helper, public_names and the package + # __getattr__, so the warning names the user's import line. + warnings.warn(f"{error}; its names are not re-exported", RuntimeWarning, stacklevel=4) + return None diff --git a/src/PythonMetaTrader5/legacy/views.py b/src/PythonMetaTrader5/legacy/views.py new file mode 100644 index 0000000..ead66f8 --- /dev/null +++ b/src/PythonMetaTrader5/legacy/views.py @@ -0,0 +1,123 @@ +"""Positions and receipts in the exact shapes the 2.x API returned. + +2.x handed out raw MetaTrader5 objects (TradePosition, OrderSendResult), so +scripts read any field, index them and call ``_asdict()``. NamedTuples with the +same field names in the same order keep all three working. +""" + +from __future__ import annotations + +from typing import Any, NamedTuple + +from PythonMetaTrader5.domain.market import Position, TradeReceipt +from PythonMetaTrader5.domain.orders import Side + +# MT5 POSITION_TYPE_BUY / POSITION_TYPE_SELL: 2.x callers compare `p.type == 0`. +_POSITION_TYPE = {Side.BUY: 0, Side.SELL: 1} + +# The keys 2.x `as_dict=True` built by hand. A projection of as_object() rather +# than a second mapping, so the shared fields cannot drift apart; only sl/tp +# differ on purpose (None instead of 0.0, as in 2.x). +_V2_DICT_KEYS = ( + "ticket", + "symbol", + "type", + "volume", + "price_open", + "sl", + "tp", + "price_current", + "profit", + "time", + "magic", + "comment", +) + + +class LegacyPosition(NamedTuple): + """Field-for-field and in order the same as MetaTrader5.TradePosition.""" + + ticket: int + time: int + time_msc: int + time_update: int + time_update_msc: int + type: int + magic: int + identifier: int + reason: int + volume: float + price_open: float + sl: float + tp: float + price_current: float + swap: float + profit: float + symbol: str + comment: str + external_id: str + + +class LegacyReceipt(NamedTuple): + """Field-for-field and in order the same as MetaTrader5.OrderSendResult.""" + + retcode: int + deal: int + order: int + volume: float + price: float + bid: float + ask: float + comment: str + request_id: int + retcode_external: int + # The echoed TradeRequest is not kept by 3.x; always None. + request: None = None + + +def as_object(p: Position) -> LegacyPosition: + return LegacyPosition( + ticket=p.ticket, + time=p.time, + time_msc=p.time_msc, + time_update=p.time_update, + time_update_msc=p.time_update_msc, + type=_POSITION_TYPE[p.side], + magic=p.magic, + identifier=p.identifier, + reason=p.reason, + volume=p.volume, + price_open=p.price_open, + # Raw MT5 objects report a missing stop as 0.0; 2.x passed them through as is. + sl=p.sl or 0.0, + tp=p.tp or 0.0, + price_current=p.price_current, + swap=p.swap, + profit=p.profit, + symbol=p.symbol, + comment=p.comment, + external_id=p.external_id, + ) + + +def as_dict(p: Position) -> dict[str, Any]: + row = as_object(p)._asdict() + # 2.x `as_dict=True` used None for a missing stop, unlike the raw objects. + return {key: row[key] for key in _V2_DICT_KEYS} | {"sl": p.sl, "tp": p.tp} + + +def as_receipt(receipt: TradeReceipt | None) -> LegacyReceipt | None: + if receipt is None: + return None + return LegacyReceipt( + retcode=receipt.retcode, + deal=receipt.deal, + order=receipt.order, + volume=receipt.volume, + price=receipt.price, + bid=receipt.bid, + ask=receipt.ask, + comment=receipt.comment, + request_id=receipt.request_id, + retcode_external=receipt.retcode_external, + ) diff --git a/src/PythonMetaTrader5/py.typed b/src/PythonMetaTrader5/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/src/PythonMetaTrader5/result.py b/src/PythonMetaTrader5/result.py new file mode 100644 index 0000000..4038831 --- /dev/null +++ b/src/PythonMetaTrader5/result.py @@ -0,0 +1,41 @@ +"""Result type used at every port and use-case boundary. + +Chosen over exceptions at boundaries because a trading call has many *expected* +failures (market closed, no money, requote); an exception-based API lets callers +forget them, while a Result forces the caller to look at the outcome. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Generic, TypeVar, Union + +T = TypeVar("T") +E = TypeVar("E") + + +@dataclass(frozen=True, slots=True) +class Ok(Generic[T]): + value: T + + def is_ok(self) -> bool: + return True + + def is_err(self) -> bool: + return False + + +@dataclass(frozen=True, slots=True) +class Err(Generic[E]): + error: E + + def is_ok(self) -> bool: + return False + + def is_err(self) -> bool: + 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 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/contract/__init__.py b/tests/contract/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/contract/test_mt5_contract.py b/tests/contract/test_mt5_contract.py new file mode 100644 index 0000000..9a07643 --- /dev/null +++ b/tests/contract/test_mt5_contract.py @@ -0,0 +1,53 @@ +"""The unit-test fakes must look like the real MetaTrader5 package. + +Kept outside tests/unit on purpose: the autouse fixture there replaces the +module with FakeMT5, which would make this a comparison of the fake with +itself. Skipped where the package is not installed (it exists only on +Windows); the Windows CI job runs it against the real wheel. +""" + +from __future__ import annotations + +import re +from typing import Any + +import pytest + +from PythonMetaTrader5.domain.market import Tick +from PythonMetaTrader5.legacy.views import LegacyPosition, LegacyReceipt +from tests.unit.fake_mt5 import CONSTANTS, FakeMT5, raw_order, raw_position, symbol_info + +mt5 = pytest.importorskip("MetaTrader5") + + +def fields(structseq: Any) -> tuple[str, ...]: + # The package's result types are C struct sequences without `_fields`; the + # repr of a filled instance lists the names in order. + sample = structseq(tuple(range(structseq.n_fields))) + return tuple(re.findall(r"(\w+)=", repr(sample))) + + +def test_fake_constants_have_the_real_values() -> None: + assert {name: getattr(mt5, name) for name in CONSTANTS} == CONSTANTS + + +def test_legacy_shapes_match_the_real_result_types() -> None: + assert LegacyPosition._fields == fields(mt5.TradePosition) + assert LegacyReceipt._fields == fields(mt5.OrderSendResult) + + +def test_fake_rows_only_use_fields_the_real_objects_have() -> None: + assert set(vars(raw_position())) == set(fields(mt5.TradePosition)) + assert set(vars(FakeMT5().send_result)) == set(fields(mt5.OrderSendResult)) - {"request"} + assert set(vars(raw_order())) <= set(fields(mt5.TradeOrder)) + assert set(vars(symbol_info())) <= set(fields(mt5.SymbolInfo)) + + +def test_the_2x_star_import_still_brings_the_metatrader5_namespace() -> None: + namespace: dict[str, Any] = {} + exec("from PythonMetaTrader5 import *", namespace) # noqa: S102 - the 2.x idiom itself + assert namespace["symbol_info"].__wrapped__ is mt5.symbol_info # locked wrapper + assert namespace["ORDER_TYPE_BUY"] == mt5.ORDER_TYPE_BUY + # Our names win a collision: MT5 has its own Tick struct. + assert namespace["Tick"] is Tick + assert namespace["Broker"].__module__ == "PythonMetaTrader5.legacy.broker" diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/integration/test_demo_account.py b/tests/integration/test_demo_account.py new file mode 100644 index 0000000..7892540 --- /dev/null +++ b/tests/integration/test_demo_account.py @@ -0,0 +1,99 @@ +"""End-to-end checks against a real MetaTrader 5 terminal on a DEMO account. + +Run locally on Windows with a terminal installed: + + set MT5_LOGIN=... & set MT5_PASSWORD=... & set MT5_SERVER=... + pytest -m integration + +Optional: MT5_SYMBOL (default EURUSD), MT5_PATH (terminal64.exe). +These tests place and close real orders, so they refuse to run on anything +but a demo account. +""" + +from __future__ import annotations + +import os +from collections.abc import Iterator + +import pytest + +from PythonMetaTrader5 import Err, ErrorKind, Ok, PendingKind, Side, Stop, Trader, connect + +pytestmark = pytest.mark.integration +# Windows-only package: the whole module is skipped where it cannot be installed. +mt5 = pytest.importorskip("MetaTrader5") + +REQUIRED = ("MT5_LOGIN", "MT5_PASSWORD", "MT5_SERVER") +# Distinct from any manual trading so cleanup never touches foreign positions. +MAGIC = 930_117 +SYMBOL = os.environ.get("MT5_SYMBOL", "EURUSD") + + +@pytest.fixture(scope="module") +def trader() -> Iterator[Trader]: + if any(name not in os.environ for name in REQUIRED): + pytest.skip("MT5_LOGIN / MT5_PASSWORD / MT5_SERVER not set") + result = connect( + os.environ["MT5_LOGIN"], + os.environ["MT5_PASSWORD"], + os.environ["MT5_SERVER"], + path=os.environ.get("MT5_PATH"), + magic=MAGIC, + ) + if isinstance(result, Err): + pytest.fail(f"cannot connect: {result.error}") + account = mt5.account_info() + if account is None or account.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO: + result.value.shutdown() + pytest.fail("refusing to trade: the account is not a demo account") + yield result.value + result.value.close_positions(magic=MAGIC) + result.value.cancel_pending_orders(magic=MAGIC) + result.value.shutdown() + + +def minimum_volume() -> float: + return float(mt5.symbol_info(SYMBOL).volume_min) + + +def test_open_and_close_a_market_position(trader: Trader) -> None: + opened = trader.open_position( + SYMBOL, + Side.BUY, + minimum_volume(), + sl=Stop.points(2000), + tp=Stop.points(2000), + comment="pmt5 integration", + ) + if isinstance(opened, Err) and opened.error.kind is ErrorKind.MARKET_CLOSED: + pytest.skip("market closed") + assert isinstance(opened, Ok), opened + positions = trader.positions(SYMBOL, magic=MAGIC) + assert isinstance(positions, Ok) + assert len(positions.value) == 1 + position = positions.value[0] + assert position.sl is not None + assert position.tp is not None + closed = trader.close_positions(ticket=position.ticket) + assert isinstance(closed, Ok), closed + assert trader.positions(SYMBOL, magic=MAGIC) == Ok([]) + + +def test_place_and_cancel_a_limit_order_far_from_the_market(trader: Trader) -> None: + bid = mt5.symbol_info_tick(SYMBOL).bid + placed = trader.place_limit_order(SYMBOL, Side.BUY, minimum_volume(), bid * 0.9) + if isinstance(placed, Err) and placed.error.kind is ErrorKind.MARKET_CLOSED: + pytest.skip("market closed") + assert isinstance(placed, Ok), placed + pending = trader.pending_orders(SYMBOL, magic=MAGIC, kind=PendingKind.LIMIT) + assert isinstance(pending, Ok) + assert len(pending.value) == 1 + cancelled = trader.cancel_pending_orders(SYMBOL, magic=MAGIC) + assert isinstance(cancelled, Ok), cancelled + assert trader.pending_orders(SYMBOL, magic=MAGIC) == Ok([]) + + +def test_oversized_comment_is_rejected_locally(trader: Trader) -> None: + result = trader.open_position(SYMBOL, Side.BUY, minimum_volume(), comment="x" * 32) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_ARGUMENT diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py new file mode 100644 index 0000000..fb37404 --- /dev/null +++ b/tests/unit/conftest.py @@ -0,0 +1,34 @@ +import sys + +import pytest + +from PythonMetaTrader5.application.trader import Trader + +from .fake_mt5 import FakeMT5 +from .fakes import FakeClock, FakeTerminal + + +@pytest.fixture(autouse=True) +def no_real_terminal(monkeypatch: pytest.MonkeyPatch) -> FakeMT5: + """Unit tests must never reach a real terminal, even where MetaTrader5 is installed.""" + fake = FakeMT5() + monkeypatch.setitem(sys.modules, "MetaTrader5", fake) + return fake + + +@pytest.fixture +def terminal() -> FakeTerminal: + fake = FakeTerminal() + fake.quote("EURUSD", (1.10000, 1.10010)) + fake.quote("XAUUSD", (2400.00, 2400.50)) + return fake + + +@pytest.fixture +def clock() -> FakeClock: + return FakeClock() + + +@pytest.fixture +def trader(terminal: FakeTerminal, clock: FakeClock) -> Trader: + return Trader(terminal, clock, magic=42) diff --git a/tests/unit/fake_mt5.py b/tests/unit/fake_mt5.py new file mode 100644 index 0000000..9387723 --- /dev/null +++ b/tests/unit/fake_mt5.py @@ -0,0 +1,148 @@ +"""A stand-in for the `MetaTrader5` module with its constants and call log.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + +CONSTANTS = { + "TRADE_ACTION_DEAL": 1, + "TRADE_ACTION_PENDING": 5, + "TRADE_ACTION_REMOVE": 8, + "ORDER_TYPE_BUY": 0, + "ORDER_TYPE_SELL": 1, + "ORDER_TYPE_BUY_LIMIT": 2, + "ORDER_TYPE_SELL_LIMIT": 3, + "ORDER_TYPE_BUY_STOP": 4, + "ORDER_TYPE_SELL_STOP": 5, + "ORDER_TYPE_BUY_STOP_LIMIT": 6, + "ORDER_TYPE_SELL_STOP_LIMIT": 7, + "ORDER_FILLING_FOK": 0, + "ORDER_FILLING_IOC": 1, + "ORDER_FILLING_RETURN": 2, + "ORDER_TIME_GTC": 0, + "POSITION_TYPE_BUY": 0, + "POSITION_TYPE_SELL": 1, + "SYMBOL_TRADE_EXECUTION_EXCHANGE": 3, + "RES_S_OK": 1, + "RES_E_INVALID_PARAMS": -2, + "RES_E_NO_MEMORY": -3, + "RES_E_NOT_FOUND": -4, + "RES_E_INVALID_VERSION": -5, + "RES_E_AUTH_FAILED": -6, + "RES_E_UNSUPPORTED": -7, + "RES_E_AUTO_TRADING_DISABLED": -8, + "RES_E_INTERNAL_FAIL_INIT": -10003, + "RES_E_INTERNAL_FAIL_CONNECT": -10004, +} + + +class FakeMT5: + def __init__(self) -> None: + for name, value in CONSTANTS.items(): + setattr(self, name, value) + self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] + self.initialize_ok = True + self.error = (1, "Success") + self.symbols: dict[str, SimpleNamespace] = {} + self.ticks: dict[str, SimpleNamespace] = {} + self.send_result: SimpleNamespace | None = SimpleNamespace( + retcode=10009, + deal=11, + order=12, + volume=0.1, + price=1.1, + bid=1.1, + ask=1.2, + comment="Request executed", + request_id=13, + retcode_external=0, + ) + self.positions: tuple[SimpleNamespace, ...] | None = () + self.orders: tuple[SimpleNamespace, ...] | None = () + + def _record(self, name: str, *args: Any, **kwargs: Any) -> None: + self.calls.append((name, args, kwargs)) + + def initialize(self, *args: Any, **kwargs: Any) -> bool: + self._record("initialize", *args, **kwargs) + return self.initialize_ok + + def last_error(self) -> tuple[int, str]: + return self.error + + def shutdown(self) -> None: + self._record("shutdown") + + def symbol_info(self, name: str) -> SimpleNamespace | None: + return self.symbols.get(name) + + def symbol_select(self, name: str, enable: bool) -> bool: + self._record("symbol_select", name, enable) + return True + + def symbol_info_tick(self, name: str) -> SimpleNamespace | None: + return self.ticks.get(name) + + def order_send(self, request: dict[str, Any]) -> SimpleNamespace | None: + self._record("order_send", request) + return self.send_result + + def positions_get(self, **kwargs: Any) -> tuple[SimpleNamespace, ...] | None: + self._record("positions_get", **kwargs) + return self.positions + + def orders_get(self, **kwargs: Any) -> tuple[SimpleNamespace, ...] | None: + self._record("orders_get", **kwargs) + return self.orders + + +def symbol_info(name: str = "EURUSD", visible: bool = True) -> SimpleNamespace: + return SimpleNamespace( + name=name, + visible=visible, + digits=5, + point=0.00001, + trade_tick_size=0.00001, + volume_min=0.01, + volume_max=100.0, + volume_step=0.01, + filling_mode=1, + trade_exemode=2, + ) + + +def raw_position(ticket: int = 1, type_: int = 1, sl: float = 0.0) -> SimpleNamespace: + return SimpleNamespace( + ticket=ticket, + symbol="EURUSD", + type=type_, + volume=0.1, + price_open=1.1, + sl=sl, + tp=0.0, + price_current=1.09, + profit=5.0, + time=1700000000, + magic=42, + comment="bot", + swap=-0.5, + identifier=ticket, + reason=3, + time_msc=1700000000123, + time_update=1700000001, + time_update_msc=1700000001456, + external_id="", + ) + + +def raw_order(ticket: int = 5, type_: int = 3) -> SimpleNamespace: + return SimpleNamespace( + ticket=ticket, + symbol="EURUSD", + type=type_, + volume_current=0.2, + price_open=1.2, + magic=0, + comment="", + ) diff --git a/tests/unit/fakes.py b/tests/unit/fakes.py new file mode 100644 index 0000000..06e77ba --- /dev/null +++ b/tests/unit/fakes.py @@ -0,0 +1,160 @@ +"""In-memory stand-ins for the two process boundaries (terminal, clock).""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass, field +from typing import Any + +from PythonMetaTrader5.application.ports import Credentials +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.market import PendingOrder, Position, Tick, TradeReceipt +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest +from PythonMetaTrader5.domain.symbol import SymbolSpec +from PythonMetaTrader5.result import Err, Ok, Result + +EURUSD = SymbolSpec( + name="EURUSD", + digits=5, + point=0.00001, + tick_size=0.00001, + volume_min=0.01, + volume_max=100.0, + volume_step=0.01, + filling_flags=1, + exchange_execution=False, +) +XAUUSD = SymbolSpec( + name="XAUUSD", + digits=2, + point=0.01, + tick_size=0.01, + volume_min=0.01, + volume_max=50.0, + volume_step=0.01, + filling_flags=2, + exchange_execution=False, +) + + +def make_position(ticket: int = 1, **overrides: Any) -> Position: + fields: dict[str, Any] = { + "ticket": ticket, + "symbol": "EURUSD", + "side": Side.BUY, + "volume": 0.1, + "price_open": 1.1, + "sl": None, + "tp": None, + "price_current": 1.1, + "profit": 0.0, + "time": 0, + "magic": 0, + "comment": "", + "swap": 0.0, + "identifier": ticket, + "reason": 0, + "time_msc": 0, + "time_update": 0, + "time_update_msc": 0, + "external_id": "", + } + return Position(**{**fields, **overrides}) + + +def receipt(retcode: int = 10009, price: float = 0.0) -> TradeReceipt: + return TradeReceipt( + retcode=retcode, + deal=1, + order=1, + volume=0.1, + price=price, + bid=0.0, + ask=0.0, + comment="", + request_id=1, + retcode_external=0, + ) + + +@dataclass +class FakeTerminal: + specs: dict[str, SymbolSpec] = field( + default_factory=lambda: {"EURUSD": EURUSD, "XAUUSD": XAUUSD} + ) + ticks: dict[str, deque[Tick]] = field(default_factory=dict) + retcodes: deque[int] = field(default_factory=deque) + open_positions: list[Position] = field(default_factory=list) + open_orders: list[PendingOrder] = field(default_factory=list) + send_failure: TradeError | None = None + connect_failure: TradeError | None = None + # A countdown rather than a flag, so a retry loop can be shown to recover. + connect_failures: int = 0 + sent: list[OrderRequest | CancelRequest] = field(default_factory=list) + connected_with: list[Credentials] = field(default_factory=list) + symbol_lookups: list[str] = field(default_factory=list) + # Number of tick() calls answered with NO_PRICE before quotes arrive. + missing_quotes: int = 0 + shut_down: bool = False + + def quote(self, symbol: str, *ticks: tuple[float, float]) -> None: + self.ticks[symbol] = deque(Tick(bid, ask) for bid, ask in ticks) + + def connect(self, credentials: Credentials) -> Result[None, TradeError]: + self.connected_with.append(credentials) + if self.connect_failures: + self.connect_failures -= 1 + return Err(TradeError(ErrorKind.CONNECTION_FAILED, "terminal not ready")) + return Err(self.connect_failure) if self.connect_failure else Ok(None) + + def shutdown(self) -> None: + self.shut_down = True + + def symbol(self, name: str) -> Result[SymbolSpec, TradeError]: + self.symbol_lookups.append(name) + if name not in self.specs: + return Err(TradeError(ErrorKind.SYMBOL_NOT_FOUND, name)) + return Ok(self.specs[name]) + + def tick(self, name: str) -> Result[Tick, TradeError]: + queue = self.ticks.get(name) + if self.missing_quotes: + self.missing_quotes -= 1 + return Err(TradeError(ErrorKind.NO_PRICE, name)) + if not queue: + return Err(TradeError(ErrorKind.NO_PRICE, name)) + # The last quote sticks, earlier ones are consumed one per call. + return Ok(queue.popleft() if len(queue) > 1 else queue[0]) + + def send(self, request: OrderRequest | CancelRequest) -> Result[TradeReceipt, TradeError]: + self.sent.append(request) + if self.send_failure: + return Err(self.send_failure) + code = self.retcodes.popleft() if self.retcodes else 10009 + price = request.price if isinstance(request, OrderRequest) else 0.0 + return Ok(receipt(code, price)) + + def positions( + self, *, symbol: str | None = None, ticket: int | None = None + ) -> Result[list[Position], TradeError]: + return Ok( + [ + p + for p in self.open_positions + if (symbol is None or p.symbol == symbol) and (ticket is None or p.ticket == ticket) + ] + ) + + def pending_orders( + self, *, symbol: str | None = None + ) -> Result[list[PendingOrder], TradeError]: + return Ok([o for o in self.open_orders if symbol is None or o.symbol == symbol]) + + +@dataclass +class FakeClock: + sleeps: list[float] = field(default_factory=list) + + def sleep(self, seconds: float) -> None: + self.sleeps.append(seconds) diff --git a/tests/unit/test_close_positions.py b/tests/unit/test_close_positions.py new file mode 100644 index 0000000..33e370e --- /dev/null +++ b/tests/unit/test_close_positions.py @@ -0,0 +1,79 @@ +from PythonMetaTrader5.application.batch import BatchFailure +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.market import Position +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.requests import OrderRequest +from PythonMetaTrader5.result import Err, Ok + +from .fakes import FakeTerminal, make_position + + +def position(ticket: int, symbol: str, side: Side, magic: int = 42) -> Position: + return make_position( + ticket, + symbol=symbol, + side=side, + volume=0.2, + price_open=1.0, + price_current=1.0, + magic=magic, + ) + + +def sent_orders(terminal: FakeTerminal) -> list[OrderRequest]: + orders = [r for r in terminal.sent if isinstance(r, OrderRequest)] + assert len(orders) == len(terminal.sent) + return orders + + +def test_each_position_is_closed_on_its_own_symbol(trader: Trader, terminal: FakeTerminal) -> None: + terminal.open_positions = [position(1, "EURUSD", Side.BUY), position(2, "XAUUSD", Side.SELL)] + result = trader.close_positions() + assert isinstance(result, Ok) + assert len(result.value) == 2 + first, second = sent_orders(terminal) + assert (first.symbol, first.side, first.price, first.position) == ("EURUSD", Side.SELL, 1.1, 1) + assert (second.symbol, second.side, second.price, second.position) == ( + "XAUUSD", + Side.BUY, + 2400.5, + 2, + ) + assert first.volume == 0.2 + + +def test_close_by_ticket_ignores_the_symbol_argument( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.open_positions = [position(1, "EURUSD", Side.BUY), position(2, "XAUUSD", Side.SELL)] + assert isinstance(trader.close_positions("EURUSD", ticket=2), Ok) + (request,) = sent_orders(terminal) + assert request.symbol == "XAUUSD" + + +def test_nothing_to_close_is_success(trader: Trader) -> None: + assert trader.close_positions("EURUSD") == Ok([]) + + +def test_magic_filter_leaves_foreign_positions_open(trader: Trader, terminal: FakeTerminal) -> None: + terminal.open_positions = [ + position(1, "EURUSD", Side.BUY, magic=7), + position(2, "EURUSD", Side.BUY, magic=42), + ] + trader.close_positions("EURUSD", magic=42) + assert [r.position for r in sent_orders(terminal)] == [2] + + +def test_partial_failure_reports_what_closed_and_what_did_not( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.open_positions = [position(1, "EURUSD", Side.BUY), position(2, "EURUSD", Side.BUY)] + terminal.retcodes.extend([10009, 10018]) + result = trader.close_positions("EURUSD") + assert isinstance(result, Err) + failure = result.error + assert isinstance(failure, BatchFailure) + assert len(failure.succeeded) == 1 + (error,) = failure.errors + assert (error.kind, error.ticket) == (ErrorKind.MARKET_CLOSED, 2) diff --git a/tests/unit/test_confirmation.py b/tests/unit/test_confirmation.py new file mode 100644 index 0000000..5a75717 --- /dev/null +++ b/tests/unit/test_confirmation.py @@ -0,0 +1,100 @@ +"""Only an answer that proves the requested effect counts as success.""" + +import operator + +import pytest + +from PythonMetaTrader5 import Broker, connect +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.application.ports import Credentials +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.result import Err, Ok + +from .fake_mt5 import FakeMT5, symbol_info +from .fakes import FakeClock, FakeTerminal + + +@pytest.mark.parametrize( + ("retcode", "kind"), [(10010, ErrorKind.PARTIAL_FILL), (10008, ErrorKind.OUTCOME_UNKNOWN)] +) +def test_market_entry_succeeds_only_when_done( + trader: Trader, terminal: FakeTerminal, retcode: int, kind: ErrorKind +) -> None: + terminal.retcodes.append(retcode) + result = trader.open_position("EURUSD", "buy", 0.1) + assert isinstance(result, Err) + assert result.error.kind is kind + assert result.error.receipt is not None + assert len(terminal.sent) == 1 # never re-sent: something may already be open + + +@pytest.mark.parametrize("retcode", [10008, 10009]) +def test_pending_entry_succeeds_when_placed( + trader: Trader, terminal: FakeTerminal, retcode: int +) -> None: + terminal.retcodes.append(retcode) + assert isinstance(trader.place_limit_order("EURUSD", "buy", 0.1, 1.0), Ok) + + +@pytest.mark.parametrize("login", ["²", "١٢٣", " 12a", ""]) +def test_non_ascii_or_malformed_login_is_an_error(login: str) -> None: + result = connect(login, "pw", "Demo") + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_ARGUMENT + + +class IndexLike: + def __index__(self) -> int: + return 12345678 + + +def test_integer_like_login_is_accepted(no_real_terminal: FakeMT5) -> None: + assert operator.index(IndexLike()) == 12345678 + assert isinstance(connect(IndexLike(), "pw", "Demo"), Ok) # type: ignore[arg-type] + assert no_real_terminal.calls[0][2]["login"] == 12345678 + + +@pytest.mark.parametrize("login", [True, 12345678.9, "abc"]) +def test_legacy_broker_rejects_logins_it_would_coerce(login: object) -> None: + with ( + pytest.warns(DeprecationWarning, match="connect"), + pytest.raises(ValueError, match="login"), + ): + Broker(login, "pw", "Demo", terminal=FakeTerminal(), clock=FakeClock()) # type: ignore[arg-type] + + +def test_failed_relogin_releases_the_session() -> None: + mt5 = FakeMT5() + adapter = MetaTrader5Terminal(mt5) + assert adapter.connect(Credentials(1, "pw", "s")) == Ok(None) + mt5.initialize_ok = False + assert isinstance(adapter.connect(Credentials(1, "bad", "s")), Err) + assert [name for name, _, _ in mt5.calls] == ["initialize", "initialize", "shutdown"] + + +def test_broker_stops_trading_after_a_failed_relogin(terminal: FakeTerminal) -> None: + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=terminal, clock=FakeClock()) + terminal.connect_failure = TradeError(ErrorKind.CONNECTION_FAILED, "down") + assert broker.login() is False + assert broker.Buy("EURUSD", 0.1) is None + assert terminal.sent == [] + + +@pytest.mark.parametrize("login", [True, 1.5, 0]) +def test_credentials_refuse_logins_mt5_would_coerce(login: object) -> None: + with pytest.raises(ValueError, match="login"): + Credentials(login, "pw", "s") # type: ignore[arg-type] + + +def test_exchange_execution_is_read_from_the_symbol() -> None: + mt5 = FakeMT5() + mt5.symbols["SBER"] = symbol_info("SBER") + mt5.symbols["SBER"].trade_exemode = 3 + mt5.symbols["EURUSD"] = symbol_info() + adapter = MetaTrader5Terminal(mt5) + sber, eurusd = adapter.symbol("SBER"), adapter.symbol("EURUSD") + assert isinstance(sber, Ok) + assert isinstance(eurusd, Ok) + assert (sber.value.exchange_execution, eurusd.value.exchange_execution) == (True, False) diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py new file mode 100644 index 0000000..307af15 --- /dev/null +++ b/tests/unit/test_connection.py @@ -0,0 +1,68 @@ +import sys + +import pytest + +from PythonMetaTrader5 import Trader, connect +from PythonMetaTrader5.adapters import system_clock +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.result import Err, Ok + +from .fake_mt5 import FakeMT5 + + +@pytest.fixture +def mt5(monkeypatch: pytest.MonkeyPatch) -> FakeMT5: + fake = FakeMT5() + monkeypatch.setitem(sys.modules, "MetaTrader5", fake) + return fake + + +def test_missing_package_is_reported_not_raised(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(sys.modules, "MetaTrader5", None) + result = MetaTrader5Terminal.load() + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.CONNECTION_FAILED + + +def test_connect_returns_a_configured_trader(mt5: FakeMT5) -> None: + result = connect("123", "pw", "Demo", magic=7) + assert isinstance(result, Ok) + assert isinstance(result.value, Trader) + assert mt5.calls[0][2]["login"] == 123 + + +def test_connect_failure_is_an_error(mt5: FakeMT5) -> None: + mt5.initialize_ok = False + result = connect(123, "pw", "Demo") + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.CONNECTION_FAILED + + +def test_non_numeric_login_is_rejected_before_touching_the_terminal(mt5: FakeMT5) -> None: + result = connect("abc", "pw", "Demo") + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_ARGUMENT + assert mt5.calls == [] + + +def test_trader_is_a_context_manager_that_shuts_down(mt5: FakeMT5) -> None: + result = connect(1, "pw", "Demo") + assert isinstance(result, Ok) + with result.value as trader: + assert isinstance(trader, Trader) + assert mt5.calls[-1][0] == "shutdown" + + +def test_system_clock_sleeps(monkeypatch: pytest.MonkeyPatch) -> None: + slept: list[float] = [] + monkeypatch.setattr(system_clock.time, "sleep", slept.append) + system_clock.SystemClock().sleep(0.25) + assert slept == [0.25] + + +def test_connect_without_package_is_an_error(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(sys.modules, "MetaTrader5", None) + result = connect(1, "pw", "Demo") + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.CONNECTION_FAILED diff --git a/tests/unit/test_failure_paths.py b/tests/unit/test_failure_paths.py new file mode 100644 index 0000000..25dc4d7 --- /dev/null +++ b/tests/unit/test_failure_paths.py @@ -0,0 +1,67 @@ +import pytest + +from PythonMetaTrader5.application.batch import BatchFailure +from PythonMetaTrader5.application.execution import RetryPolicy +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.market import Position +from PythonMetaTrader5.result import Err + +from .fakes import FakeTerminal, make_position, receipt + + +def btc_position() -> Position: + return make_position(9, symbol="BTCUSD", price_open=1.0, price_current=1.0) + + +@pytest.mark.parametrize("policy", [{"attempts": 0}, {"delay_seconds": -1.0}]) +def test_nonsensical_retry_policy_fails_at_construction(policy: dict[str, float]) -> None: + with pytest.raises(ValueError, match="invalid retry policy"): + RetryPolicy(**policy) # type: ignore[arg-type] + + +def test_errors_render_kind_retcode_and_ticket() -> None: + error = TradeError(ErrorKind.MARKET_CLOSED, "market is closed", retcode=10018, ticket=3) + assert str(error) == "market_closed: market is closed (retcode 10018) [ticket 3]" + failure = BatchFailure((receipt(),), (error,)) + assert str(failure).startswith("1 failed, 1 succeeded: market_closed") + + +def test_close_reports_unknown_symbol_and_missing_quote( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.open_positions = [btc_position()] + result = trader.close_positions() + assert isinstance(result, Err) + assert result.error.errors[0].kind is ErrorKind.SYMBOL_NOT_FOUND + terminal.specs["BTCUSD"] = terminal.specs["EURUSD"] + result = trader.close_positions() + assert isinstance(result, Err) + assert result.error.errors[0].kind is ErrorKind.NO_PRICE + + +def test_close_rejects_overlong_comment_before_touching_positions( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.open_positions = [btc_position()] + result = trader.close_positions(comment="c" * 32) + assert isinstance(result, Err) + assert result.error.errors[0].kind is ErrorKind.INVALID_ARGUMENT + assert terminal.sent == [] + + +class BrokenListing(FakeTerminal): + def positions(self, **_: object) -> Err[TradeError]: # type: ignore[override] + return Err(TradeError(ErrorKind.TERMINAL_ERROR, "positions_get failed")) + + def pending_orders(self, **_: object) -> Err[TradeError]: # type: ignore[override] + return Err(TradeError(ErrorKind.TERMINAL_ERROR, "orders_get failed")) + + +def test_listing_failures_surface_as_batch_failures(clock: object) -> None: + trader = Trader(BrokenListing(), clock) # type: ignore[arg-type] + for result in (trader.close_positions(), trader.cancel_pending_orders()): + assert isinstance(result, Err) + assert result.error.errors[0].kind is ErrorKind.TERMINAL_ERROR + assert isinstance(trader.positions(), Err) + assert isinstance(trader.pending_orders(), Err) diff --git a/tests/unit/test_input_guards.py b/tests/unit/test_input_guards.py new file mode 100644 index 0000000..e988852 --- /dev/null +++ b/tests/unit/test_input_guards.py @@ -0,0 +1,262 @@ +"""Inputs a webhook can deliver malformed must fail loudly before anything is sent.""" + +from __future__ import annotations + +import math +import threading +from decimal import Decimal + +import pytest + +from PythonMetaTrader5 import Broker, Stop, StopKind +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.application.entries import Entry +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.result import Err, Ok + +from .fake_mt5 import FakeMT5, raw_position +from .fakes import EURUSD, FakeClock, FakeTerminal, make_position + +NOT_A_STOP = [0, 0.0, -1.1, math.nan, math.inf, True, Decimal("sNaN"), "1.1"] +NOT_A_NUMBER = [math.nan, math.inf, -math.inf, True, "0.1", Decimal("sNaN"), Decimal("NaN"), None] + + +@pytest.mark.parametrize("stop", NOT_A_STOP) +@pytest.mark.parametrize("which", ["sl", "tp"]) +def test_a_stop_of_zero_or_garbage_is_refused_not_dropped( + trader: Trader, terminal: FakeTerminal, stop: object, which: str +) -> None: + # MT5 reads sl=0 as "no stop": a missing webhook field would open unprotected. + for result in ( + trader.open_position("EURUSD", "buy", 0.1, **{which: stop}), # type: ignore[arg-type] + trader.place_limit_order("EURUSD", "buy", 0.1, 1.09, **{which: stop}), # type: ignore[arg-type] + ): + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_STOPS + assert terminal.sent == [] + + +@pytest.mark.parametrize("stop", [0.000001, Stop.points(10_000_000)]) +def test_a_stop_that_resolves_to_zero_or_below_is_refused( + trader: Trader, terminal: FakeTerminal, stop: Stop | float +) -> None: + # 0.000001 snaps to 0.0 on a 5-digit grid; 10M points below 1.1 is negative. + result = trader.open_position("EURUSD", "buy", 0.1, sl=stop) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_STOPS + assert terminal.sent == [] + + +@pytest.mark.parametrize("volume", [*NOT_A_NUMBER, 0, -0.1]) +def test_volume_that_is_not_a_positive_finite_number_is_refused( + trader: Trader, terminal: FakeTerminal, volume: object +) -> None: + result = trader.open_position("EURUSD", "buy", volume) # type: ignore[arg-type] + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_VOLUME + assert terminal.sent == [] + + +@pytest.mark.parametrize("price", [*NOT_A_NUMBER[:-1], 0, -1.0]) +def test_price_that_is_not_a_positive_finite_number_is_refused( + trader: Trader, terminal: FakeTerminal, price: object +) -> None: + for result in ( + trader.open_position("EURUSD", "buy", 0.1, price=price), # type: ignore[arg-type] + trader.place_limit_order("EURUSD", "buy", 0.1, price), # type: ignore[arg-type] + ): + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_PRICE + assert terminal.sent == [] + + +@pytest.mark.parametrize("ticket", [0, -5, True, 1.0, "7"]) +def test_a_ticket_that_is_not_a_positive_integer_never_reaches_the_terminal( + trader: Trader, terminal: FakeTerminal, ticket: object +) -> None: + # positions_get(ticket=0) may mean "no filter" and close the whole account. + terminal.open_positions = [make_position(1)] + query = trader.positions(ticket=ticket) # type: ignore[arg-type] + assert isinstance(query, Err) + assert query.error.kind is ErrorKind.INVALID_ARGUMENT + closed = trader.close_positions(ticket=ticket) # type: ignore[arg-type] + assert isinstance(closed, Err) + assert closed.error.errors[0].kind is ErrorKind.INVALID_ARGUMENT + assert terminal.sent == [] + + +def test_legacy_calls_refuse_a_zero_stop_and_a_zero_ticket(terminal: FakeTerminal) -> None: + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=terminal, clock=FakeClock()) + terminal.open_positions = [make_position(1)] + assert broker.BuySL("EURUSD", 0.1, 0) is None + assert broker.Close(None, ticket=0) is False + assert broker.GetPositions(ticket=0) == [] + assert terminal.sent == [] + + +def test_adapter_applies_symbol_and_ticket_together() -> None: + # MT5's positions_get ignores `symbol` once `ticket` is given. + mt5 = FakeMT5() + mt5.positions = (raw_position(ticket=1),) + adapter = MetaTrader5Terminal(mt5) + assert adapter.positions(symbol="XAUUSD", ticket=1) == Ok([]) + listed = adapter.positions(symbol="EURUSD", ticket=1) + assert isinstance(listed, Ok) + assert [p.ticket for p in listed.value] == [1] + + +def test_concurrent_calls_cannot_read_each_others_last_error() -> None: + # last_error() is process-global: a call and its error read must not interleave. + mt5 = FakeMT5() + entered, release = threading.Event(), threading.Event() + mt5.positions = None + + def blocking_positions_get(**_: object) -> None: + entered.set() + release.wait(5) + + mt5.positions_get = blocking_positions_get # type: ignore[method-assign] + first, second = MetaTrader5Terminal(mt5), MetaTrader5Terminal(mt5) + worker = threading.Thread(target=first.positions) + worker.start() + assert entered.wait(5) + finished = threading.Event() + other = threading.Thread(target=lambda: (second.tick("EURUSD"), finished.set())) + other.start() + blocked = not finished.wait(0.2) + release.set() + worker.join(5) + other.join(5) + assert blocked, "a second adapter ran while the first was between call and last_error()" + + +@pytest.mark.parametrize("level", [0, -1.0, math.inf, math.nan, True]) +def test_legacy_limit_with_a_bad_level_sends_nothing(terminal: FakeTerminal, level: object) -> None: + # A bad level used to be compared with the quote first and "crossed" into a market order. + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=terminal, clock=FakeClock()) + assert broker.SellLimit("EURUSD", 0.1, level) is None # type: ignore[arg-type] + assert broker.BuyLimit("EURUSD", 0.1, level) is None # type: ignore[arg-type] + assert terminal.sent == [] + + +@pytest.mark.parametrize("value", [0, -1.1, True, math.nan, math.inf, Decimal("sNaN"), "1.1"]) +@pytest.mark.parametrize("factory", [Stop.at_price, Stop.points]) +def test_a_stop_cannot_be_built_from_a_value_mt5_would_misread( + factory: object, value: object +) -> None: + if factory == Stop.points and isinstance(value, float) and value < 0: + pytest.skip("a negative distance is a distance") + with pytest.raises(ValueError, match="positive finite"): + factory(value) # type: ignore[operator] + + +def test_a_stop_holds_a_float_and_a_distance_has_no_sign() -> None: + assert Stop.points(-1000) == Stop.points(1000) + assert Stop.at_price(Decimal("1.1")).value == 1.1 + assert isinstance(Stop.points(Decimal("100")).value, float) + + +@pytest.mark.parametrize("sl_type", ["absolute", "offset"]) +def test_legacy_refuses_a_bool_stop(terminal: FakeTerminal, sl_type: str) -> None: + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=terminal, clock=FakeClock()) + assert broker.OpenPosition("EURUSD", "buy", 0.1, sl=True, sl_type=sl_type) is None # type: ignore[arg-type] + assert broker.OpenPosition("EURUSD", "buy", 0.1, sl=0, sl_type=sl_type) is None + assert terminal.sent == [] + + +def test_decimal_amounts_are_accepted(trader: Trader, terminal: FakeTerminal) -> None: + result = trader.open_position("EURUSD", "buy", Decimal("0.1"), price=Decimal("1.1001")) # type: ignore[arg-type] + assert isinstance(result, Ok) + request = terminal.sent[0] + assert (request.volume, request.price) == (0.1, 1.1001) # type: ignore[union-attr] + + +def test_a_bad_price_is_refused_before_any_symbol_lookup( + trader: Trader, terminal: FakeTerminal +) -> None: + for result in ( + trader.open_position("EURUSD", "buy", 0.1, price=math.nan), + trader.place_limit_order("EURUSD", "buy", 0.1, 0), + ): + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_PRICE + assert terminal.symbol_lookups == [] + + +def test_a_bad_side_is_still_reported_before_a_bad_price(trader: Trader) -> None: + result = trader.open_position("EURUSD", "hold", 0.1, price=math.nan) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_ARGUMENT + + +def test_an_entry_without_a_price_or_a_quote_sends_nothing() -> None: + entry = Entry(EURUSD, Side.BUY, 0.1, "", None, None, None) + result = entry.request(pending=None, deviation=10, magic=0) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.NO_PRICE + + +def test_a_price_that_snaps_to_zero_is_refused_before_sending( + trader: Trader, terminal: FakeTerminal +) -> None: + for result in ( + trader.open_position("EURUSD", "buy", 0.1, price=1e-6), + trader.place_limit_order("EURUSD", "buy", 0.1, 0.000004), + ): + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_PRICE + assert terminal.sent == [] + + +def test_numbers_too_large_for_a_float_are_refused_not_raised( + trader: Trader, terminal: FakeTerminal +) -> None: + huge = 10**400 + for result, kind in ( + (trader.open_position("EURUSD", "buy", huge), ErrorKind.INVALID_VOLUME), + (trader.open_position("EURUSD", "buy", 0.1, sl=huge), ErrorKind.INVALID_STOPS), + ): + assert isinstance(result, Err) + assert result.error.kind is kind + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=terminal, clock=FakeClock()) + assert broker.OpenPosition("EURUSD", "buy", 0.1, sl=huge, sl_type="offset") is None + assert terminal.sent == [] + + +def test_stop_parse_is_the_non_raising_way_to_build_a_stop() -> None: + assert Stop.parse(-1000, StopKind.POINTS) == Ok(Stop.points(1000)) + for value in (math.nan, 0, True): + parsed = Stop.parse(value, StopKind.POINTS) + assert isinstance(parsed, Err) + assert parsed.error.kind is ErrorKind.INVALID_STOPS + + +def test_a_stop_kind_must_be_a_stop_kind() -> None: + with pytest.raises(TypeError, match="StopKind"): + Stop(1000, "points") # type: ignore[arg-type] + + +def test_a_finite_price_too_large_for_the_tick_grid_is_refused_not_raised( + trader: Trader, terminal: FakeTerminal +) -> None: + for result, kind in ( + (trader.open_position("EURUSD", "buy", 0.1, price=1e305), ErrorKind.INVALID_PRICE), + (trader.place_limit_order("EURUSD", "buy", 0.1, 1e305), ErrorKind.INVALID_PRICE), + (trader.open_position("EURUSD", "buy", 0.1, sl=1e305), ErrorKind.INVALID_STOPS), + (trader.open_position("EURUSD", "buy", 0.1, tp=1e305), ErrorKind.INVALID_STOPS), + ): + assert isinstance(result, Err) + assert result.error.kind is kind + assert terminal.sent == [] + + +def test_stop_parse_reports_a_wrong_kind_as_a_type_error_for_any_value() -> None: + for value in (0, 5): + with pytest.raises(TypeError, match="StopKind"): + Stop.parse(value, "points") # type: ignore[arg-type] diff --git a/tests/unit/test_legacy_broker.py b/tests/unit/test_legacy_broker.py new file mode 100644 index 0000000..dcfc351 --- /dev/null +++ b/tests/unit/test_legacy_broker.py @@ -0,0 +1,165 @@ +"""The 2.x `Broker` API keeps its names, arguments and return shapes.""" + +import pytest + +from PythonMetaTrader5 import Broker +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.market import PendingKind, PendingOrder, Position +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest + +from .fake_mt5 import FakeMT5, raw_position +from .fakes import FakeClock, FakeTerminal, make_position + + +@pytest.fixture +def broker(terminal: FakeTerminal, clock: FakeClock) -> Broker: + with pytest.warns(DeprecationWarning, match="connect"): + return Broker(123, "pw", "Demo", terminal=terminal, clock=clock) + + +def orders(terminal: FakeTerminal) -> list[OrderRequest]: + return [r for r in terminal.sent if isinstance(r, OrderRequest)] + + +def long_position(ticket: int = 1) -> Position: + return make_position(ticket, price_open=1.0, tp=1.2, price_current=1.0, profit=3.0, time=5) + + +def test_constructor_logs_in_with_string_credentials(terminal: FakeTerminal) -> None: + with pytest.warns(DeprecationWarning, match="connect"): + Broker("123", 456, "Demo", terminal=terminal, clock=FakeClock()) + (credentials,) = terminal.connected_with + assert (credentials.login, credentials.password, credentials.server) == (123, "456", "Demo") + + +def test_failed_login_is_logged_and_retried_by_login( + terminal: FakeTerminal, clock: FakeClock, caplog: pytest.LogCaptureFixture +) -> None: + terminal.connect_failure = TradeError(ErrorKind.CONNECTION_FAILED, "bad password") + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=terminal, clock=clock) + assert "bad password" in caplog.text + assert broker.login() is False + assert broker.OpenPosition("EURUSD", "buy", 0.1) is None + terminal.connect_failure = None + assert broker.login(ToEffect=True) is True + + +def test_open_position_with_offsets_returns_the_receipt( + broker: Broker, terminal: FakeTerminal +) -> None: + result = broker.OpenPosition( + "EURUSD", "long", 0.1, sl=1000, tp=1500, sl_type="offset", tp_type="offset" + ) + assert result is not None + assert result.retcode == 10009 + (request,) = orders(terminal) + assert (request.sl, request.tp) == (1.0901, 1.1151) + + +def test_wrappers_map_to_sides_and_absolute_stops(broker: Broker, terminal: FakeTerminal) -> None: + broker.Buy("EURUSD", 0.1) + broker.Sell("EURUSD", 0.1) + broker.BuySL("EURUSD", 0.1, 1.05) + broker.SellSL("EURUSD", 0.1, 100, sl_type="offset") + sides = [(r.side, r.sl) for r in orders(terminal)] + assert sides == [(Side.BUY, None), (Side.SELL, None), (Side.BUY, 1.05), (Side.SELL, 1.101)] + + +def test_broker_refusal_returns_the_receipt_and_logs_it( + broker: Broker, terminal: FakeTerminal, caplog: pytest.LogCaptureFixture +) -> None: + terminal.retcodes.append(10027) + result = broker.OpenPosition("EURUSD", "buy", 0.1) + assert result is not None + assert result.retcode == 10027 + assert "Algo Trading" in caplog.text + assert broker.RetCodes[10027] + + +@pytest.mark.parametrize( + "kwargs", + [{"side": "hold"}, {"sl": 1, "sl_type": "pips"}, {"tp": 1, "tp_type": "pips"}, {"ticket": 5}], +) +def test_unsupported_arguments_return_none(broker: Broker, kwargs: dict[str, object]) -> None: + arguments: dict[str, object] = {"side": "buy", **kwargs} + assert broker.OpenPosition("EURUSD", volume=0.1, **arguments) is None # type: ignore[arg-type] + + +def test_positions_keep_the_2x_shapes(broker: Broker, terminal: FakeTerminal) -> None: + terminal.open_positions = [long_position()] + (raw,) = broker.GetPositions() + assert (raw.ticket, raw.type, raw.sl, raw.tp) == (1, 0, 0.0, 1.2) + (as_dict,) = broker.GetPositionsBySymbol("EURUSD", as_dict=True) + assert (as_dict["type"], as_dict["sl"], as_dict["profit"]) == (0, None, 3.0) + assert broker.GetPosition(ticket=1, as_dict=True) == as_dict + assert broker.GetPosition("XAUUSD") is None + + +def test_close_returns_true_only_when_something_closed( + broker: Broker, terminal: FakeTerminal +) -> None: + assert broker.Close("EURUSD") is False + terminal.open_positions = [long_position()] + assert broker.Close("EURUSD") is True + terminal.retcodes.append(10018) + assert broker.Close("EURUSD", ticket=1) is False + + +def test_limit_crossing_the_market_executes_immediately( + broker: Broker, terminal: FakeTerminal +) -> None: + broker.BuyLimit("EURUSD", 0.1, stoplimit=1.2) # ask 1.1001 <= 1.2 + broker.SellLimit("EURUSD", 0.1, stoplimit=1.0) # bid 1.1 >= 1.0 + assert [(r.side, r.pending) for r in orders(terminal)] == [(Side.BUY, None), (Side.SELL, None)] + + +def test_limit_away_from_the_market_rests(broker: Broker, terminal: FakeTerminal) -> None: + terminal.retcodes.extend([10008, 10008]) + assert broker.BuyLimit("EURUSD", 0.1, stoplimit=1.05) is not None + assert broker.SellLimit("EURUSD", 0.1, stoplimit=1.15) is not None + assert [r.pending for r in orders(terminal)] == [PendingKind.LIMIT, PendingKind.LIMIT] + + +def test_limit_rejects_price_argument_and_missing_quote( + broker: Broker, terminal: FakeTerminal +) -> None: + assert broker.BuyLimit("EURUSD", 0.1, 1.05, price=1.0) is None + terminal.ticks.clear() + assert broker.SellLimit("EURUSD", 0.1, 1.15) is None + assert terminal.sent == [] + + +def test_cancel_orders_removes_only_limit_orders(broker: Broker, terminal: FakeTerminal) -> None: + def pending(ticket: int, kind: PendingKind) -> PendingOrder: + return PendingOrder(ticket, "EURUSD", Side.BUY, kind, 0.1, 1.0, 0, "") + + terminal.open_orders = [pending(5, PendingKind.LIMIT), pending(6, PendingKind.STOP)] + broker.CancelOrders("EURUSD") + assert terminal.sent == [CancelRequest(order=5)] + + +def test_disconnect_shuts_the_terminal_down(broker: Broker, terminal: FakeTerminal) -> None: + broker.Disconnect() + assert terminal.shut_down + + +def test_login_with_to_effect_keeps_trying_until_it_works( + broker: Broker, terminal: FakeTerminal, clock: FakeClock +) -> None: + terminal.connect_failures = 2 + before = len(terminal.connected_with) + assert broker.login(ToEffect=True) is True + assert len(terminal.connected_with) - before == 3 + assert clock.sleeps[-2:] == [1.0, 1.0] + + +def test_broker_without_an_injected_terminal_uses_the_metatrader5_module( + no_real_terminal: FakeMT5, +) -> None: + no_real_terminal.positions = (raw_position(ticket=8),) + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", clock=FakeClock()) + assert [p.ticket for p in broker.GetPositions()] == [8] + assert no_real_terminal.calls[0][0] == "initialize" diff --git a/tests/unit/test_legacy_compat.py b/tests/unit/test_legacy_compat.py new file mode 100644 index 0000000..25b5b6d --- /dev/null +++ b/tests/unit/test_legacy_compat.py @@ -0,0 +1,128 @@ +"""2.x returned raw MT5 objects; scripts index them, unpack them and call _asdict().""" + +from __future__ import annotations + +from collections import deque + +import pytest + +from PythonMetaTrader5 import Broker +from PythonMetaTrader5.domain.requests import OrderRequest + +from .fakes import FakeClock, FakeTerminal, make_position + +# Field order of MetaTrader5.TradePosition / OrderSendResult (package 5.0.6231). +MT5_POSITION_FIELDS = ( + "ticket", + "time", + "time_msc", + "time_update", + "time_update_msc", + "type", + "magic", + "identifier", + "reason", + "volume", + "price_open", + "sl", + "tp", + "price_current", + "swap", + "profit", + "symbol", + "comment", + "external_id", +) +MT5_RECEIPT_FIELDS = ( + "retcode", + "deal", + "order", + "volume", + "price", + "bid", + "ask", + "comment", + "request_id", + "retcode_external", + "request", +) +V2_DICT_KEYS = { + "ticket", + "symbol", + "type", + "volume", + "price_open", + "sl", + "tp", + "price_current", + "profit", + "time", + "magic", + "comment", +} + + +@pytest.fixture +def broker(terminal: FakeTerminal) -> Broker: + with pytest.warns(DeprecationWarning, match="connect"): + return Broker(1, "pw", "Demo", terminal=terminal, clock=FakeClock()) + + +def sent_orders(terminal: FakeTerminal) -> list[OrderRequest]: + return [r for r in terminal.sent if isinstance(r, OrderRequest)] + + +def test_positions_carry_every_mt5_field_in_mt5_order( + broker: Broker, terminal: FakeTerminal +) -> None: + terminal.open_positions = [make_position(7, swap=-1.5, identifier=7, reason=3)] + (p,) = broker.GetPositions() + assert p._fields == MT5_POSITION_FIELDS + assert (p.swap, p.identifier, p.reason) == (-1.5, 7, 3) + assert p[0] == 7 # 2.x scripts index the raw tuple + + +def test_as_dict_keeps_exactly_the_2x_keys(broker: Broker, terminal: FakeTerminal) -> None: + terminal.open_positions = [make_position(7, swap=-1.5)] + (row,) = broker.GetPositions(as_dict=True) + assert set(row) == V2_DICT_KEYS + + +def test_entry_returns_an_order_send_result_shaped_receipt( + broker: Broker, terminal: FakeTerminal +) -> None: + receipt = broker.Buy("EURUSD", 0.1) + assert receipt._fields == MT5_RECEIPT_FIELDS + assert receipt[0] == receipt.retcode == 10009 + assert receipt._asdict()["retcode_external"] == 0 + # The original request object is not kept; scripts reading it get None. + assert receipt.request is None + + +def test_a_rejected_entry_returns_the_same_receipt_shape( + broker: Broker, terminal: FakeTerminal +) -> None: + terminal.retcodes = deque([10019]) + receipt = broker.Sell("EURUSD", 0.1) + assert receipt._fields == MT5_RECEIPT_FIELDS + assert receipt.retcode == 10019 + + +def test_numeric_strings_are_converted_as_2x_did(broker: Broker, terminal: FakeTerminal) -> None: + broker.OpenPosition("EURUSD", "buy", "0.1", price="1.10010", sl="1.09", tp="1.2") # type: ignore[arg-type] + broker.BuyLimit("EURUSD", "0.2", "1.05") # type: ignore[arg-type] + market, limit = sent_orders(terminal) + assert (market.volume, market.price, market.sl, market.tp) == (0.1, 1.1001, 1.09, 1.2) + assert (limit.volume, limit.price) == (0.2, 1.05) + + +def test_a_non_numeric_string_raises_as_2x_did(broker: Broker, terminal: FakeTerminal) -> None: + with pytest.raises(ValueError, match="could not convert"): + broker.Buy("EURUSD", "lots") # type: ignore[arg-type] + assert terminal.sent == [] + + +def test_ticket_wins_over_symbol_as_in_2x(broker: Broker, terminal: FakeTerminal) -> None: + terminal.open_positions = [make_position(1)] + (p,) = broker.GetPositions("XAUUSD", ticket=1) + assert (p.ticket, p.symbol) == (1, "EURUSD") diff --git a/tests/unit/test_legacy_failures.py b/tests/unit/test_legacy_failures.py new file mode 100644 index 0000000..a047235 --- /dev/null +++ b/tests/unit/test_legacy_failures.py @@ -0,0 +1,45 @@ +"""The 2.x facade degrades loudly: every failure is logged and returns 2.x's 'nothing'.""" + +import sys + +import pytest + +from PythonMetaTrader5 import Broker + +from .fakes import FakeClock +from .test_failure_paths import BrokenListing + + +def test_without_metatrader5_package_every_call_is_a_logged_no_op( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setitem(sys.modules, "MetaTrader5", None) + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", clock=FakeClock()) + assert "not installed" in caplog.text + assert broker.login() is False + assert broker.GetPositions() == [] + assert broker.Close("EURUSD") is False + assert broker.BuyLimit("EURUSD", 0.1, 1.0) is None + caplog.clear() + broker.CancelOrders("EURUSD") + assert "not connected" in caplog.text + broker.Disconnect() + assert "not connected" in caplog.text + + +def test_listing_failures_are_logged(caplog: pytest.LogCaptureFixture) -> None: + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=BrokenListing(), clock=FakeClock()) + assert broker.GetPositions() == [] + assert broker.Close("EURUSD") is False + broker.CancelOrders("EURUSD") + assert caplog.text.count("orders_get failed") == 1 + assert caplog.text.count("positions_get failed") == 2 + + +def test_limit_with_ticket_is_refused(caplog: pytest.LogCaptureFixture) -> None: + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=BrokenListing(), clock=FakeClock()) + assert broker.SellLimit("EURUSD", 0.1, 1.0, ticket=3) is None + assert "Close(ticket=...)" in caplog.text diff --git a/tests/unit/test_market.py b/tests/unit/test_market.py new file mode 100644 index 0000000..456cdde --- /dev/null +++ b/tests/unit/test_market.py @@ -0,0 +1,18 @@ +from PythonMetaTrader5.domain.market import Tick +from PythonMetaTrader5.domain.orders import Side + +from .fakes import make_position + + +def test_tick_quotes_the_price_a_side_trades_at() -> None: + tick = Tick(bid=1.1, ask=1.2) + assert tick.entry_price(Side.BUY) == 1.2 + assert tick.entry_price(Side.SELL) == 1.1 + assert tick.exit_price(Side.BUY) == 1.1 + assert tick.exit_price(Side.SELL) == 1.2 + + +def test_position_without_stops_reports_none() -> None: + position = make_position(7, side=Side.SELL, price_current=1.09, profit=10.0) + assert position.to_dict()["sl"] is None + assert position.to_dict()["side"] == "sell" diff --git a/tests/unit/test_mt5_adapter.py b/tests/unit/test_mt5_adapter.py new file mode 100644 index 0000000..ecb7184 --- /dev/null +++ b/tests/unit/test_mt5_adapter.py @@ -0,0 +1,201 @@ +from types import SimpleNamespace + +import pytest + +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.application.ports import Credentials +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.market import PendingKind, Tick +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest +from PythonMetaTrader5.domain.symbol import Filling +from PythonMetaTrader5.result import Err, Ok + +from .fake_mt5 import FakeMT5, raw_order, raw_position, symbol_info + +CREDENTIALS = Credentials(login=123, password="secret", server="Demo", timeout_ms=5000) + + +@pytest.fixture +def mt5() -> FakeMT5: + return FakeMT5() + + +@pytest.fixture +def adapter(mt5: FakeMT5) -> MetaTrader5Terminal: + return MetaTrader5Terminal(mt5) + + +def last_sent(mt5: FakeMT5) -> dict[str, object]: + name, (request,), _ = mt5.calls[-1] + assert name == "order_send" + return request # type: ignore[no-any-return] + + +def test_connect_passes_credentials_and_reports_failure( + adapter: MetaTrader5Terminal, mt5: FakeMT5 +) -> None: + assert adapter.connect(CREDENTIALS) == Ok(None) + assert mt5.calls[0] == ( + "initialize", + (), + {"login": 123, "password": "secret", "server": "Demo", "timeout": 5000}, + ) + mt5.initialize_ok, mt5.error = False, (-6, "Authorization failed") + result = adapter.connect(Credentials(1, "hunter2-pw", "s", path="C:/mt5/terminal64.exe")) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.CONNECTION_FAILED + assert "Authorization failed" in result.error.message + assert "hunter2" not in result.error.message + assert mt5.calls[-2][1] == ("C:/mt5/terminal64.exe",) + assert mt5.calls[-1][0] == "shutdown" + + +def test_password_never_appears_in_repr() -> None: + assert "secret" not in repr(CREDENTIALS) + + +def test_symbol_is_mapped_and_hidden_symbols_are_selected( + adapter: MetaTrader5Terminal, mt5: FakeMT5 +) -> None: + mt5.symbols["EURUSD"] = symbol_info(visible=False) + result = adapter.symbol("EURUSD") + assert isinstance(result, Ok) + assert (result.value.digits, result.value.tick_size) == (5, 1e-5) + assert ("symbol_select", ("EURUSD", True), {}) in mt5.calls + missing = adapter.symbol("NOPE") + assert isinstance(missing, Err) + assert missing.error.kind is ErrorKind.SYMBOL_NOT_FOUND + + +def test_tick_requires_a_two_sided_quote(adapter: MetaTrader5Terminal, mt5: FakeMT5) -> None: + mt5.ticks["EURUSD"] = SimpleNamespace(bid=1.1, ask=1.2) + assert adapter.tick("EURUSD") == Ok(Tick(1.1, 1.2)) + mt5.ticks["EURUSD"] = SimpleNamespace(bid=0.0, ask=0.0) + for name in ("EURUSD", "NOPE"): + result = adapter.tick(name) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.NO_PRICE + + +def test_market_close_request_is_translated(adapter: MetaTrader5Terminal, mt5: FakeMT5) -> None: + request = OrderRequest( + symbol="EURUSD", + side=Side.SELL, + volume=0.1, + price=1.1, + filling=Filling.FOK, + deviation=10, + magic=42, + comment="x", + sl=1.2, + position=7, + ) + result = adapter.send(request) + assert isinstance(result, Ok) + assert (result.value.retcode, result.value.deal, result.value.request_id) == (10009, 11, 13) + assert last_sent(mt5) == { + "action": 1, + "symbol": "EURUSD", + "volume": 0.1, + "type": 1, + "price": 1.1, + "deviation": 10, + "magic": 42, + "comment": "x", + "type_filling": 0, + "type_time": 0, + "sl": 1.2, + "position": 7, + } + + +def test_pending_and_cancel_requests_are_translated( + adapter: MetaTrader5Terminal, mt5: FakeMT5 +) -> None: + adapter.send( + OrderRequest( + symbol="EURUSD", + side=Side.BUY, + volume=0.1, + price=1.0, + filling=Filling.RETURN, + deviation=10, + magic=0, + tp=1.1, + pending=PendingKind.LIMIT, + ) + ) + sent = last_sent(mt5) + assert (sent["action"], sent["type"], sent["type_filling"], sent["tp"]) == (5, 2, 2, 1.1) + assert "sl" not in sent + adapter.send(CancelRequest(order=99)) + assert last_sent(mt5) == {"action": 8, "order": 99} + + +def test_undeliverable_request_is_a_terminal_error( + adapter: MetaTrader5Terminal, mt5: FakeMT5 +) -> None: + mt5.send_result, mt5.error = None, (-2, 'Invalid "comment" argument') + result = adapter.send(CancelRequest(order=1)) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.TERMINAL_ERROR + assert "comment" in result.error.message + + +def test_positions_are_mapped_with_zero_stops_as_none( + adapter: MetaTrader5Terminal, mt5: FakeMT5 +) -> None: + mt5.positions = (raw_position(sl=1.2),) + result = adapter.positions(symbol="EURUSD") + assert isinstance(result, Ok) + (position,) = result.value + assert (position.side, position.sl, position.tp, position.magic) == (Side.SELL, 1.2, None, 42) + adapter.positions(ticket=1) + adapter.positions() + filters = [kwargs for name, _, kwargs in mt5.calls if name == "positions_get"] + assert filters == [{"symbol": "EURUSD"}, {"ticket": 1}, {}] + + +def test_pending_orders_skip_non_pending_types(adapter: MetaTrader5Terminal, mt5: FakeMT5) -> None: + mt5.orders = (raw_order(5, type_=3), raw_order(6, type_=0), raw_order(7, type_=4)) + result = adapter.pending_orders(symbol="EURUSD") + assert isinstance(result, Ok) + kinds = [(o.ticket, o.side, o.kind, o.volume) for o in result.value] + assert kinds == [(5, Side.SELL, PendingKind.LIMIT, 0.2), (7, Side.BUY, PendingKind.STOP, 0.2)] + + +def test_listing_distinguishes_empty_from_failure( + adapter: MetaTrader5Terminal, mt5: FakeMT5 +) -> None: + mt5.positions = mt5.orders = None + assert adapter.positions() == Ok([]) + assert adapter.pending_orders() == Ok([]) + mt5.error = (-10004, "No IPC connection") + for result in (adapter.positions(), adapter.pending_orders()): + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.TERMINAL_ERROR + + +def test_shutdown_is_forwarded(adapter: MetaTrader5Terminal, mt5: FakeMT5) -> None: + adapter.shutdown() + assert mt5.calls[-1][0] == "shutdown" + + +def test_positions_and_receipts_keep_every_mt5_field( + adapter: MetaTrader5Terminal, mt5: FakeMT5 +) -> None: + mt5.positions = (raw_position(ticket=4),) + listed = adapter.positions() + assert isinstance(listed, Ok) + (p,) = listed.value + assert (p.swap, p.identifier, p.reason, p.external_id) == (-0.5, 4, 3, "") + assert (p.time_msc, p.time_update, p.time_update_msc) == ( + 1700000000123, + 1700000001, + 1700000001456, + ) + mt5.send_result.retcode_external = 77 # type: ignore[union-attr] + sent = adapter.send(CancelRequest(order=1)) + assert isinstance(sent, Ok) + assert sent.value.retcode_external == 77 diff --git a/tests/unit/test_mt5_namespace.py b/tests/unit/test_mt5_namespace.py new file mode 100644 index 0000000..a2225cb --- /dev/null +++ b/tests/unit/test_mt5_namespace.py @@ -0,0 +1,100 @@ +"""2.x re-exported the MetaTrader5 namespace; scripts call symbol_info() through it.""" + +from __future__ import annotations + +import subprocess +import sys +from types import SimpleNamespace +from typing import Any + +import pytest + +import PythonMetaTrader5 +from PythonMetaTrader5.adapters import mt5_session +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.market import Tick +from PythonMetaTrader5.result import Err + +from .fake_mt5 import FakeMT5 + + +def star_import() -> dict[str, Any]: + namespace: dict[str, Any] = {} + exec("from PythonMetaTrader5 import *", namespace) # noqa: S102 - the 2.x idiom itself + return namespace + + +def test_the_2x_star_import_brings_mt5_names_and_ours_win(no_real_terminal: FakeMT5) -> None: + names = star_import() + assert names["ORDER_TYPE_BUY"] == 0 + assert names["Tick"] is Tick # MT5 has its own Tick struct; ours wins + assert names["Broker"] is PythonMetaTrader5.Broker + names["symbol_select"]("EURUSD", True) + assert no_real_terminal.calls[-1] == ("symbol_select", ("EURUSD", True), {}) + for leaked_by_2x in ("time", "logger", "pyautogui"): + assert leaked_by_2x not in names + + +def test_re_exported_functions_run_under_the_adapters_session_lock( + no_real_terminal: FakeMT5, +) -> None: + held: list[bool] = [] + no_real_terminal.last_error = lambda: held.append(mt5_session.SESSION._is_owned()) or (1, "") # type: ignore[attr-defined, method-assign, func-returns-value] + PythonMetaTrader5.last_error() + assert held == [True] + + +def test_without_the_package_only_our_names_exist(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(sys.modules, "MetaTrader5", None) + names = star_import() + assert "Broker" in names + assert "symbol_info" not in names + with pytest.raises(AttributeError, match="symbol_info"): + _ = PythonMetaTrader5.symbol_info + + +@pytest.mark.parametrize( + "failure", + [ + ImportError("DLL load failed while importing _core"), + ModuleNotFoundError("No module named 'numpy'", name="numpy"), + AttributeError("module 'numpy' has no attribute '_ARRAY_API'"), + ValueError("numpy.dtype size changed"), + ], +) +def test_a_broken_install_is_reported_without_breaking_imports_or_tools( + monkeypatch: pytest.MonkeyPatch, failure: Exception +) -> None: + def broken(name: str) -> None: + raise failure + + # Replaces the importlib reference inside mt5_session only, not the stdlib. + monkeypatch.setattr(mt5_session, "importlib", SimpleNamespace(import_module=broken)) + with pytest.warns(RuntimeWarning, match="cannot be imported"): + names = star_import() + assert "connect" in names # a script using only connect() still imports + assert "symbol_info" not in names + assert not hasattr(PythonMetaTrader5, "symbol_info") + with pytest.raises(AttributeError, match="cannot be imported") as raised: + _ = PythonMetaTrader5.symbol_info + assert isinstance(raised.value.__cause__, ImportError) + loaded = MetaTrader5Terminal.load() + assert isinstance(loaded, Err) + assert loaded.error.kind is ErrorKind.CONNECTION_FAILED + assert loaded.error.message == f"MetaTrader5 is installed but cannot be imported: {failure}" + + +def test_importing_the_library_does_not_import_metatrader5() -> None: + # The re-export is lazy: pure-domain users and tooling never pay for or + # depend on the MetaTrader5 import. + probe = "import sys, PythonMetaTrader5; print('MetaTrader5' in sys.modules)" + out = subprocess.run( # noqa: S603 - fixed arguments, our own interpreter + [sys.executable, "-c", probe], capture_output=True, text=True, check=True + ) + assert out.stdout.strip() == "False" + + +def test_dir_lists_our_names_and_the_mt5_names(no_real_terminal: FakeMT5) -> None: + listed = dir(PythonMetaTrader5) + assert {"Broker", "connect", "symbol_info", "ORDER_TYPE_BUY"} <= set(listed) diff --git a/tests/unit/test_open_position.py b/tests/unit/test_open_position.py new file mode 100644 index 0000000..48b861a --- /dev/null +++ b/tests/unit/test_open_position.py @@ -0,0 +1,104 @@ +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind, TradeError +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.requests import OrderRequest +from PythonMetaTrader5.domain.stops import Stop +from PythonMetaTrader5.domain.symbol import Filling +from PythonMetaTrader5.result import Err, Ok + +from .fakes import FakeClock, FakeTerminal + + +def only_request(terminal: FakeTerminal) -> OrderRequest: + (request,) = terminal.sent + assert isinstance(request, OrderRequest) + return request + + +def test_buy_uses_ask_and_resolves_point_stops(trader: Trader, terminal: FakeTerminal) -> None: + result = trader.open_position( + "EURUSD", "buy", 0.1, sl=Stop.points(1000), tp=Stop.points(1500), comment="hook" + ) + assert isinstance(result, Ok) + request = only_request(terminal) + assert (request.side, request.price, request.volume) == (Side.BUY, 1.1001, 0.1) + assert (request.sl, request.tp) == (1.0901, 1.1151) + assert (request.filling, request.magic, request.comment) == (Filling.FOK, 42, "hook") + assert request.position is None + + +def test_sell_uses_bid_and_plain_float_stops_are_prices( + trader: Trader, terminal: FakeTerminal +) -> None: + trader.open_position("XAUUSD", Side.SELL, 0.1, sl=2410.123, tp=2390.0) + request = only_request(terminal) + assert (request.price, request.sl, request.tp) == (2400.0, 2410.12, 2390.0) + assert request.filling is Filling.IOC + + +def test_requote_is_retried_with_a_fresh_quote( + trader: Trader, terminal: FakeTerminal, clock: FakeClock +) -> None: + terminal.quote("EURUSD", (1.1, 1.1001), (1.1002, 1.1003)) + terminal.retcodes.extend([10004, 10009]) + assert isinstance(trader.open_position("EURUSD", "buy", 0.1), Ok) + assert [r.price for r in terminal.sent] == [1.1001, 1.1003] # type: ignore[union-attr] + assert clock.sleeps == [0.5] + + +def test_retries_are_bounded(trader: Trader, terminal: FakeTerminal) -> None: + terminal.retcodes.extend([10004] * 10) + result = trader.open_position("EURUSD", "buy", 0.1) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.RETRIES_EXHAUSTED + assert result.error.retcode == 10004 + assert len(terminal.sent) == 3 + + +def test_permanent_failure_is_not_retried(trader: Trader, terminal: FakeTerminal) -> None: + terminal.retcodes.append(10018) + result = trader.open_position("EURUSD", "buy", 0.1) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.MARKET_CLOSED + assert result.error.receipt is not None + assert len(terminal.sent) == 1 + + +def test_transport_failure_is_returned_without_retry( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.send_failure = TradeError(ErrorKind.TERMINAL_ERROR, "IPC broken") + result = trader.open_position("EURUSD", "buy", 0.1) + assert result == Err(terminal.send_failure) + assert len(terminal.sent) == 1 + + +def test_explicit_price_is_normalized_and_sent_once(trader: Trader, terminal: FakeTerminal) -> None: + terminal.retcodes.append(10004) + result = trader.open_position("EURUSD", "buy", 0.1, price=1.123456, sl=Stop.points(100)) + assert isinstance(result, Err) + request = only_request(terminal) + assert (request.price, request.sl) == (1.12346, 1.12246) + + +def test_invalid_input_never_reaches_the_terminal(trader: Trader, terminal: FakeTerminal) -> None: + cases = [ + (trader.open_position("EURUSD", "hold", 0.1), ErrorKind.INVALID_ARGUMENT), + (trader.open_position("EURUSD", "buy", 0.015), ErrorKind.INVALID_VOLUME), + (trader.open_position("NOPE", "buy", 0.1), ErrorKind.SYMBOL_NOT_FOUND), + ( + trader.open_position("EURUSD", "buy", 0.1, comment="c" * 40), + ErrorKind.INVALID_ARGUMENT, + ), + ] + for result, kind in cases: + assert isinstance(result, Err) + assert result.error.kind is kind + assert terminal.sent == [] + + +def test_missing_quote_is_an_error(trader: Trader, terminal: FakeTerminal) -> None: + terminal.ticks.clear() + result = trader.open_position("EURUSD", "buy", 0.1) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.NO_PRICE diff --git a/tests/unit/test_orders.py b/tests/unit/test_orders.py new file mode 100644 index 0000000..ec67c67 --- /dev/null +++ b/tests/unit/test_orders.py @@ -0,0 +1,36 @@ +import pytest + +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.orders import Side, validate_comment +from PythonMetaTrader5.result import Err, Ok + + +@pytest.mark.parametrize( + ("text", "side"), + [("buy", Side.BUY), ("LONG", Side.BUY), (" sell ", Side.SELL), ("short", Side.SELL)], +) +def test_side_parses_aliases(text: str, side: Side) -> None: + assert Side.parse(text) == Ok(side) + assert Side.parse(side) == Ok(side) + + +def test_unknown_side_is_rejected() -> None: + result = Side.parse("hold") + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_ARGUMENT + + +def test_side_has_opposite() -> None: + assert Side.BUY.opposite is Side.SELL + assert Side.SELL.opposite is Side.BUY + + +def test_comment_within_terminal_limit_is_kept() -> None: + assert validate_comment(None) == Ok("") + assert validate_comment("x" * 31) == Ok("x" * 31) + + +def test_comment_over_terminal_limit_is_rejected_not_truncated() -> None: + result = validate_comment("x" * 32) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_ARGUMENT diff --git a/tests/unit/test_pending_orders.py b/tests/unit/test_pending_orders.py new file mode 100644 index 0000000..03c9cb5 --- /dev/null +++ b/tests/unit/test_pending_orders.py @@ -0,0 +1,96 @@ +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.market import PendingKind, PendingOrder +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest +from PythonMetaTrader5.domain.stops import Stop +from PythonMetaTrader5.domain.symbol import Filling +from PythonMetaTrader5.result import Err, Ok + +from .fakes import FakeTerminal, make_position + + +def test_limit_order_is_placed_at_its_level(trader: Trader, terminal: FakeTerminal) -> None: + terminal.retcodes.append(10008) + result = trader.place_limit_order("EURUSD", "buy", 0.1, 1.0950004, sl=Stop.points(50)) + assert isinstance(result, Ok) + (request,) = terminal.sent + assert isinstance(request, OrderRequest) + assert (request.pending, request.price, request.sl) == (PendingKind.LIMIT, 1.095, 1.0945) + assert request.filling is Filling.FOK + + +def test_limit_order_rejected_by_server_is_an_error(trader: Trader, terminal: FakeTerminal) -> None: + terminal.retcodes.append(10015) + result = trader.place_limit_order("EURUSD", "sell", 0.1, 1.0) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_PRICE + + +def order(ticket: int, symbol: str, magic: int = 42) -> PendingOrder: + return PendingOrder( + ticket=ticket, + symbol=symbol, + side=Side.BUY, + kind=PendingKind.LIMIT, + volume=0.1, + price=1.0, + magic=magic, + comment="", + ) + + +def test_cancel_removes_every_pending_order_of_the_symbol( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.open_orders = [order(5, "EURUSD"), order(6, "XAUUSD"), order(7, "EURUSD", magic=1)] + result = trader.cancel_pending_orders("EURUSD") + assert isinstance(result, Ok) + assert terminal.sent == [CancelRequest(order=5), CancelRequest(order=7)] + + +def test_cancel_with_magic_filter(trader: Trader, terminal: FakeTerminal) -> None: + terminal.open_orders = [order(5, "EURUSD"), order(7, "EURUSD", magic=1)] + trader.cancel_pending_orders("EURUSD", magic=1) + assert terminal.sent == [CancelRequest(order=7)] + + +def test_queries_filter_by_magic(trader: Trader, terminal: FakeTerminal) -> None: + terminal.open_orders = [order(5, "EURUSD"), order(7, "EURUSD", magic=1)] + pending = trader.pending_orders(magic=1) + assert isinstance(pending, Ok) + assert [o.ticket for o in pending.value] == [7] + terminal.open_positions = [make_position(1, magic=1), make_position(2, magic=0)] + positions = trader.positions("EURUSD", magic=1) + assert isinstance(positions, Ok) + assert [p.ticket for p in positions.value] == [1] + + +def test_shutdown_releases_the_terminal(trader: Trader, terminal: FakeTerminal) -> None: + trader.shutdown() + assert terminal.shut_down + + +def test_invalid_limit_order_never_reaches_the_terminal( + trader: Trader, terminal: FakeTerminal +) -> None: + result = trader.place_limit_order("EURUSD", "buy", 1000.0, 1.0) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_VOLUME + assert terminal.sent == [] + + +def test_cancel_can_be_limited_to_one_order_kind(trader: Trader, terminal: FakeTerminal) -> None: + stop = PendingOrder( + ticket=8, + symbol="EURUSD", + side=Side.SELL, + kind=PendingKind.STOP, + volume=0.1, + price=1.0, + magic=42, + comment="", + ) + terminal.open_orders = [order(5, "EURUSD"), stop] + trader.cancel_pending_orders("EURUSD", kind=PendingKind.LIMIT) + assert terminal.sent == [CancelRequest(order=5)] diff --git a/tests/unit/test_result.py b/tests/unit/test_result.py new file mode 100644 index 0000000..071b41b --- /dev/null +++ b/tests/unit/test_result.py @@ -0,0 +1,21 @@ +from PythonMetaTrader5.result import Err, Ok, Result + + +def describe(result: Result[int, str]) -> str: + match result: + case Ok(value): + return f"ok:{value}" + case Err(error): + return f"err:{error}" + + +def test_ok_and_err_are_pattern_matchable() -> None: + assert describe(Ok(3)) == "ok:3" + assert describe(Err("boom")) == "err:boom" + + +def test_ok_and_err_report_their_state() -> None: + assert Ok(1).is_ok() + assert not Ok(1).is_err() + assert Err("x").is_err() + assert not Err("x").is_ok() diff --git a/tests/unit/test_retcodes.py b/tests/unit/test_retcodes.py new file mode 100644 index 0000000..90b21fa --- /dev/null +++ b/tests/unit/test_retcodes.py @@ -0,0 +1,45 @@ +import pytest + +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.retcodes import Outcome, classify, error_for + + +@pytest.mark.parametrize("retcode", [10008, 10009, 10010]) +def test_done_placed_and_partial_are_success(retcode: int) -> None: + assert classify(retcode) is Outcome.SUCCESS + + +@pytest.mark.parametrize("retcode", [10004, 10020, 10021, 10024]) +def test_price_moves_and_throttling_are_retried(retcode: int) -> None: + assert classify(retcode) is Outcome.RETRY + + +@pytest.mark.parametrize("retcode", [10012, 10031]) +def test_timeout_and_lost_connection_are_never_retried(retcode: int) -> None: + # Retrying when the request may already be on the server risks a double fill. + assert classify(retcode) is Outcome.FAIL + assert error_for(retcode).kind is ErrorKind.OUTCOME_UNKNOWN + + +@pytest.mark.parametrize( + ("retcode", "kind"), + [ + (10018, ErrorKind.MARKET_CLOSED), + (10019, ErrorKind.NO_MONEY), + (10014, ErrorKind.INVALID_VOLUME), + (10016, ErrorKind.INVALID_STOPS), + (10015, ErrorKind.INVALID_PRICE), + (10030, ErrorKind.INVALID_FILLING), + (10027, ErrorKind.ALGO_TRADING_DISABLED), + (10017, ErrorKind.TRADE_DISABLED), + (10040, ErrorKind.LIMIT_REACHED), + (10006, ErrorKind.REJECTED), + (99999, ErrorKind.REJECTED), + ], +) +def test_permanent_failures_map_to_a_kind(retcode: int, kind: ErrorKind) -> None: + assert classify(retcode) is Outcome.FAIL + error = error_for(retcode) + assert error.kind is kind + assert error.retcode == retcode + assert error.message diff --git a/tests/unit/test_safety_edges.py b/tests/unit/test_safety_edges.py new file mode 100644 index 0000000..6702d63 --- /dev/null +++ b/tests/unit/test_safety_edges.py @@ -0,0 +1,178 @@ +"""Edge cases where a mistake would close, duplicate or silently lose trades.""" + +import sys +from dataclasses import replace + +import pytest + +from PythonMetaTrader5 import Broker, connect +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.application.ports import Credentials +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.market import PendingKind, PendingOrder, Position +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.requests import CancelRequest +from PythonMetaTrader5.domain.symbol import Filling +from PythonMetaTrader5.result import Err, Ok + +from .fake_mt5 import FakeMT5, symbol_info +from .fakes import FakeClock, FakeTerminal, make_position + + +def position(ticket: int, volume: float = 0.5) -> Position: + return make_position(ticket, volume=volume, price_open=1.0, price_current=1.0) + + +def test_empty_symbol_is_rejected_instead_of_meaning_all( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.open_positions = [position(1)] + for result in ( + trader.close_positions(""), + trader.cancel_pending_orders(""), + ): + assert isinstance(result, Err) + assert result.error.errors[0].kind is ErrorKind.INVALID_ARGUMENT + for query in (trader.positions(""), trader.pending_orders("")): + assert isinstance(query, Err) + assert query.error.kind is ErrorKind.INVALID_ARGUMENT + assert terminal.sent == [] + + +def test_adapter_passes_an_empty_symbol_through_as_a_filter() -> None: + mt5 = FakeMT5() + adapter = MetaTrader5Terminal(mt5) + adapter.positions(symbol="") + adapter.pending_orders(symbol="") + filters = [kwargs for name, _, kwargs in mt5.calls if name in {"positions_get", "orders_get"}] + assert filters == [{"symbol": ""}, {"symbol": ""}] + + +def test_legacy_close_without_symbol_or_ticket_closes_nothing( + terminal: FakeTerminal, caplog: pytest.LogCaptureFixture +) -> None: + terminal.open_positions = [position(1)] + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=terminal, clock=FakeClock()) + assert broker.Close(None) is False + assert terminal.sent == [] + assert "symbol or ticket" in caplog.text + + +@pytest.mark.parametrize( + ("code", "kind"), + [ + (-10005, ErrorKind.OUTCOME_UNKNOWN), # IPC timeout: request may be on the server + (-10001, ErrorKind.OUTCOME_UNKNOWN), + (-2, ErrorKind.TERMINAL_ERROR), # invalid arguments: never sent + (-10004, ErrorKind.TERMINAL_ERROR), # no IPC connection: never sent + (-8, ErrorKind.ALGO_TRADING_DISABLED), + ], +) +def test_undelivered_send_is_unknown_unless_provably_not_sent(code: int, kind: ErrorKind) -> None: + mt5 = FakeMT5() + mt5.send_result, mt5.error = None, (code, "x") + result = MetaTrader5Terminal(mt5).send(CancelRequest(order=1)) + assert isinstance(result, Err) + assert result.error.kind is kind + + +def test_symbol_that_cannot_be_selected_is_an_error() -> None: + mt5 = FakeMT5() + mt5.symbols["GBPJPY"] = symbol_info("GBPJPY", visible=False) + mt5.symbol_select = lambda name, enable: False # type: ignore[method-assign] + result = MetaTrader5Terminal(mt5).symbol("GBPJPY") + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.SYMBOL_NOT_FOUND + + +def test_first_missing_quote_after_selection_is_waited_for( + trader: Trader, terminal: FakeTerminal, clock: FakeClock +) -> None: + terminal.ticks.clear() + terminal.missing_quotes = 1 + terminal.quote("EURUSD", (1.1, 1.1001)) + assert isinstance(trader.open_position("EURUSD", "buy", 0.1), Ok) + assert clock.sleeps == [0.5] + assert len(terminal.sent) == 1 + + +def test_partial_close_is_a_failure(trader: Trader, terminal: FakeTerminal) -> None: + terminal.open_positions = [position(1)] + terminal.retcodes.append(10010) + closed = trader.close_positions("EURUSD") + assert isinstance(closed, Err) + assert closed.error.errors[0].kind is ErrorKind.PARTIAL_FILL + + +def test_limit_order_uses_a_filling_mode_the_symbol_allows( + trader: Trader, terminal: FakeTerminal +) -> None: + trader.place_limit_order("XAUUSD", "buy", 0.1, 2300.0) + (request,) = terminal.sent + assert request.filling is Filling.IOC # type: ignore[union-attr] + + +def test_close_all_reads_each_symbol_spec_once(trader: Trader, terminal: FakeTerminal) -> None: + terminal.open_positions = [position(1), position(2), position(3)] + assert isinstance(trader.close_positions("EURUSD"), Ok) + assert terminal.symbol_lookups == ["EURUSD"] + + +@pytest.mark.parametrize("login", [None, 1.5e400, "abc", [1]]) +def test_unusable_login_is_an_error_not_an_exception(login: object) -> None: + result = connect(login, "pw", "Demo") # type: ignore[arg-type] + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_ARGUMENT + + +def test_failed_login_releases_the_terminal(monkeypatch: pytest.MonkeyPatch) -> None: + mt5 = FakeMT5() + mt5.initialize_ok = False + monkeypatch.setitem(sys.modules, "MetaTrader5", mt5) + assert isinstance(connect(1, "pw", "Demo"), Err) + assert mt5.calls[-1][0] == "shutdown" + + +def test_limit_on_an_exchange_symbol_rests_with_return_filling( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.specs["EURUSD"] = replace(terminal.specs["EURUSD"], exchange_execution=True) + trader.place_limit_order("EURUSD", "buy", 0.1, 1.05) + trader.open_position("EURUSD", "buy", 0.1) + limit, market = terminal.sent + assert limit.filling is Filling.RETURN # type: ignore[union-attr] + assert market.filling is Filling.FOK # type: ignore[union-attr] + + +def test_close_answered_with_placed_is_not_reported_as_closed( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.open_positions = [position(1)] + terminal.retcodes.append(10008) + result = trader.close_positions("EURUSD") + assert isinstance(result, Err) + assert result.error.errors[0].kind is ErrorKind.OUTCOME_UNKNOWN + + +def test_legacy_cancel_orders_without_symbol_cancels_nothing(terminal: FakeTerminal) -> None: + terminal.open_orders = [PendingOrder(5, "EURUSD", Side.BUY, PendingKind.LIMIT, 0.1, 1.0, 0, "")] + with pytest.warns(DeprecationWarning, match="connect"): + broker = Broker(1, "pw", "Demo", terminal=terminal, clock=FakeClock()) + broker.CancelOrders(None) # type: ignore[arg-type] + assert terminal.sent == [] + + +@pytest.mark.parametrize("login", [True, 12345678.9, "12 34", -5]) +def test_login_that_would_be_coerced_is_rejected(login: object) -> None: + result = connect(login, "pw", "Demo") # type: ignore[arg-type] + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_ARGUMENT + + +def test_adapter_releases_the_session_after_a_failed_login() -> None: + mt5 = FakeMT5() + mt5.initialize_ok = False + assert isinstance(MetaTrader5Terminal(mt5).connect(Credentials(1, "pw", "s")), Err) + assert [name for name, _, _ in mt5.calls] == ["initialize", "shutdown"] diff --git a/tests/unit/test_stops.py b/tests/unit/test_stops.py new file mode 100644 index 0000000..cb02f82 --- /dev/null +++ b/tests/unit/test_stops.py @@ -0,0 +1,39 @@ +import pytest + +from PythonMetaTrader5.domain.orders import Side +from PythonMetaTrader5.domain.stops import Stop +from PythonMetaTrader5.domain.symbol import SymbolSpec +from PythonMetaTrader5.result import Ok + +SPEC = SymbolSpec( + name="EURUSD", + digits=5, + point=0.00001, + tick_size=0.00001, + volume_min=0.01, + volume_max=100.0, + volume_step=0.01, + filling_flags=1, + exchange_execution=False, +) + + +def test_absolute_stop_is_only_normalized() -> None: + assert Stop.at_price(1.123456).stop_loss(Side.BUY, 1.2, SPEC) == Ok(1.12346) + assert Stop.at_price(1.123456).take_profit(Side.SELL, 1.2, SPEC) == Ok(1.12346) + + +@pytest.mark.parametrize( + ("side", "stop_loss", "take_profit"), + [(Side.BUY, 1.09, 1.115), (Side.SELL, 1.11, 1.085)], +) +def test_point_offsets_follow_trade_direction( + side: Side, stop_loss: float, take_profit: float +) -> None: + reference = 1.1 + assert Stop.points(1000).stop_loss(side, reference, SPEC) == Ok(stop_loss) + assert Stop.points(1500).take_profit(side, reference, SPEC) == Ok(take_profit) + + +def test_negative_offset_is_treated_as_distance() -> None: + assert Stop.points(-1000).stop_loss(Side.BUY, 1.1, SPEC) == Ok(1.09) diff --git a/tests/unit/test_symbol.py b/tests/unit/test_symbol.py new file mode 100644 index 0000000..2145226 --- /dev/null +++ b/tests/unit/test_symbol.py @@ -0,0 +1,71 @@ +import pytest + +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.domain.symbol import Filling, SymbolSpec +from PythonMetaTrader5.result import Err, Ok + + +def eurusd(**overrides: object) -> SymbolSpec: + fields: dict[str, object] = { + "name": "EURUSD", + "digits": 5, + "point": 0.00001, + "tick_size": 0.00001, + "volume_min": 0.01, + "volume_max": 100.0, + "volume_step": 0.01, + "filling_flags": 1, + "exchange_execution": False, + } + fields.update(overrides) + return SymbolSpec(**fields) # type: ignore[arg-type] + + +def on_grid(spec: SymbolSpec, price: float) -> object: + return spec.price_on_grid(price, ErrorKind.INVALID_PRICE, "price") + + +def test_prices_snap_to_the_tick_without_float_noise() -> None: + assert on_grid(eurusd(), 1.123456) == Ok(1.12346) + assert on_grid(eurusd(), 1.1) == Ok(1.1) + + +def test_prices_use_a_tick_size_coarser_than_point() -> None: + index = eurusd(name="US500", digits=2, point=0.01, tick_size=0.25) + assert on_grid(index, 5780.13) == Ok(5780.25) + + +def test_prices_fall_back_to_point_when_tick_size_missing() -> None: + assert on_grid(eurusd(tick_size=0.0), 1.123456) == Ok(1.12346) + + +@pytest.mark.parametrize("volume", [0.01, 0.1, 0.37, 100.0]) +def test_valid_volume_is_accepted(volume: float) -> None: + assert eurusd().validate_volume(volume) == Ok(volume) + + +@pytest.mark.parametrize("volume", [0.0, 0.005, 0.015, 100.01, -1.0]) +def test_invalid_volume_is_rejected(volume: float) -> None: + result = eurusd().validate_volume(volume) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_VOLUME + + +@pytest.mark.parametrize( + ("flags", "expected"), + [ + (1, Filling.FOK), + (2, Filling.IOC), + (3, Filling.FOK), + (0, Filling.RETURN), + (4, Filling.RETURN), + ], +) +def test_market_filling_prefers_fill_or_kill(flags: int, expected: Filling) -> None: + assert eurusd(filling_flags=flags).market_filling() is expected + + +def test_pricing_on_broken_data_is_a_terminal_error_even_when_called_directly() -> None: + result = on_grid(eurusd(point=0.0, tick_size=0.0), 1.1) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.BROKEN_SYMBOL_DATA diff --git a/tests/unit/test_symbol_data.py b/tests/unit/test_symbol_data.py new file mode 100644 index 0000000..995839c --- /dev/null +++ b/tests/unit/test_symbol_data.py @@ -0,0 +1,166 @@ +"""Broken data from the terminal must never price an order, and never block a close.""" + +from __future__ import annotations + +import math +from dataclasses import replace +from fractions import Fraction +from types import SimpleNamespace + +import pytest + +from PythonMetaTrader5 import Stop +from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal +from PythonMetaTrader5.application.trader import Trader +from PythonMetaTrader5.domain.errors import ErrorKind +from PythonMetaTrader5.result import Err, Ok + +from .fake_mt5 import FakeMT5, symbol_info +from .fakes import EURUSD, FakeTerminal, make_position + +BROKEN_STEP = [{"point": 0.0, "tick_size": 0.0}, {"point": math.inf, "tick_size": 0.0}] +BROKEN_STEP += [{"tick_size": math.inf}, {"point": math.nan, "tick_size": 0.0}] +BROKEN_STEP += [{"tick_size": math.nan}, {"tick_size": -0.25}, {"digits": -1}] +BROKEN_VOLUME = [{"volume_step": 0.0}, {"volume_min": 0.0}, {"volume_max": 0.001}] +BROKEN_VOLUME += [{"volume_max": math.nan}, {"volume_step": math.inf}] + + +@pytest.mark.parametrize("broken", BROKEN_STEP) +def test_a_symbol_without_a_usable_step_prices_nothing( + trader: Trader, terminal: FakeTerminal, broken: dict[str, float] +) -> None: + terminal.specs["EURUSD"] = replace(EURUSD, **broken) + for result in ( + trader.place_limit_order("EURUSD", "buy", 0.1, 1.05), + trader.open_position("EURUSD", "buy", 0.1, sl=1.0), + trader.open_position("EURUSD", "buy", 0.1), # no price, no stops + ): + assert isinstance(result, Err) + # The broker's data is at fault, not the caller's input. + assert result.error.kind is ErrorKind.BROKEN_SYMBOL_DATA + assert terminal.sent == [] + + +def test_broken_data_is_reported_before_the_callers_volume_is_judged( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.specs["EURUSD"] = replace(EURUSD, tick_size=math.nan) + result = trader.open_position("EURUSD", "buy", 1000.0) # above volume_max too + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.BROKEN_SYMBOL_DATA + + +def test_a_hand_built_spec_with_a_non_number_is_refused_not_raised() -> None: + spec = replace(EURUSD, point=None, tick_size=0.0) # type: ignore[arg-type] + result = spec.check_tradable() + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.BROKEN_SYMBOL_DATA + + +@pytest.mark.parametrize("point", [0.0, math.inf, math.nan]) +def test_points_stops_need_a_usable_point_but_prices_do_not( + trader: Trader, terminal: FakeTerminal, point: float +) -> None: + # A tick size alone is enough for absolute prices; only points need `point`. + terminal.specs["EURUSD"] = replace(EURUSD, point=point) + refused = trader.open_position("EURUSD", "buy", 0.1, sl=Stop.points(1000)) + assert isinstance(refused, Err) + assert refused.error.kind is ErrorKind.BROKEN_SYMBOL_DATA + assert terminal.sent == [] + assert isinstance(trader.open_position("EURUSD", "buy", 0.1, sl=1.09), Ok) + + +@pytest.mark.parametrize("broken", BROKEN_VOLUME) +def test_unusable_volume_limits_refuse_every_entry( + trader: Trader, terminal: FakeTerminal, broken: dict[str, float] +) -> None: + terminal.specs["EURUSD"] = replace(EURUSD, **broken) + result = trader.open_position("EURUSD", "buy", 0.1) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.BROKEN_SYMBOL_DATA + assert terminal.sent == [] + + +@pytest.mark.parametrize("broken", [*BROKEN_STEP, *BROKEN_VOLUME]) +def test_a_position_on_a_symbol_with_broken_data_can_still_be_closed( + trader: Trader, terminal: FakeTerminal, broken: dict[str, float] +) -> None: + terminal.specs["EURUSD"] = replace(EURUSD, **broken) + terminal.open_positions = [make_position(1)] + closed = trader.close_positions("EURUSD") + assert isinstance(closed, Ok) + assert len(closed.value) == 1 + + +def test_the_adapter_passes_broken_symbol_data_on_so_closes_still_work() -> None: + # Refusing it in the adapter would block close_positions (the a0f2aba bug). + mt5 = FakeMT5() + info = symbol_info() + info.point, info.trade_tick_size, info.volume_step = 0.0, 0.0, 0.0 + mt5.symbols["EURUSD"] = info + spec = MetaTrader5Terminal(mt5).symbol("EURUSD") + assert isinstance(spec, Ok) + assert isinstance(spec.value.check_tradable(), Err) + + +@pytest.mark.parametrize("quote", [math.nan, math.inf]) +def test_a_nan_or_infinite_quote_is_no_price(quote: float) -> None: + mt5 = FakeMT5() + mt5.ticks["EURUSD"] = SimpleNamespace(bid=1.1, ask=quote) + result = MetaTrader5Terminal(mt5).tick("EURUSD") + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.NO_PRICE + + +class _OutOfRange(Fraction): + # Stands in for a numpy longdouble under np.seterr(over="raise"). + def __float__(self) -> float: + raise FloatingPointError("overflow") + + +def test_a_number_whose_float_conversion_overflows_is_refused_not_raised( + trader: Trader, terminal: FakeTerminal +) -> None: + result = trader.open_position("EURUSD", "buy", _OutOfRange(1, 10)) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_VOLUME + assert terminal.sent == [] + + +def test_a_bad_price_is_reported_before_a_bad_stop(trader: Trader) -> None: + result = trader.place_limit_order("EURUSD", "buy", 0.1, 1e-6, sl=1e-6) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_PRICE + + +def test_absolute_stops_are_checked_before_the_quote_is_fetched( + trader: Trader, terminal: FakeTerminal +) -> None: + # No quote: a stop that can never be valid must not wait for retries first. + terminal.ticks.clear() + result = trader.open_position("EURUSD", "buy", 0.1, sl=1e-6) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_STOPS + + +def test_a_points_take_profit_below_zero_is_refused(trader: Trader, terminal: FakeTerminal) -> None: + result = trader.open_position("EURUSD", "sell", 0.1, tp=Stop.points(10_000_000)) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.INVALID_STOPS + assert terminal.sent == [] + + +def test_a_points_stop_on_a_limit_needs_a_usable_point( + trader: Trader, terminal: FakeTerminal +) -> None: + terminal.specs["EURUSD"] = replace(EURUSD, point=0.0) + result = trader.place_limit_order("EURUSD", "buy", 0.1, 1.05, sl=Stop.points(100)) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.BROKEN_SYMBOL_DATA + assert terminal.sent == [] + + +def test_volume_checked_directly_on_broken_limits_is_broken_symbol_data() -> None: + result = replace(EURUSD, volume_step=0.0).validate_volume(0.1) + assert isinstance(result, Err) + assert result.error.kind is ErrorKind.BROKEN_SYMBOL_DATA