Skip to content

Add Windows GUI (pytr-gui) with all CLI commands - #357

Open
parodev93 wants to merge 47 commits into
pytr-org:masterfrom
parodev93:master
Open

parodev93 wants to merge 47 commits into
pytr-org:masterfrom
parodev93:master

Conversation

@parodev93

Copy link
Copy Markdown
Contributor

Summary

  • Adds pytr/gui.py — a Windows desktop GUI (pytr-gui) that wraps all existing CLI commands in a tkinter interface
  • Adds pytr-gui entry point and reportlab dependency to pyproject.toml
  • Adds a GUI (Windows) section to README.md

Details

A tkinter-based Windows GUI that exposes all pytr CLI commands without the terminal. A persistent credentials bar at the top handles login — including the OTP/SMS verification popup — and a Stop button cancels any in-flight operation. Each CLI command has its own tab with the relevant options; all network calls run in background threads so the UI stays responsive. Command output and log messages are captured from sys.stdout/sys.stderr and shown in a scrollable output area at the bottom. The Details tab additionally accepts a free-text name instead of an ISIN, searching for matching instruments via a picker dialog, and exports a formatted PDF via reportlab after fetching details.

parodev93 and others added 30 commits June 3, 2026 12:39
Trade Republic changed their WebSocket API in June 2026: subscriptions to
"compactPortfolio" on web sessions (connect_id=31) now return:

  BAD_SUBSCRIPTION_TYPE: Unknown topic type: compactPortfolio.31

The replacement endpoint is "compactPortfolioByType" which accepts the same
optional secAccNo parameter. The response format changed: positions are now
grouped in categories[].positions instead of a flat top-level positions array.

Additionally, the new format uses "isin" as the field name where the old
endpoint used "instrumentId". The fix normalizes the field at reception so
all downstream code in portfolio.py continues to work unchanged.

Fixes pytr-org#361
Introduces a new `rates` command that fetches current bid/ask prices for
a list of ISINs. ISINs can be passed as positional arguments, read from a
CSV file (-i), or piped via stdin. Output is a fixed-column table to the
console or a semicolon-delimited CSV (-o).

To support code sharing with the existing portfolio command, ticker-fetching
logic (instrument details, ticker subscriptions, bond price correction,
decimal formatting, language normalisation) has been extracted into a new
tickers.py module used by both commands.

Also adds --ignore flag to the portfolio command to exclude specific ISINs.
event_dict.get("eventType", "") only falls back to "" when the key
is missing, not when it's present but null, which Trade Republic
sends for some card events. That None then hits .startswith("card_")
and raises AttributeError.

Added a regression fixture with eventType explicitly null (existing
kartenzahlung_no_eventType.json only covers the key being absent).
Refacture event parsing
Fix some corner cases
Add more tests and sanitize test data
…-org#369)

Add a --load-event-database PATH option to export_transactions that loads
events from an arbitrary all_events.json instead of fetching from Trade
Republic, skipping authentication entirely. --last_days -1 also benefits
from the same fix: both paths now avoid calling login() and no longer
touch self.tr in Timeline.tl_loop().

Improvements to Timeline:
- tl_loop() returns early when fetch_from_tr is false, preventing any
  accidental access to self.tr
- Event database is only written back when data was actually fetched
  (fetch_from_tr and store_event_database both true)
- Log messages distinguish "Loading event database from <path>" (read-only)
  from "Updated event database." (after a live fetch and write)
- Empty or invalid JSON in the event database file logs a warning instead
  of crashing with JSONDecodeError

Add tests/all_events_test.json (5 events: buy, sell, dividend, deposit,
split), a golden CSV, and tests/test_export_transactions.py with 11 tests
covering no-connection guarantee, event loading, chronological sort, no
spurious database write, per-type CSV assertions, and a CLI golden-file test.
This adds a `chmod` that changes the permissions of the credentials file
`~/.pytr/credentials` to only allow reading and writing by the user and not the
group or other users.

SSH does something similar where it requires that private keys must be set to
600 instead of the default 644 mode.
…rage (pytr-org#370)

TR API now delivers eventType values in UPPER_CASE. Normalize the lookup by calling .upper() on eventTypeStr at parse time, then convert all keys in tr_event_type_mapping, events_known_ignored, and inline comparisons to UPPER_CASE accordingly.
Add mappings and ignored entries for newly observed event types (BANK_TRANSACTION_INCOMING/OUTGOING, CARD_TRANSACTION, SAVEBACK_AGGREGATE, SPARE_CHANGE_AGGREGATE, SSP_TAX_CORRECTION, PRIVATE_MARKET_FUND_TRADE_EXECUTED, etc.).
Move all test fixtures from tests/ into tests/events/ and add new fixtures for the newly handled event types.
…nt.py (pytr-org#371)

After parsing, Event.isin/isin2 are now authoritative for SPINOFF and SWAP
events: isin holds the received security, isin2 the source. The note-to-ISIN
lookup tables (_note_to_isin, _swap_note_to_isin_overrides) live in event.py
so any future consumer gets correct ISINs without repeating the lookup.
EQT/Apollo note overrides for PRIVATE_MARKETS_ORDER and TAXES events also
move to event.py.

transactions.py SPINOFF, SWAP, PRIVATE_MARKETS_ORDER, and TAXES branches are
reduced to presentation logic only.

Side effects on exported CSV: private markets notes now follow the standard
"note - title" format (e.g. "EQT - Private Equity" instead of "EQT");
the 1 % Bonus note is no longer overridden by the fund name.

Also: suppress INFO-level log output during pytest runs via conftest.py;
add per-fixture ok: lines to test_events.py for visibility with -s.
- Map SSP_SECURITIES_TRANSFER_INCOMING to TRANSFER_IN, including ISIN
  parsing, share count, and value defaulting to 0
- Add ADDRESS_CHANGED to events_known_ignored
- Add "Kauforder abgelehnt" to events_known_ignored_subtitle
- Add "Fee" to fees_dict lookup for English-language event sections
- Add TRANSFER_IN to the value=0 default guard
- Add test fixtures and test rows for all four new cases
  (address_changed, kauforder_abgelehnt, neues_geraet,
  securities_transfer_incoming)

Closes pytr-org#358. Based on work from PR pytr-org#359 by @shukali.

Co-authored-by: Marcus Rottschäfer <shukali@users.noreply.github.com>
Cleanups and fixes to dl_docs processing, try to cover lot of new and changed events/documents from TR.
Flatten document subfolders for Trades, Sparplan, Saveback, RoundUp (Abrechnung), Zinsen, Einzahlungen, Auszahlungen, and Aktien-Bonus (now under Misc).
Remove the history file mechanism.
Add testing of download paths and add more test fixtures.
Parametrize test_events for per-fixture pytest output.
Co-authored-by: tharshan09@github.com
The Playwright strategy pulls in a ~130 MB package and a ~630 MB Chromium
download for one job: fetching an AWS WAF token once per web login. Not
every deployment is challenged by that WAF, and the pure-Python `awswaf`
strategy solves the same challenge without a browser. Three changes so
that choice is actually available:

* `playwright` moves to an optional extra and is imported inside
  `_fetch_waf_token_playwright` instead of at module level, so
  `import pytr.api` no longer requires it. A missing install is reported
  with the command that fixes it.

* The retry branch that ran `playwright install chromium` via subprocess
  is gone. It was reached by *any* exception -- a timeout, a network
  blip, a WAF change -- and answered all of them by downloading and
  executing a browser at runtime, inside the process holding the user's
  PIN and cookies, bypassing whatever pinning the installing environment
  had applied. It only ever helped for one of the failures that reached
  it.

* `pytr.awswaf` is imported lazily too (it reads webgl.json at import
  time), and its two unbounded loops are bounded, because switching to
  it as a fallback puts them on the login path:
  - the challenge.js host is scraped out of the login page with a regex
    and then requested; it is now required to be `*.token.awswaf.com`,
    which removes the request-forgery primitive.
  - `hash_pow` and `compute_scrypt_nonce` looped over
    `itertools.count()` with no exit but success, while `difficulty`
    comes from the server. Anything above 256 can never be satisfied at
    all. Both now stop, and `build_payload` raises instead of posting a
    null solution.
  - `network_bandwidth` allocated a buffer sized by a number parsed out
    of challenge.js. Capped at the largest size AWS' own table uses.

CLI behaviour is unchanged: `--waf-token` still defaults to
`playwright`, and its help text now names the extra and the
browser-free alternative.
Improve documentation and error messages for trade republic login options
Default login option is v1, using the playwright method to obtain the AWS WAF token.
New login option -v2 is not using an AWS WAF token by default.
Error messages when playwright/chromium are not available are improved and also if WAF token was likely rejected.
Documentation for old App Login was removed from README.md since the feature had been removed some time ago.
Events of type SSP_CORPORATE_ACTION_INVOICE_CASH or SSP_CORPORATE_ACTION_CASH are now classified as taxes if they have a negative value and as dividends otherwise. This simplifies the logic and seems to correctly handle all known cases.
RealCLanger and others added 17 commits September 15, 2026 20:22
* Make the README mksync check runnable on macOS

The check normalised both sides with `sed -z '$s/\n*$//'` before diffing.
`-z` is a GNU extension. BSD sed, which is what macOS ships, rejects it:

    sed: illegal option -- z

Because the flag failed on *both* sides of the diff, the step compared two
empty streams and exited 0. On a Mac it did not merely fail to work, it
reported success on a README that was actually stale, so a contributor
checking locally before pushing got a green result and a red CI.

`$(...)` already strips every trailing newline, and `printf '%s\n'` puts
exactly one back, so the same normalisation happens with no GNU-only flag and
the readable `diff -u` output is kept.

Verified on macOS: the new command exits 0 on the current README, and exits 1
with the expected one-line table-of-contents diff once a heading is added
without regenerating. The old command exits 0 in both cases.
The logic did not wait for the confirmation of the popup in the app so it could never complete authentication.
…unt (pytr-org#399)

* Support company and child accounts via --account

A Trade Republic login can act for more accounts than its own, e.g. a
company account (legal entity) or a child's account. These are separate
customers: the web app lists them at /api/v1/customer/relationships/detailed
and switches by posting the customer id as subjectId to
/api/v2/auth/web/session, which swaps the session tokens.

- add relationships() and switch_account() to the API, and --account to
  every subcommand that logs in
- keep the session on the chosen account when it is refreshed
- read the securities account number from the accountPairs topic when
  /api/v2/auth/account refuses with INVALID_AUTH_ACCOUNT_STATE, which it
  does while the session acts for another account
- accept saved cookies that act for another account instead of forcing a
  new login, and return to the own account when --account is not given

* Add an accounts command that lists what --account accepts

Prints type, name and state of every account the login can act for, from
the same relationships call the switch resolves its argument with.
…nt (pytr-org#382)

* Allow overriding the TR app version and User-Agent from the environment

The v2 login identifies itself as Trade Republic's own web frontend, using
two values that describe someone else's deployment: APP_VERSION, sent as
X-TR-App-Version, and the browser User-Agent. Trade Republic can invalidate
either one at any moment. A frontend release makes APP_VERSION stale, at
which point every login returns 426 CLIENT_VERSION_OUTDATED, which is exactly
what pytr-org#250 was; a change to their bot filtering can make the User-Agent the
thing being rejected.

Neither failure needs a code change to fix. It needs a different string. But
because both are baked into the module, a user locked out today has to wait
for a release, and the maintainers have to cut one under time pressure.

PYTR_TR_APP_VERSION and PYTR_TR_USER_AGENT override them, so the fix becomes
an exported variable and the release can happen at its own pace. An unset or
empty variable keeps the built-in default, so an empty assignment can never
send an empty header.

X-TR-Device-Info stays consistent with whatever User-Agent is in force:
browserVersion is scraped from it, and a non-Chrome override leaves that
field empty rather than reporting a version the browser never claimed. The
frontend omits fields it cannot fill too, and the server accepts their
absence.

Tests cover both overrides, the empty-value fallback, the absence of
cross-instance leakage, and the device-info consistency. README documents
both variables, where to read current values from the live frontend, and
asks users who need one to open an issue so the default gets updated.
Preserve the rebased README and GUI version label.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.