Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ All notable changes to this project are documented here. The format follows

## [Unreleased]

### Fixed
- A defaulted `close_positions()` / `cancel_pending_orders()` that matched
nothing dropped a failure of its follow-up check for items with other magics
left open, so `Ok([])` could read as "flat" in silence on a netting account.
It now logs a warning that it could not check.

### Changed
- README: a table of contents, an index of every ADR, and the essentials in
one place: connecting, magic-number scope (symbol, ticket, magic 0 on a
single-bot account, netting), error kinds with what to do, batch failures,
and a checklist before trading real money. The README may have up to 600
lines; every other file keeps the 300-line limit. Links to other documents
are absolute GitHub URLs, so they also work on PyPI.

## [3.0.0] - 2026-11-09

Complete rewrite. See [MIGRATION.md](MIGRATION.md) for every behaviour change.
Expand Down
399 changes: 327 additions & 72 deletions README.md

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion docs/adr/0011-close-all-defaults-to-own-magic.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ gives trades opened by hand magic 0.
a property of netting, not of this default. So that `Ok([])` never reads
as "flat" in silence, a defaulted close/cancel that matches nothing while
items with other magics are in scope logs a warning naming how many were
left open (one extra listing, only on that path). We did not detect the
left open (one extra listing, only on that path). If that listing fails,
the warning says so instead of dropping the error; the close/cancel stays
`Ok`, because it did what was asked and an `Err` would invite a retry of an
action that already ran. We did not detect the
account's margin mode: it would add a port call for a case the warning
already surfaces.
- `application/magic_scope.py` holds the rule and its warnings, apart from
Expand Down
12 changes: 9 additions & 3 deletions scripts/check_file_length.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
MAX_LINES = 300
# Binary or third-party verbatim files; nothing generated is tracked.
EXEMPT_SUFFIXES = {".png", ".jpg", ".ico", ".whl"}
# The owner's call (2026-11-09): the README is the landing page on GitHub and
# PyPI, so it keeps every essential behind a table of contents rather than
# sending readers through several pages. A higher ceiling, not none: an
# unbounded exemption would let a pasted log through. Only the top-level README.
LIMITS = {Path("README.md"): 600}


def tracked_files() -> list[Path]:
Expand All @@ -23,10 +28,11 @@ def main() -> int:
for path in tracked_files():
if path.suffix in EXEMPT_SUFFIXES or not path.is_file():
continue
limit = LIMITS.get(path, MAX_LINES)
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")
if count > limit:
offenders.append(f"{path}: {count} lines (limit {limit})")
print("\n".join(offenders) or "all tracked files are within their line limits")
return 1 if offenders else 0


Expand Down
12 changes: 11 additions & 1 deletion src/PythonMetaTrader5/application/magic_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,17 @@ def warn_about_default(
# that kept another magic, and Ok([]) alone would read as "flat". The extra
# listing runs only on this path.
others = everything()
if isinstance(others, Ok) and others.value:
if not isinstance(others, Ok):
# Not turned into an Err: the close/cancel itself did what was asked,
# and failing it would make a bot retry an action that already ran.
log.warning(
"nothing with magic %s to close/cancel, and could not check for items "
"with other magics left open: %s",
own,
others.error,
)
return
if others.value:
log.warning(
"nothing with magic %s to close/cancel; %d item(s) with other magics "
"left open (on netting a deal merges into a position that keeps its "
Expand Down
56 changes: 56 additions & 0 deletions tests/unit/test_check_file_length.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""The line-limit guard that CI runs over every tracked file."""

from __future__ import annotations

import importlib.util
from pathlib import Path
from types import ModuleType

import pytest

SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "check_file_length.py"


def load_script() -> ModuleType:
spec = importlib.util.spec_from_file_location("check_file_length", SCRIPT)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module


def run_on(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, name: str, lines: int) -> int:
script = load_script()
target = tmp_path / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("x\n" * lines, encoding="utf-8")
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(script, "tracked_files", lambda: [Path(name)])
return script.main()


def test_a_long_hand_written_file_fails(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
code = run_on(tmp_path, monkeypatch, "docs/guide.md", 301)
assert code == 1
assert "guide.md: 301 lines" in capsys.readouterr().out


def test_the_readme_may_be_longer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
assert run_on(tmp_path, monkeypatch, "README.md", 600) == 0


def test_the_readme_still_has_a_ceiling(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
assert run_on(tmp_path, monkeypatch, "README.md", 601) == 1
assert "README.md: 601 lines (limit 600)" in capsys.readouterr().out


def test_only_the_top_level_readme_is_exempt(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
code = run_on(tmp_path, monkeypatch, "docs/README.md", 301)
assert code == 1
15 changes: 15 additions & 0 deletions tests/unit/test_own_magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
connect,
)
from PythonMetaTrader5.application.trader import Trader
from PythonMetaTrader5.domain.errors import TradeError
from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest
from PythonMetaTrader5.result import Err, Ok

Expand Down Expand Up @@ -240,6 +241,20 @@ def test_a_default_close_that_matches_nothing_says_what_it_left_open(
assert terminal.sent == []


def test_a_failed_check_for_items_left_open_is_logged_not_dropped(
trader: Trader, terminal: FakeTerminal, caplog: pytest.LogCaptureFixture
) -> None:
# The own listing is empty, then the listing of every magic fails: Ok([])
# alone would read as "flat" with a merged netting position still open.
answers = iter([Ok([]), Err(TradeError(ErrorKind.TERMINAL_ERROR, "IPC timeout"))])
terminal.positions = lambda **_: next(answers) # type: ignore[method-assign]
with caplog.at_level(logging.WARNING, logger="PythonMetaTrader5"):
assert trader.close_positions("EURUSD") == Ok([])
(message,) = [r.getMessage() for r in caplog.records]
assert "could not check" in message
assert "IPC timeout" in message


def test_no_left_open_warning_when_own_items_were_handled(
trader: Trader, mixed_positions: FakeTerminal, caplog: pytest.LogCaptureFixture
) -> None:
Expand Down
Loading