pmt5api 1.1.2__tar.gz → 1.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. pmt5api-1.3.0/CHANGELOG.md +158 -0
  2. {pmt5api-1.1.2 → pmt5api-1.3.0}/LICENSE.txt +0 -0
  3. {pmt5api-1.1.2 → pmt5api-1.3.0}/PKG-INFO +33 -6
  4. {pmt5api-1.1.2 → pmt5api-1.3.0}/README.md +31 -4
  5. {pmt5api-1.1.2 → pmt5api-1.3.0}/examples/bars.py +0 -0
  6. {pmt5api-1.1.2 → pmt5api-1.3.0}/examples/connect.py +0 -0
  7. {pmt5api-1.1.2 → pmt5api-1.3.0}/examples/pnl.py +6 -4
  8. pmt5api-1.3.0/examples/rotate_view_password.py +20 -0
  9. {pmt5api-1.1.2 → pmt5api-1.3.0}/examples/servers.py +0 -0
  10. {pmt5api-1.1.2 → pmt5api-1.3.0}/examples/sizing.py +3 -3
  11. {pmt5api-1.1.2 → pmt5api-1.3.0}/examples/stream_async.py +0 -0
  12. {pmt5api-1.1.2 → pmt5api-1.3.0}/examples/stream_quotes.py +0 -0
  13. {pmt5api-1.1.2 → pmt5api-1.3.0}/examples/trade_demo.py +0 -0
  14. {pmt5api-1.1.2 → pmt5api-1.3.0}/hatch_build.py +0 -0
  15. {pmt5api-1.1.2 → pmt5api-1.3.0}/pyproject.toml +1 -1
  16. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/__init__.py +3 -3
  17. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/__main__.py +0 -0
  18. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_account.py +77 -30
  19. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_base.py +0 -0
  20. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_coverage.py +17 -1
  21. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_events.py +0 -0
  22. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_market.py +0 -0
  23. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_risk.py +4 -2
  24. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_runtime.py +70 -8
  25. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_session.py +78 -0
  26. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_streams.py +5 -4
  27. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_trading.py +0 -0
  28. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/_util.py +0 -0
  29. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/bars.py +0 -0
  30. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/client.py +9 -2
  31. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/diagnostics.py +8 -0
  32. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/docs/API.md +101 -14
  33. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/docs/FROM-CSHARP.md +14 -1
  34. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/errors.py +13 -0
  35. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/frames.py +0 -0
  36. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/models.py +30 -1
  37. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/py.typed +0 -0
  38. {pmt5api-1.1.2 → pmt5api-1.3.0}/src/pmt5api/servers.py +0 -0
  39. pmt5api-1.1.2/CHANGELOG.md +0 -79
@@ -0,0 +1,158 @@
1
+ # Changelog — pmt5api
2
+
3
+ ## [1.3.0] — 2026-11-29
4
+
5
+ Bundles **wmt5api 4.2.0** (up from 3.2.1): modern broker builds, the trader-grade `Order` fields, and account
6
+ password management. All additive over 1.2.0.
7
+
8
+ ### Added
9
+ - **`change_view_password(new_view_password)`** — change the read-only investor ("view") password (live read-only
10
+ visibility without trade rights). **`roll_view_password(length=12)`** — rotate it to a freshly generated strong
11
+ password and return the new value (schedule this yourself; persist the returned value before relying on it).
12
+ **`change_password_timeout`** — how long to wait for the server's acknowledgement (ms).
13
+ - **`Order.net_profit`**, **`Order.open_time_utc` / `Order.close_time_utc`** (UTC-kinded),
14
+ **`Order.open_timestamp_utc` / `Order.close_timestamp_utc`** (Unix seconds), and
15
+ **`Order.is_buy` / `is_sell` / `is_pending` / `is_ledger_entry`**.
16
+ - **`get_position_deals(position_ticket, opened_after=None, timeout_ms=0)`** — every deal that makes up a position.
17
+ - **`reconcile()`** → **`ReconcileSnapshot`** (orders, sequence, session, server_time): a consistent snapshot of the
18
+ open positions and pending orders for an event-driven client.
19
+ - **`announce_build`**, **`auto_upgrade_on_old_version`**, **`connect_retries`**, **`connect_retry_base_delay`**
20
+ (connect tuning) and read-only **`last_handshake_build`**, **`server_new_form`** (handshake diagnostics).
21
+ - Status **Production/Stable** (classifier `5 - Production/Stable`).
22
+
23
+ ### Changed
24
+ - **`change_password` now works on modern broker builds and confirms the result** — it waits for the server's
25
+ acknowledgement and raises on a broker-side rejection (e.g. `INVALID_PASSWORD`, `NOT_PERMISSION`) instead of
26
+ failing silently. Call it on a session authenticated with the main password.
27
+
28
+ ## [1.2.0] — 2026-11-06
29
+
30
+ Bundles **wmt5api 3.2.1**. A minor release with a **Breaking** section, like the core's: history is always asked for
31
+ by a window you choose.
32
+
33
+ ### Breaking — history is always asked for by window
34
+ - **`history(start, end)` and `summary(start, end)` need both ends.** `history()` no longer defaults to the last 30
35
+ days and `summary()` no longer means "all time" (the core read every deal since 1970 for it, on every call). A
36
+ missing or reversed window raises `InvalidRequestError` before anything is sent; `request_history(start, end)`
37
+ likewise.
38
+ - **One call covers at most `max_history_days` (366 by default).** A longer window raises `InvalidRequestError`
39
+ before anything is sent. Ask window by window and add the results up, or set `Client(max_history_days=...)` /
40
+ `c.max_history_days` when you mean one long download (`0` removes the limit; the ends stay required).
41
+ `equity_history(start)` and `calibrate_money_scale(start)` run to now, so their start is at most that long ago (an
42
+ older one makes `calibrate_money_scale` return `False`, the reason in `money_scale_evidence`).
43
+ - What to change: `c.summary()` → `c.summary(start, end)`; `c.history()` → `c.history(start, end)` (for "up to now",
44
+ `end = c.server_time`); a calibration over two years → over at most one.
45
+
46
+ ### Added
47
+ - `Client.max_history_days` (read and write) and the constructor argument of the same name.
48
+ - `Client.server_name`: the name of the trade server the session logged in to (for example `ICMarketsSC-Demo`).
49
+
50
+ ### Changed (core wmt5api 3.2.0 / 3.2.1)
51
+ - `history()` asks the server for your window only (the server answers in whole calendar months; before, three more
52
+ months were asked for on every call). A position closed in the window but held longer than three months before it
53
+ is now listed in `orders` (up to a year back); a position whose deals arrived in different pages is no longer
54
+ dropped.
55
+ - Two `history()` calls at once on one client run one after the other instead of failing with `BusyError`.
56
+
57
+ ### Fixed (this package)
58
+ - **The platform wheel could not start on a machine that also has a newer .NET installed on `PATH`** (for example a
59
+ system .NET 10 next to the bundled .NET 9): the loader under pythonnet asked that `dotnet` for its runtimes, took
60
+ the newest and looked for it in the bundled runtime — `RuntimeNotFoundError` ("needs the .NET 8 (or later)
61
+ runtime"), on 1.1.2 too. The runtime is now started at a version the chosen runtime folder holds, and the message
62
+ says which runtime it tried.
63
+
64
+ ### Fixed (core wmt5api 3.2.0 / 3.2.1)
65
+ - **Events could reach callbacks out of order** — an order's close before its open, an older price after a newer one,
66
+ a disconnect before the connect. Quotes, order updates, order progress, connect progress and history chunks now
67
+ arrive in the order the client received them; a throwing handler no longer drops the rest of a batch.
68
+ - **A market order or close with the default fill policy could use a filling mode the symbol does not accept**, and
69
+ the broker refused it (`UNSUPPORTED_FILLING_MODE`): the symbol's declared modes are a bit mask and were read as one
70
+ value. The default now picks a declared mode (fill-or-kill if declared, else immediate-or-cancel, else return on an
71
+ exchange).
72
+ - `Order.fill_policy` of a market order filled immediate-or-cancel read fill-or-kill; it reports the mode the server
73
+ confirmed.
74
+ - `equity_history()`: the documentation no longer says "empty" for a window with no deal (it is a flat line).
75
+
76
+ ### Security (core wmt5api 3.2.0)
77
+ - `token_url` must be `https` (plain `http` only for a loopback host) and carry no user information, query or
78
+ fragment; redirects from the licence service are not followed (they would re-send the key).
79
+ - A login already bound to another trading account under your licence is refused with `LicenseError` reason
80
+ `AccountLimitReached` and a message that says so.
81
+
82
+ ## [1.1.2] — 2026-10-15
83
+
84
+ From the delta re-test of 1.1.1 (no S1 or S2). Python layer only: the cores are unchanged.
85
+
86
+ ### Fixed
87
+ - A `bars()` timeout says the budget of the call (`not complete within 0.5 s`), not what was left for the last block.
88
+ - `Order` and `Deal` money fields (profit, swap, commission, fee) carry no binary noise (`1.3900000000000001` is `1.39`).
89
+ - README: a connect to an unreachable licence service waits about twice `token_timeout`.
90
+
91
+ ## [1.1.1] — 2026-10-14
92
+
93
+ From the Windows re-test of 1.1.0 (13 notes, one S2). Bundles wmt5api 3.1.2.
94
+
95
+ ### Fixed
96
+ - **`equity_history()` returned `[]` for a window with no deal** (an idle account): the balance curve is now a flat line
97
+ at the current balance (core `wmt5api 3.1.2`). A script that read `eq[-1]` on an idle account raised `IndexError`.
98
+ - Account money figures carry no binary noise (`1635341.7899999998` is `1635341.79`).
99
+ - A bars timeout states a sub-second wait as it is (`0.5 s`, not `0 s`).
100
+ - A missing .NET runtime on a **32-bit** Python says that 32-bit Python needs the 32-bit runtime.
101
+ - `SymbolInfo` has a meaning for every field in the reference.
102
+ - README: ticks and their `time`, that the server enforces volume min/step, the minute rounding of an expiry, Ctrl+C
103
+ during `connect()`, the licence request retry.
104
+
105
+ ## [1.1.0] — 2026-10-13
106
+
107
+ Found by a customer-style test on Windows Server 2022 / Python 3.10 (28 findings); every one is addressed. Bundles
108
+ wmt5api 3.1.1. Additive: nothing that worked in 1.0.0 is removed.
109
+
110
+ ### Fixed
111
+ - **Two packages could not start the .NET runtime from two threads at once** (`RuntimeNotFoundError` in one of them,
112
+ every time, on Linux as well). One lock now covers every `pmt*api` package in the process.
113
+ - **`bars()` re-aggregated the whole series after every block** (MT5): a deep request was quadratic and timed out
114
+ (`D1` × 1000 took over two minutes of CPU). It counts as the blocks arrive and aggregates once; the default budget
115
+ is `bars_timeout` plus a second per two weeks of one-minute bars the request needs.
116
+ - **A closed client left a thread behind** for every client that had used callbacks or `quotes()`: the callback
117
+ thread now ends at `disconnect()` (and when the client is dropped) and returns with the next event.
118
+ - **Type checkers saw every method as `(*Any, **Any) -> Any`**: the decorator that translates errors now keeps the
119
+ signature.
120
+ - Messages: a missing .NET runtime names the runtime and where to get it; the no-key text speaks `api_key=`; a bars
121
+ timeout states its real wait; a trade refusal names its code.
122
+ - `python -m pmt4api --connect` / `pmt5api --connect` accept `host:port` in `PMT*_HOST`.
123
+ - The reference gains a meaning for every field of the main data types.
124
+ - `close()`, `modify()` and `cancel()` return the order they acted on, the same on both packages (`pmt5api`: `close()` returned an empty record and `modify()` `None`; `pmt4api`: `cancel()` returned `None`).
125
+ - The core fixes: see wmt5api 3.1.1 — **`Deal.price` / `Deal.open_price` were swapped on a closing deal**, a pending sell order reported `DealBuy`, and `history()` omitted cancelled and expired pending orders.
126
+
127
+ ### Added
128
+ - `lots_for_risk(..., side="buy" | "sell")`: a stop on the wrong side of the entry is refused instead of being sized by its distance.
129
+ - `LoginRejectedError` (a `ServerError`): the broker refused the login — `connect()` raises it for a wrong account or password instead of a bare `ServerError`; a dial that times out is a `ConnectError`, as on MT4.
130
+
131
+ ## [1.0.0] — 2026-10-12
132
+
133
+ First release. `pmt5api` exposes every public capability of the wmt5api 3.x C# library to Python.
134
+
135
+ ### Capabilities
136
+ - Connection and session: licensing, failover, `auto_reconnect`, proxies (SOCKS4/SOCKS5/HTTPS), client certificate,
137
+ all timeouts, connect-progress events, server time and account mode.
138
+ - Market data: symbols with trading rules and sessions, commissions, quotes and subscriptions (callbacks, iterators,
139
+ asyncio), bars M1–D1 with tick volume, tick value and contract size.
140
+ - Account: balances and margins (with and without swap/commission), orders, positions, closed orders, history and
141
+ deal history (blocking and event-driven), realized summary, balance/equity curve.
142
+ - Sizing and risk: money-scale calibration, lots-for-risk with evidence, required margin, order profit.
143
+ - Order entry: market, pending (limit, stop, stop-limit), expiration, fill policy, modify, partial close, close-by,
144
+ cancel — synchronous, with request ids and progress events, and awaitable; magic number on orders and deals.
145
+ - Offline helpers and administration: `servers.dat` read and write, demo account request, password change.
146
+ - Diagnostics: the core's log into Python `logging`.
147
+ - Parity manifest `pmt5api.COVERAGE`, checked against the DLL by the test suite; generated API reference and a
148
+ C#-to-Python table.
149
+
150
+ ### Packaging
151
+ - Linux x86-64 wheel carrying the core and the .NET 9 runtime (`manylinux_2_28`); a pure wheel carrying the core;
152
+ an sdist.
153
+
154
+ ### Verified
155
+ Against real demo accounts, from clean containers without .NET (Python 3.9, 3.12, 3.13; glibc 2.28 and 2.41):
156
+ read-only and trading suites, reconnects (drops, a refused window, a silent link), every shipped example, and a
157
+ three-hour unattended run (4 recovered drops, no errors, memory flat after warm-up).
158
+ Not verified: Windows, macOS, arm64, musl; netting accounts; client certificates.
File without changes
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pmt5api
3
- Version: 1.1.2
3
+ Version: 1.3.0
4
4
  Summary: Complete Python interface to the wmt5api MetaTrader 5 client library (market data, account, sizing, order entry, events).
5
5
  Project-URL: Homepage, https://mtapi.one
6
6
  Author: Sen Trading
7
7
  License-File: LICENSE.txt
8
8
  Keywords: market-data,metatrader,mt5,trading,wmt5api
9
- Classifier: Development Status :: 4 - Beta
9
+ Classifier: Development Status :: 5 - Production/Stable
10
10
  Classifier: Intended Audience :: Developers
11
11
  Classifier: Intended Audience :: Financial and Insurance Industry
12
12
  Classifier: License :: Other/Proprietary License
@@ -202,9 +202,9 @@ Do not size a trade from a one-line formula: what a price unit is worth depends
202
202
  from your own closed deals and refuses to size without that evidence:
203
203
 
204
204
  ```python
205
- from datetime import datetime
205
+ from datetime import timedelta
206
206
 
207
- if c.calibrate_money_scale(datetime(2025, 1, 1)): # read-only; places no order
207
+ if c.calibrate_money_scale(c.server_time - timedelta(days=365)): # read-only; places no order; at most a year back
208
208
  r = c.lots_for_risk("EURUSD", entry_price=1.1000, stop_price=1.0950, risk_amount=50.0, side="buy")
209
209
  for w in r.warnings:
210
210
  print("warning:", w) # read these: ok can still be True with a caveat
@@ -228,12 +228,29 @@ to be checked. Also: `required_margin(symbol, lots)`, `order_profit(symbol, open
228
228
  | `account(refresh=True)` | `AccountInfo` — balance, equity, floating P/L (with and without swap/commission), margin, free margin, margin level, leverage, account mode, contact details |
229
229
  | `orders()` / `positions()` / `closed_orders()` | `list[Order]` — working / open positions only / what this session saw close |
230
230
  | `history(start, end)` / `deal_history(year, month)` | `History` — `.orders` and `.deals` (the ledger, including deposits and withdrawals) |
231
- | `summary(start=None, end=None)` | `AccountSummary` — realized profit, deposits, withdrawals, from the deal ledger |
231
+ | `summary(start, end)` | `AccountSummary` — realized profit, deposits, withdrawals, from the deal ledger |
232
232
  | `equity_history(start, "D1")` | `list[EquityPoint]` — balance (exact) and equity (reconstructed) curve with drawdowns |
233
233
  | `request_history(...)`, `request_bars(...)` | without waiting; the data arrives through `on_history` / `on_quote_history` |
234
234
 
235
235
  Times are naive `datetime` values in the **broker's server time**, as the server reports them; an unset time is `None`.
236
236
 
237
+ **History is asked for by window.** `history()` and `summary()` take a start and an end, and one call covers at most
238
+ `max_history_days` (366 by default; set it on the client, `0` removes the limit); `equity_history()` and
239
+ `calibrate_money_scale()` run from their start to now, so the start is at most that long ago. A missing, reversed or longer window raises
240
+ `InvalidRequestError` before anything is sent. For a longer period, ask window by window and add the results up:
241
+
242
+ ```python
243
+ from datetime import timedelta
244
+
245
+ end = c.server_time # server time; "up to now"
246
+ h = c.history(end - timedelta(days=30), end) # .orders and .deals
247
+ year = c.summary(end - timedelta(days=365), end)
248
+ ```
249
+
250
+ The server answers history in whole calendar months; `history()` keeps your window, and lists a position closed in it
251
+ whose opening deal is earlier (up to a year before the window). A window with no deal in it gives a flat equity curve
252
+ at the balance, never an empty one.
253
+
237
254
  `account()` first quotes each open position's symbol once and recalculates profits, so equity, profit and margin
238
255
  level are current (a cold read would otherwise show equity equal to balance). Pass `refresh=False` to skip that.
239
256
 
@@ -241,7 +258,9 @@ level are current (a cold read would otherwise show equity equal to balance). Pa
241
258
 
242
259
  `on_quote`, `on_order_update`, `on_order_progress`, `on_connect_progress`, `on_history`, `on_quote_history`,
243
260
  `on_symbols_update`, `on_symbol_update` — each returns a function that removes the callback. `quotes()` and
244
- `order_updates()` (and the `a…` async versions) turn a stream into an iterator.
261
+ `order_updates()` (and the `a…` async versions) turn a stream into an iterator. Events reach you in the order the
262
+ client received them — an order's open before its close, ticks in time order — and callbacks run one at a time on the
263
+ client's own thread.
245
264
 
246
265
  ## Staying connected
247
266
 
@@ -262,12 +281,20 @@ subscriptions are restored, cached snapshots are not.
262
281
  | Reconnect | `auto_reconnect`, `reconnect_backoff` (3, doubling up to `reconnect_max_backoff`, 30), `reconnect_max_attempts` (0 = no limit) | — |
263
282
  | Proxy | `proxy=Proxy("socks5" \| "socks4" \| "https", host, port, user, password)` — `host` must be an IP address | — |
264
283
  | Client certificate / common key | `certificate=`, `certificate_password=`, `common_key=` | — |
284
+ | History window | `max_history_days=` (366; `0` = no limit) — also a client attribute | — |
265
285
  | .NET runtime location | — | `DOTNET_ROOT` |
266
286
 
267
287
  A core path you give (argument or `WMTAPI_DLL`) is used exactly as given and is an error if it does not exist. The
268
288
  .NET runtime is taken from `DOTNET_ROOT` if you set it, else the runtime bundled in the wheel, else an installed one.
269
289
  The bundled runtime runs in invariant-culture mode on machines without ICU.
270
290
 
291
+ **These two settings decide what code runs in your process.** `WMTAPI_DLL` (or `dll_path=`) names the library that is
292
+ loaded, and `DOTNET_ROOT` (or, without it, the `dotnet` found on `PATH`) names the .NET runtime that is started;
293
+ both run with your rights. Set them only from configuration you control, and do not run with an environment
294
+ someone else can change. With `enable_core_logging()` switched on, the package logs once when either was chosen
295
+ by the environment. The licence service URL must be `https` (plain `http` only for a loopback test service), and
296
+ redirects from it are not followed.
297
+
271
298
  ### Diagnostics
272
299
 
273
300
  ```python
@@ -175,9 +175,9 @@ Do not size a trade from a one-line formula: what a price unit is worth depends
175
175
  from your own closed deals and refuses to size without that evidence:
176
176
 
177
177
  ```python
178
- from datetime import datetime
178
+ from datetime import timedelta
179
179
 
180
- if c.calibrate_money_scale(datetime(2025, 1, 1)): # read-only; places no order
180
+ if c.calibrate_money_scale(c.server_time - timedelta(days=365)): # read-only; places no order; at most a year back
181
181
  r = c.lots_for_risk("EURUSD", entry_price=1.1000, stop_price=1.0950, risk_amount=50.0, side="buy")
182
182
  for w in r.warnings:
183
183
  print("warning:", w) # read these: ok can still be True with a caveat
@@ -201,12 +201,29 @@ to be checked. Also: `required_margin(symbol, lots)`, `order_profit(symbol, open
201
201
  | `account(refresh=True)` | `AccountInfo` — balance, equity, floating P/L (with and without swap/commission), margin, free margin, margin level, leverage, account mode, contact details |
202
202
  | `orders()` / `positions()` / `closed_orders()` | `list[Order]` — working / open positions only / what this session saw close |
203
203
  | `history(start, end)` / `deal_history(year, month)` | `History` — `.orders` and `.deals` (the ledger, including deposits and withdrawals) |
204
- | `summary(start=None, end=None)` | `AccountSummary` — realized profit, deposits, withdrawals, from the deal ledger |
204
+ | `summary(start, end)` | `AccountSummary` — realized profit, deposits, withdrawals, from the deal ledger |
205
205
  | `equity_history(start, "D1")` | `list[EquityPoint]` — balance (exact) and equity (reconstructed) curve with drawdowns |
206
206
  | `request_history(...)`, `request_bars(...)` | without waiting; the data arrives through `on_history` / `on_quote_history` |
207
207
 
208
208
  Times are naive `datetime` values in the **broker's server time**, as the server reports them; an unset time is `None`.
209
209
 
210
+ **History is asked for by window.** `history()` and `summary()` take a start and an end, and one call covers at most
211
+ `max_history_days` (366 by default; set it on the client, `0` removes the limit); `equity_history()` and
212
+ `calibrate_money_scale()` run from their start to now, so the start is at most that long ago. A missing, reversed or longer window raises
213
+ `InvalidRequestError` before anything is sent. For a longer period, ask window by window and add the results up:
214
+
215
+ ```python
216
+ from datetime import timedelta
217
+
218
+ end = c.server_time # server time; "up to now"
219
+ h = c.history(end - timedelta(days=30), end) # .orders and .deals
220
+ year = c.summary(end - timedelta(days=365), end)
221
+ ```
222
+
223
+ The server answers history in whole calendar months; `history()` keeps your window, and lists a position closed in it
224
+ whose opening deal is earlier (up to a year before the window). A window with no deal in it gives a flat equity curve
225
+ at the balance, never an empty one.
226
+
210
227
  `account()` first quotes each open position's symbol once and recalculates profits, so equity, profit and margin
211
228
  level are current (a cold read would otherwise show equity equal to balance). Pass `refresh=False` to skip that.
212
229
 
@@ -214,7 +231,9 @@ level are current (a cold read would otherwise show equity equal to balance). Pa
214
231
 
215
232
  `on_quote`, `on_order_update`, `on_order_progress`, `on_connect_progress`, `on_history`, `on_quote_history`,
216
233
  `on_symbols_update`, `on_symbol_update` — each returns a function that removes the callback. `quotes()` and
217
- `order_updates()` (and the `a…` async versions) turn a stream into an iterator.
234
+ `order_updates()` (and the `a…` async versions) turn a stream into an iterator. Events reach you in the order the
235
+ client received them — an order's open before its close, ticks in time order — and callbacks run one at a time on the
236
+ client's own thread.
218
237
 
219
238
  ## Staying connected
220
239
 
@@ -235,12 +254,20 @@ subscriptions are restored, cached snapshots are not.
235
254
  | Reconnect | `auto_reconnect`, `reconnect_backoff` (3, doubling up to `reconnect_max_backoff`, 30), `reconnect_max_attempts` (0 = no limit) | — |
236
255
  | Proxy | `proxy=Proxy("socks5" \| "socks4" \| "https", host, port, user, password)` — `host` must be an IP address | — |
237
256
  | Client certificate / common key | `certificate=`, `certificate_password=`, `common_key=` | — |
257
+ | History window | `max_history_days=` (366; `0` = no limit) — also a client attribute | — |
238
258
  | .NET runtime location | — | `DOTNET_ROOT` |
239
259
 
240
260
  A core path you give (argument or `WMTAPI_DLL`) is used exactly as given and is an error if it does not exist. The
241
261
  .NET runtime is taken from `DOTNET_ROOT` if you set it, else the runtime bundled in the wheel, else an installed one.
242
262
  The bundled runtime runs in invariant-culture mode on machines without ICU.
243
263
 
264
+ **These two settings decide what code runs in your process.** `WMTAPI_DLL` (or `dll_path=`) names the library that is
265
+ loaded, and `DOTNET_ROOT` (or, without it, the `dotnet` found on `PATH`) names the .NET runtime that is started;
266
+ both run with your rights. Set them only from configuration you control, and do not run with an environment
267
+ someone else can change. With `enable_core_logging()` switched on, the package logs once when either was chosen
268
+ by the environment. The licence service URL must be `https` (plain `http` only for a loopback test service), and
269
+ redirects from it are not followed.
270
+
244
271
  ### Diagnostics
245
272
 
246
273
  ```python
File without changes
File without changes
@@ -3,7 +3,7 @@
3
3
  PMT5_LOGIN=... PMT5_PASSWORD=... PMT5_HOST=... python pnl.py
4
4
  """
5
5
  import os
6
- from datetime import datetime, timedelta
6
+ from datetime import timedelta
7
7
 
8
8
  from pmt5api import Client
9
9
 
@@ -13,10 +13,12 @@ with Client(int(os.environ["PMT5_LOGIN"]), os.environ["PMT5_PASSWORD"], os.envir
13
13
  print("balance %.2f equity %.2f floating %.2f (swap %.2f, commission %.2f)"
14
14
  % (a.balance, a.equity, a.floating_pl, a.swap, a.commission))
15
15
 
16
- s = c.summary() # from the deal ledger; blocks while it downloads
17
- print("realized %.2f deposits %.2f withdrawals %.2f" % (s.realized_profit, s.deposit, s.withdrawal))
16
+ now = c.server_time # history windows are in the broker's server time
17
+ s = c.summary(now - timedelta(days=365), now) # the last year (at most max_history_days per call); blocks
18
+ print("last 365 days: realized %.2f deposits %.2f withdrawals %.2f"
19
+ % (s.realized_profit, s.deposit, s.withdrawal))
18
20
 
19
- curve = c.equity_history(datetime.now() - timedelta(days=30), "D1")
21
+ curve = c.equity_history(now - timedelta(days=30), "D1")
20
22
  for p in curve[-5:]:
21
23
  flag = " (incomplete)" if p.incomplete else ""
22
24
  print("%s balance %.2f equity %.2f drawdown %.2f%%%s"
@@ -0,0 +1,20 @@
1
+ """Rotate the read-only investor ("view") password — share live, read-only account access without trade rights.
2
+
3
+ Set WMTAPI_DLL and WMTAPI_KEY, then (on a session authenticated with the MAIN password):
4
+ PMT5_LOGIN=12345678 PMT5_PASSWORD=<main> PMT5_HOST=broker-access-host python rotate_view_password.py
5
+
6
+ Schedule this on your OWN timer/cron; PERSIST the returned value before you rely on it, or the investor login is lost.
7
+ """
8
+ import os
9
+
10
+ from pmt5api import Client, WmtError
11
+
12
+ with Client(int(os.environ["PMT5_LOGIN"]), os.environ["PMT5_PASSWORD"], os.environ["PMT5_HOST"],
13
+ int(os.environ.get("PMT5_PORT", "443"))) as c:
14
+ try:
15
+ new_view = c.roll_view_password() # generate + set a fresh strong password; waits for the server ack
16
+ # store_investor_password(new_view) # <- persist it FIRST (your secret store / DB)
17
+ print("investor/view password rolled to:", new_view)
18
+ except WmtError as e: # a broker-side rejection surfaces here, not silently
19
+ print("view-password change was rejected:", e)
20
+ # ...or set a specific value: c.change_view_password("View!Pass_2026")
File without changes
@@ -4,7 +4,7 @@
4
4
  """
5
5
  import os
6
6
  import sys
7
- from datetime import datetime, timedelta
7
+ from datetime import timedelta
8
8
 
9
9
  from pmt5api import Client
10
10
 
@@ -19,8 +19,8 @@ with Client(int(os.environ["PMT5_LOGIN"]), os.environ["PMT5_PASSWORD"], os.envir
19
19
  acct = c.account()
20
20
  print("account currency %s, equity %.2f" % (acct.currency, acct.equity))
21
21
 
22
- # 1. measure the account's own conventions from its closed deals (read-only; places no order)
23
- if not c.calibrate_money_scale(datetime.now() - timedelta(days=730)):
22
+ # 1. measure the account's own conventions from its closed deals of the last year (read-only; places no order)
23
+ if not c.calibrate_money_scale(c.server_time - timedelta(days=365)):
24
24
  sys.exit("cannot size yet: " + c.money_scale_evidence)
25
25
  print("money scale %s" % c.money_scale)
26
26
 
File without changes
File without changes
@@ -11,7 +11,7 @@ requires-python = ">=3.9"
11
11
  authors = [{ name = "Sen Trading" }]
12
12
  keywords = ["metatrader", "mt5", "trading", "market-data", "wmt5api"]
13
13
  classifiers = [
14
- "Development Status :: 4 - Beta",
14
+ "Development Status :: 5 - Production/Stable",
15
15
  "Intended Audience :: Developers",
16
16
  "Intended Audience :: Financial and Insurance Industry",
17
17
  "License :: Other/Proprietary License",
@@ -14,16 +14,16 @@ from .errors import (BusyError, ConnectError, NoQuoteError, ConnectionLostError,
14
14
  from .frames import to_frame
15
15
  from .models import (AccountInfo, AccountSummary, BaseInfo, CommissionInfo, CommissionTier, ConnectEvent, Deal,
16
16
  DemoAccount, DemoAccountRequest, EquityPoint, History, LotSizing, Order, OrderProgress,
17
- OrderUpdate, Quote, ServerRecord, SymbolInfo, SymbolSessions, TradingSession)
17
+ OrderUpdate, Quote, ReconcileSnapshot, ServerRecord, SymbolInfo, SymbolSessions, TradingSession)
18
18
  from .servers import load_servers_dat, request_demo_account, save_servers_dat, tick_value_from_deal
19
19
 
20
- __version__ = "1.1.2"
20
+ __version__ = "1.3.0"
21
21
 
22
22
  __all__ = [
23
23
  "Client", "Proxy",
24
24
  "Quote", "SymbolInfo", "SymbolSessions", "TradingSession", "CommissionInfo", "CommissionTier", "BaseInfo",
25
25
  "AccountInfo", "AccountSummary", "EquityPoint", "LotSizing", "Order", "Deal", "History",
26
- "OrderUpdate", "OrderProgress", "ConnectEvent", "QuoteHistoryEvent",
26
+ "OrderUpdate", "OrderProgress", "ConnectEvent", "QuoteHistoryEvent", "ReconcileSnapshot",
27
27
  "ServerRecord", "DemoAccountRequest", "DemoAccount",
28
28
  "Bar", "TIMEFRAMES", "aggregate", "to_frame",
29
29
  "load_servers_dat", "save_servers_dat", "request_demo_account", "tick_value_from_deal", "enable_core_logging",
File without changes
@@ -1,13 +1,20 @@
1
1
  """The account: balances, positions, orders, history, and the curves derived from them."""
2
2
  from __future__ import annotations
3
3
 
4
- from datetime import datetime, timedelta, timezone
5
- from typing import List, Optional
4
+ from datetime import datetime
5
+ from typing import Any, List, Optional
6
6
 
7
7
  from ._base import _Base
8
8
  from ._util import enum_value, to_core_time, translated
9
- from .errors import NotConnectedError
10
- from .models import AccountInfo, AccountSummary, EquityPoint, History, Order
9
+ from .errors import InvalidRequestError, NotConnectedError
10
+ from .models import AccountInfo, AccountSummary, Deal, EquityPoint, History, Order, ReconcileSnapshot
11
+
12
+
13
+ def _history_days(days: Any) -> int:
14
+ """A ``max_history_days`` value: a whole number of days, 0 for no limit."""
15
+ if isinstance(days, bool) or not isinstance(days, int) or days < 0:
16
+ raise ValueError("max_history_days must be a whole number of days, or 0 for no limit (got %r)" % (days,))
17
+ return days
11
18
 
12
19
 
13
20
  def _money(value) -> float:
@@ -82,22 +89,20 @@ class _AccountMixin(_Base):
82
89
  # ---- history -----------------------------------------------------------------------------------------------
83
90
 
84
91
  @translated
85
- def history(self, start: Optional[datetime] = None, end: Optional[datetime] = None,
86
- timeout: Optional[float] = None) -> History:
87
- """Orders and deals between ``start`` and ``end`` (default: the last 30 days up to now). Blocks until the
88
- server has sent everything, up to ``timeout`` seconds (default: the client's ``history_timeout``).
92
+ def history(self, start: datetime, end: datetime, timeout: Optional[float] = None) -> History:
93
+ """Orders and deals between ``start`` and ``end``. Blocks until the server has sent everything, up to
94
+ ``timeout`` seconds (default: the client's ``history_timeout``).
95
+
96
+ Both ends are required and the window may be at most :attr:`max_history_days` long (366 by default): a missing,
97
+ reversed or longer window raises :class:`InvalidRequestError` before anything is sent. For a longer period,
98
+ call once per window and add the results up. For "up to now", pass ``c.server_time`` as ``end``. ``orders``
99
+ also lists a position closed in the window whose opening deal is earlier (up to a year before the window).
89
100
 
90
101
  Naive datetimes are used exactly as given, in the broker's server time; timezone-aware ones are converted to
91
- it. The default window is computed on the server's clock.
102
+ it. Two calls at once on one client run one after the other (the wait counts toward the second one's timeout).
92
103
  """
93
104
  self._require_connected()
94
- now = self.server_time or datetime.now(timezone.utc).replace(tzinfo=None)
95
- end = self._server_naive(end)
96
- start = self._server_naive(start)
97
- if end is None:
98
- end = now + timedelta(days=1) # nothing the server has booked is later than this
99
- if start is None:
100
- start = now - timedelta(days=30)
105
+ start, end = self._window(start, end, "history")
101
106
  ms = int(timeout * 1000) if timeout is not None else int(self._api.DownloadOrderHistoryTimeoutMs)
102
107
  return History._from_core(self._api.DownloadOrderHistory(to_core_time(start), to_core_time(end), ms))
103
108
 
@@ -107,13 +112,33 @@ class _AccountMixin(_Base):
107
112
  self._require_connected()
108
113
  return History._from_core(self._api.RequestDealHistory(int(year), int(month)))
109
114
 
115
+ @translated
116
+ def get_position_deals(self, position_ticket: int, opened_after: Optional[datetime] = None,
117
+ timeout_ms: int = 0) -> List[Deal]:
118
+ """Every deal that makes up one position — the entry, any partial closes, and the close — oldest first.
119
+ ``opened_after`` optionally keeps only deals from that time on; ``timeout_ms`` 0 uses the default wait."""
120
+ self._require_connected()
121
+ from System import DateTime
122
+ after = to_core_time(opened_after) if opened_after is not None else DateTime.MinValue
123
+ result = self._api.GetPositionDeals(int(position_ticket), after, int(timeout_ms))
124
+ return [Deal._from_core(d) for d in (result or ())]
125
+
126
+ @translated
127
+ def reconcile(self) -> ReconcileSnapshot:
128
+ """A consistent snapshot of the open positions and pending orders right now, with the update sequence it is
129
+ current to — for an event-driven client: replace your state with the snapshot, then apply the later updates."""
130
+ self._require_connected()
131
+ return ReconcileSnapshot._from_core(self._api.Reconcile())
132
+
110
133
  @translated
111
134
  def request_history(self, start: datetime, end: datetime) -> None:
112
135
  """Ask for history without waiting; it arrives through :meth:`on_history`. The server's answer is not trimmed
113
- to ``start`` / ``end`` (it can hold more than you asked for, in pages): filter by time. The blocking
114
- :meth:`history` does trim."""
136
+ to ``start`` / ``end`` (it comes in whole calendar months, in pages): filter by time. The blocking
137
+ :meth:`history` does trim. The window rules of :meth:`history` apply; refused while a :meth:`history`
138
+ download runs on this client (:class:`BusyError`), because the answers would mix."""
115
139
  self._require_connected()
116
- self._api.RequestOrderHistory(to_core_time(self._server_naive(start)), to_core_time(self._server_naive(end)))
140
+ start, end = self._window(start, end, "request_history")
141
+ self._api.RequestOrderHistory(to_core_time(start), to_core_time(end))
117
142
 
118
143
  @translated
119
144
  def request_history_month(self, year: int, month: int) -> None:
@@ -121,32 +146,54 @@ class _AccountMixin(_Base):
121
146
  self._require_connected()
122
147
  self._api.RequestOrderHistory(int(year), int(month))
123
148
 
149
+ @property
150
+ def max_history_days(self) -> int:
151
+ """The longest window, in days, one :meth:`history`, :meth:`request_history`, :meth:`summary`,
152
+ :meth:`equity_history` or :meth:`calibrate_money_scale` call may ask for (default 366). A longer window raises
153
+ :class:`InvalidRequestError` before anything is sent: split the period into several calls, or raise this when
154
+ you mean one long download. ``0`` removes the limit (the start and end are still required)."""
155
+ return int(self._api.MaxHistoryDays)
156
+
157
+ @max_history_days.setter
158
+ def max_history_days(self, days: int) -> None:
159
+ self._api.MaxHistoryDays = _history_days(days)
160
+
161
+ def _window(self, start: Optional[datetime], end: Optional[datetime], what: str) -> tuple:
162
+ """``start`` and ``end`` in server time; both are required (the length is checked by the core)."""
163
+ if start is None or end is None:
164
+ raise InvalidRequestError("%s() needs a start and an end: history is always asked for by window "
165
+ "(at most max_history_days, %d days, per call)" % (what, self.max_history_days))
166
+ return self._server_naive(start), self._server_naive(end)
167
+
124
168
  # ---- realized figures and curves ---------------------------------------------------------------------------
125
169
 
126
170
  @translated
127
- def summary(self, start: Optional[datetime] = None, end: Optional[datetime] = None) -> AccountSummary:
128
- """Realized trading result, deposits and withdrawals, from the deal ledger (all time by default).
171
+ def summary(self, start: datetime, end: datetime) -> AccountSummary:
172
+ """Realized trading result, deposits and withdrawals between ``start`` and ``end``, from the deal ledger. Both
173
+ ends are required; the window may be at most :attr:`max_history_days` long — for a longer period, add up one
174
+ summary per window (``balance`` is the account's current balance in each).
129
175
 
130
176
  Downloads the deal history, so it blocks; call it off your UI thread (or use ``asyncio.to_thread``).
131
177
  """
132
178
  self._require_connected()
133
- if start is None and end is None:
134
- return AccountSummary._from_core(self._api.GetAccountSummary())
135
- if start is None or end is None:
136
- raise ValueError("give both start and end, or neither")
137
- return AccountSummary._from_core(self._api.GetAccountSummary(to_core_time(self._server_naive(start)),
138
- to_core_time(self._server_naive(end))))
179
+ start, end = self._window(start, end, "summary")
180
+ return AccountSummary._from_core(self._api.GetAccountSummary(to_core_time(start), to_core_time(end)))
139
181
 
140
182
  @translated
141
183
  def equity_history(self, start: datetime, timeframe: str = "D1", exclude_same_bars: bool = True) -> List[EquityPoint]:
142
- """The balance and equity curve since ``start`` (``timeframe`` is ``H1``, ``H4`` or ``D1``).
184
+ """The balance and equity curve from ``start`` to now (``timeframe`` is ``H1``, ``H4`` or ``D1``); ``start``
185
+ may be at most :attr:`max_history_days` ago.
143
186
 
144
187
  ``balance`` is exact; the historical ``equity`` is a bar-priced reconstruction and a point with
145
188
  ``incomplete`` set has understated floating P/L. With ``exclude_same_bars`` (the default, as in the C# library)
146
- consecutive points with an unchanged balance and equity are dropped. Downloads deals and per-symbol bars, so it
147
- blocks.
189
+ consecutive points with an unchanged balance and equity are dropped. A window with no deal in it is a flat line
190
+ at the balance (never empty); the last point is the live balance and equity. Downloads deals and per-symbol
191
+ bars, so it blocks.
148
192
  """
149
193
  self._require_connected()
194
+ if start is None:
195
+ raise InvalidRequestError("equity_history() needs a start (at most max_history_days, %d days, ago)"
196
+ % self.max_history_days)
150
197
  tf = enum_value(self._core.EquityTimeframe, timeframe, "equity timeframe")
151
198
  points = self._api.CalculateEquityHistory(to_core_time(self._server_naive(start)), tf, bool(exclude_same_bars))
152
199
  return [EquityPoint._from_core(p) for p in (points or ())]
File without changes