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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ Complete rewrite. See [MIGRATION.md](MIGRATION.md) for every behaviour change.
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.
`close_positions()` / `cancel_pending_orders()` default to the trader's own
magic; `ANY_MAGIC` acts on the whole account; a `ticket` is closed whatever
its magic (ADR 0011). `Broker.Close` / `CancelOrders` keep acting on every
magic, as in 2.x. `connect(magic=...)` must be an integer from 0 to 2**64-1; a magic-0
trader logs a warning when a close/cancel affects magic-0 (manual) trades.
- 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.
Expand Down
4 changes: 2 additions & 2 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ logging.basicConfig(level=logging.INFO)
| `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")` |
| `Close("EURUSD")` | `trader.close_positions("EURUSD", magic=ANY_MAGIC)`; without `magic` only the trader's own positions close (ADR 0011) |
| `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)` |
| `CancelOrders(s)` | `trader.cancel_pending_orders(s, magic=ANY_MAGIC, kind=PendingKind.LIMIT)` |
| `GetPositions(as_dict=True)` | see below |
| `Disconnect()` | `trader.shutdown()` or `with trader:` |

Expand Down
23 changes: 17 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ with trader: # shuts the terminal connection down on exit
case Err(error):
print("not opened:", error.kind, error.message)

trader.close_positions("EURUSD", magic=1001) # only this bot's positions
trader.close_positions("EURUSD") # only this bot's (magic 1001) positions
```

## API
Expand All @@ -88,8 +88,8 @@ deviation=10, retry=None) -> Result[Trader, TradeError]`
|---|---|
| `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]` |
| `close_positions(symbol=None, *, ticket=None, magic=<own>, comment=None)` | `Result[list[TradeReceipt], BatchFailure]` |
| `cancel_pending_orders(symbol=None, *, magic=<own>, 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` |
Expand All @@ -116,9 +116,20 @@ deviation=10, retry=None) -> Result[Trader, TradeError]`
the BMP, such as most emoji, count as 2 (combined emoji more). The `MetaTrader5` package refuses 30 or more (measured on 5.0.6231; its
docs say 31). Longer comments, and comments that are not `str`, are rejected
before sending, 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.
- **`close_positions()` and `cancel_pending_orders()` act only on the trader's
own `magic`** unless you pass another one (ADR 0011); `magic=None` is still
"own". To act on the whole account, manual trades included, pass
`magic=ANY_MAGIC`. A `ticket` is closed whatever its magic. `positions()`
and `pending_orders()` still list every magic by default.
- Manual trades have magic 0, the `connect()` default, so set your own `magic`
for this to protect them. Until then a close/cancel that affects magic-0
items logs a warning; `magic=0` passed explicitly acknowledges it. On a
netting account a position keeps the magic of the deal that opened it, so
merged volume cannot be told apart by magic; a defaulted close/cancel that
matches nothing logs how many items with other magics it left open.
- A magic must be an integer from 0 to 2\*\*64-1 (MT5's ulong); `connect()`
returns `Err(INVALID_ARGUMENT)` otherwise, e.g. for `None`. An empty string
`""` as symbol is rejected too.
- `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
Expand Down
66 changes: 66 additions & 0 deletions docs/adr/0011-close-all-defaults-to-own-magic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# ADR 0011: Close-all and cancel-all default to the trader's own magic

- Status: accepted (3.0.0). Decided by the package owner on 2026-11-09.

## Context

`close_positions()` and `cancel_pending_orders()` without a `magic` acted on
the whole account, manual trades and other bots included. The README warned
about it in bold, but a bot that forgets `magic` once closes everything. MT5
gives trades opened by hand magic 0.

## Decision

- **Own by default.** Without `magic`, both calls act only on items whose
magic equals the trader's (`connect(..., magic=...)`). With a `symbol`
too: `close_positions("EURUSD")` closing someone's manual EURUSD trade is
the same hazard. This goes beyond the owner's question, which named only
the no-argument call.
- **The whole account is spelled `ANY_MAGIC`.** An explicit `magic=None` is
still "own". We chose a named value instead of `None` because a `None` read
from a missing config key would otherwise widen the call to the whole
account, the exact accident this change removes.
- **A `ticket` is closed whatever its magic.** The caller named the position.
Filtering it out would return `Ok([])` with the position still open. An
explicit `magic` still applies to a ticket.
- **Reads are unchanged.** `positions()` and `pending_orders()` still list
everything by default; they also accept `ANY_MAGIC`. A read cannot close
anything, and narrowing it would hide positions from a status screen.
- **A magic outside MT5's ulong is refused** as `INVALID_ARGUMENT` (`"42"`,
`True`, `1.5`, `-1`, `2**64`). `"42"` would match
nothing and report an empty success with every position still open.
- **The trader's own magic must be an integer from 0 to 2\*\*64-1** (MT5's
ulong). `connect()` returns `Err(INVALID_ARGUMENT)` and `Trader(...)` raises `ValueError` for
`None`, `ANY_MAGIC`, `"1001"` or `True`. Without this check,
`connect(magic=cfg.get("magic"))` with the key missing made "own" mean
"every magic" (found in review).
- **`Broker` keeps 2.x.** `Close(symbol)` and `CancelOrders(symbol)` closed
every magic in 2.x, so the facade passes `ANY_MAGIC`.

## Consequences

- A trader connected with the default `magic=0` shares that magic with manual
trades, so its close-all still closes them. The protection only works once
a bot sets its own `magic`. `connect()` keeps `magic=0` as its default
rather than making `magic` required; that is an API choice left to the
owner before release (`Broker` builds its `Trader` directly and is not
affected either way). A defaulted close/cancel on a magic-0 trader that
matches something logs a warning that manual trades are included; passing
`magic=0` explicitly acknowledges it.
- On a **netting** account one position per symbol collects every deal, and
it keeps the magic of the deal that opened it. A bot's deal that merges
into a manual position is then not "own", and a manual deal that merges
into the bot's position is. The magic filter cannot separate them; this is
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
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
`Trader`.
- `close_positions()` ported from 2.x `Close()` now leaves positions of other
magics open. MIGRATION.md maps `Close(s)` to
`close_positions(s, magic=ANY_MAGIC)` for an exact equivalent.
- The read/write asymmetry (`None` = all for reads, own for closes) is
deliberate. The parameter docstrings state it.
4 changes: 4 additions & 0 deletions src/PythonMetaTrader5/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
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.inputs import ANY_MAGIC as ANY_MAGIC
from PythonMetaTrader5.domain.inputs import AnyMagic as AnyMagic
from PythonMetaTrader5.domain.market import PendingKind as PendingKind
from PythonMetaTrader5.domain.market import PendingOrder as PendingOrder
from PythonMetaTrader5.domain.market import Position as Position
Expand All @@ -33,6 +35,8 @@
from PythonMetaTrader5.result import Result as Result

_OWN_NAMES = (
"ANY_MAGIC",
"AnyMagic",
"BatchFailure",
"Broker",
"Err",
Expand Down
7 changes: 5 additions & 2 deletions src/PythonMetaTrader5/application/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import Protocol, TypeVar

from PythonMetaTrader5.domain.errors import TradeError
from PythonMetaTrader5.domain.inputs import ANY_MAGIC, AnyMagic
from PythonMetaTrader5.domain.market import TradeReceipt
from PythonMetaTrader5.result import Err, Ok, Result

Expand Down Expand Up @@ -53,5 +54,7 @@ def run_batch(
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]
def with_magic(items: list[_T], magic: int | AnyMagic | None) -> list[_T]:
if magic is None or magic is ANY_MAGIC:
return items
return [item for item in items if item.magic == magic]
65 changes: 65 additions & 0 deletions src/PythonMetaTrader5/application/magic_scope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Which magic a close-all / cancel-all acts on when the caller gives none (ADR 0011).

Kept apart from Trader: the rule and the warnings it owes are one decision,
and they would otherwise push trader.py past the file-length limit.
"""

from __future__ import annotations

import logging
from collections.abc import Callable
from typing import TypeVar

from PythonMetaTrader5.domain.errors import TradeError
from PythonMetaTrader5.domain.inputs import ANY_MAGIC, AnyMagic, magic_filter
from PythonMetaTrader5.result import Ok, Result

log = logging.getLogger("PythonMetaTrader5")
_T = TypeVar("_T")


def resolve(
own: int, magic: int | AnyMagic | None, ticket: int | None
) -> Result[int | AnyMagic, TradeError]:
"""The magic to filter by: the caller's, else the trader's own."""
checked = magic_filter(magic)
if not isinstance(checked, Ok):
return checked
if checked.value is not None:
return Ok(checked.value)
# A named ticket is explicit intent: filtering it out by magic would
# report Ok([]) for a position the caller asked to close.
return Ok(ANY_MAGIC if ticket is not None else own)


def warn_about_default(
own: int,
magic: object,
ticket: int | None,
matched: list[_T],
everything: Callable[[], Result[list[_T], TradeError]],
) -> None:
"""Say what the own-magic default cannot know; quiet once a magic is given."""
if magic is not None or ticket is not None:
return
if matched:
if own == 0:
# magic 0 stays allowed (it is the connect() default), but then
# "own" includes every manual trade.
log.warning(
"trader magic is 0, which manual trades share: this close/cancel "
"includes them; set magic at connect(), or pass magic=0 to confirm"
)
return
# Matched nothing: on netting the bot's deal may have merged into a position
# 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:
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 "
"first magic); pass magic=ANY_MAGIC to include them",
own,
len(others.value),
)
75 changes: 62 additions & 13 deletions src/PythonMetaTrader5/application/trader.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,20 @@
from dataclasses import replace
from types import TracebackType

from PythonMetaTrader5.application import magic_scope
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.inputs import (
ANY_MAGIC,
AnyMagic,
magic_filter,
own_magic,
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
Expand All @@ -30,7 +38,11 @@ def __init__(
) -> None:
self._terminal = terminal
self._clock = clock
self._magic = magic
own = own_magic(magic)
if isinstance(own, Err):
# A constructor cannot return a Result; connect() reports this as Err.
raise ValueError(own.error.message)
self._magic = own.value
self._deviation = deviation
self._retry = retry or RetryPolicy()

Expand Down Expand Up @@ -115,20 +127,30 @@ def close_positions(
symbol: str | None = None,
*,
ticket: int | None = None,
magic: int | None = None,
magic: int | AnyMagic | 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.
Only the trader's own ``magic`` unless another ``magic`` is given;
``magic=ANY_MAGIC`` closes every position, manual ones included. A
``ticket`` is closed whatever its magic.
"""
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)
own = magic_scope.resolve(self._magic, magic, ticket)
if isinstance(own, Err):
return Err(BatchFailure((), (own.error,)))
listed = self.positions(
None if ticket is not None else symbol, ticket=ticket, magic=own.value
)
if isinstance(listed, Err):
return Err(BatchFailure((), (listed.error,)))
scope = None if ticket is not None else symbol
magic_scope.warn_about_default(
self._magic, magic, ticket, listed.value, lambda: self.positions(scope, magic=ANY_MAGIC)
)
# One spec lookup per symbol, not per position: close-all is time-critical.
specs: dict[str, Result[SymbolSpec, TradeError]] = {}

Expand All @@ -143,39 +165,66 @@ def cancel_pending_orders(
self,
symbol: str | None = None,
*,
magic: int | None = None,
magic: int | AnyMagic | None = None,
kind: PendingKind | None = None,
) -> Result[list[TradeReceipt], BatchFailure]:
listed = self.pending_orders(symbol, magic=magic, kind=kind)
"""Cancel matching pending orders of the trader's own ``magic`` by default.

``magic=ANY_MAGIC`` cancels every order on the account, manual ones included.
"""
own = magic_scope.resolve(self._magic, magic, None)
if isinstance(own, Err):
return Err(BatchFailure((), (own.error,)))
listed = self.pending_orders(symbol, magic=own.value, kind=kind)
if isinstance(listed, Err):
return Err(BatchFailure((), (listed.error,)))
magic_scope.warn_about_default(
self._magic,
magic,
None,
listed.value,
lambda: self.pending_orders(symbol, magic=ANY_MAGIC, kind=kind),
)
return run_batch(listed.value, self._cancel_one)

# ----------------------------------------------------------------- queries

def positions(
self, symbol: str | None = None, *, ticket: int | None = None, magic: int | None = None
self,
symbol: str | None = None,
*,
ticket: int | None = None,
magic: int | AnyMagic | None = None,
) -> Result[list[Position], TradeError]:
"""Every position by default: a read never needs the own-magic guard."""
checked = magic_filter(magic)
if isinstance(checked, Err):
return checked
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))
if isinstance(listed, Err):
return listed
return Ok(with_magic(listed.value, checked.value))

def pending_orders(
self,
symbol: str | None = None,
*,
magic: int | None = None,
magic: int | AnyMagic | None = None,
kind: PendingKind | None = None,
) -> Result[list[PendingOrder], TradeError]:
checked = symbol_filter(symbol)
checked = magic_filter(magic)
if isinstance(checked, Err):
return checked
symbol_checked = symbol_filter(symbol)
if isinstance(symbol_checked, Err):
return symbol_checked
listed = self._terminal.pending_orders(symbol=symbol)
if isinstance(listed, Err):
return listed
orders = with_magic(listed.value, magic)
orders = with_magic(listed.value, checked.value)
return Ok(orders if kind is None else [o for o in orders if o.kind is kind])

def shutdown(self) -> None:
Expand Down
Loading
Loading