Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
42602ba
Add Windows GUI (pytr-gui) with all CLI commands
parodev93 Jun 3, 2026
6df4cf5
Fix ruff linting errors in gui.py: sort imports and split semicolon s…
parodev93 Jun 3, 2026
f8a8700
Apply ruff format to gui.py
parodev93 Jun 3, 2026
d67b20f
Fix mypy errors: add types-reportlab dev dependency, annotate story/r…
parodev93 Jun 3, 2026
7f7e09f
Fix import order in gui.py
parodev93 Jun 3, 2026
449e63d
Handle private markets sell order and IPO
RealCLanger Jun 17, 2026
74ca148
fix: replace compactPortfolio with compactPortfolioByType
LoicSERRE Jun 21, 2026
e69aa2d
Add support for TRANSFER_IN and TRANSFER_OUT events (#308)
MedAzizKhayati Jun 25, 2026
24163dc
Add rates command (#363)
RealCLanger Jun 27, 2026
080bc59
Fix crash in _parse_card_note when eventType is null
Titouan-Loeb Jul 18, 2026
8962f5c
Refacture event parsing (#366)
RealCLanger Jul 25, 2026
753353c
Sanitize test data (#367)
RealCLanger Jul 25, 2026
1905ce8
export_transactions: add --load-event-database to skip TR login (#369)
RealCLanger Jul 25, 2026
9d7b32a
Store credentials file with restricted 600 perms (#368)
KevSlashNull Jul 26, 2026
e46ac8a
Normalize event type strings to UPPER_CASE and extend event type cove…
RealCLanger Jul 26, 2026
a84286d
Move ISIN resolution and note overrides from transactions.py into eve…
RealCLanger Jul 26, 2026
d0b25c3
Add parsing for SSP_SECURITIES_TRANSFER_INCOMING and more ignored events
RealCLanger Jul 26, 2026
08ba6ec
Overhaul dl_docs
RealCLanger Jul 27, 2026
66f2359
New login method (#380)
RealCLanger Aug 5, 2026
71b11dd
Make playwright optional and bound the awswaf path
tharshan09 Jul 31, 2026
ab39136
Document the --v2 web login flag in the README (#355)
twannooitmeer Aug 6, 2026
969ce1a
Cleanup login options
RealCLanger Aug 6, 2026
2bf197c
Stop flagging informational events as unknown/skipped warnings (#379)
felixschndr Aug 6, 2026
6eb05e5
Fix handling of interest (new event type)
RealCLanger Aug 6, 2026
1cff3d7
Bump version to 0.4.11
RealCLanger Aug 6, 2026
26637c0
Adapt to name change of Honeywell Aerospace in mapping table
RealCLanger Aug 7, 2026
ff4350d
Classify negative cash invoices as taxes (#387)
Guflly Aug 9, 2026
174ffd0
Add a test fixture for testing incoming transfer without eventType fi…
RealCLanger Aug 9, 2026
d5c0389
Support Trade Republic Card Purchase without event type
RealCLanger Aug 9, 2026
1fd5c3c
Better implementation of SWAP transactions (#394)
RealCLanger Aug 14, 2026
5625f81
Add Handling for Teva Swap
RealCLanger Sep 15, 2026
e7f3ba3
Ignore pending savings plans
RealCLanger Sep 16, 2026
64cbdd1
Make the README mksync check runnable on macOS (#390)
twannooitmeer Oct 7, 2026
353839d
Fix details without instrument suitability
TiloHeidasch Oct 7, 2026
9cb07f5
Fix weblogin v2 logic with totp enabled (#400)
Zorgosto Oct 7, 2026
d855855
Support other accounts of a login, e.g. a company account, via --acco…
HerrNiklasRaab Oct 8, 2026
db34fa3
Allow overriding the TR app version and User-Agent from the environme…
twannooitmeer Oct 8, 2026
6cb84d8
Add from_timestamp and until_timestamp to export_transactions command
RealCLanger Oct 12, 2026
3998052
Add TK Accelis Spinoff
RealCLanger Oct 30, 2026
85f7657
Send login headers on v1 web login requests (#413)
phatloi0010 Nov 2, 2026
52cbc69
Add Windows GUI (pytr-gui) with all CLI commands
parodev93 Jun 3, 2026
83b0178
Fix ruff linting errors in gui.py: sort imports and split semicolon s…
parodev93 Jun 3, 2026
224e743
Apply ruff format to gui.py
parodev93 Jun 3, 2026
d6f89c8
Fix mypy errors: add types-reportlab dev dependency, annotate story/r…
parodev93 Jun 3, 2026
bba152e
Fix import order in gui.py
parodev93 Jun 3, 2026
8c69431
Add version label to footer in PytrGUI
parodev93 Nov 13, 2026
83af087
Merge fork master after rebase
parodev93 Nov 13, 2026
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
6 changes: 3 additions & 3 deletions .github/workflows/publish-pypi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ jobs:
- name: Pytest
run: uv run pytest
- name: Ruff check
run: uv run ruff check
run: uvx ruff@0.9.6 check
- name: Ruff format
run: uv run ruff format --check --diff
run: uvx ruff@0.9.6 format --check --diff
- name: Mypy type check
run: uv run mypy .
- name: Check if README.md automatically generated content is up to date
run: diff -u <(cat README.md | sed -z '$s/\n*$//') <(uvx mksync@0.1.5 README.md | sed -z '$s/\n*$//')
run: diff -u <(printf '%s\n' "$(cat README.md)") <(printf '%s\n' "$(uvx mksync@0.1.5 README.md)")

build-n-publish:
name: Build and publish Python distributions to PyPI
Expand Down
89 changes: 71 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ __Table of Contents__
<!-- toc -->
* [Quickstart](#quickstart)
* [Usage](#usage)
* [GUI (Windows)](#gui-windows)
* [Authentication](#authentication)
* [Web login (default)](#web-login-default)
* [App login](#app-login)
* [Web login](#web-login)
* [If web login suddenly stops working](#if-web-login-suddenly-stops-working)
* [Other accounts of your login](#other-accounts-of-your-login)
* [Development](#development)
* [Setting Up a Development Environment](#setting-up-a-development-environment)
* [Linting and Code Formatting](#linting-and-code-formatting)
Expand Down Expand Up @@ -62,17 +64,20 @@ If you want to use the cutting-edge version, use this command instead:
<!-- runcmd code:console uv run --python 3.13 pytr help --for-readme -->
```console
usage: pytr [-h] [-V] [-v {warning,info,debug}] [--debug-logfile DEBUG_LOGFILE] [--debug-log-filter DEBUG_LOG_FILTER]
{help,login,portfolio,details,dl_docs,export_transactions,get_price_alarms,set_price_alarms,get_savings_plans,completion} ...
{help,login,accounts,portfolio,rates,details,dl_docs,export_transactions,get_price_alarms,set_price_alarms,get_savings_plans,completion} ...

Use "pytr command_name --help" to get detailed help to a specific command

Commands:
{help,login,portfolio,details,dl_docs,export_transactions,get_price_alarms,set_price_alarms,get_savings_plans,completion}
{help,login,accounts,portfolio,rates,details,dl_docs,export_transactions,get_price_alarms,set_price_alarms,get_savings_plans,completion}
Desired action to perform
help Print this help message
login Check if credentials file exists. If not create it and ask for input. Try to
login. Ask for device reset if needed
accounts List accounts of this login, e.g. a company accounts or child accounts. Use them
with --account
portfolio Show current portfolio
rates Fetch current prices for a list of ISINs given as direct list or CSV input
details Get details for an ISIN
dl_docs Download all pdf documents from the timeline and sort them into folders. Also
export account transactions (account_transactions.csv) and JSON files with all
Expand All @@ -93,30 +98,78 @@ Options:
```
<!-- end runcmd -->

## GUI (Windows)

A Windows desktop interface that exposes all pytr functionality without the command line.
It requires the same Python installation and dependencies as the CLI.

After installing (see [Quickstart](#quickstart)), run:

```sh
pytr-gui
```

## Authentication

There are two authentication methods:
### Web login

Web login uses the public web-login endpoints at `api.traderepublic.com`. Two variants are available:

- **v1 (default)**: `pytr login`. You receive a four-digit code in the TradeRepublic app (or via SMS as a
fallback) and enter it in the terminal. This is the original behavior; nothing changes for existing users.
v1 requires passing an AWS WAF token with the login request; by default pytr fetches one automatically
via Playwright (requires the optional `playwright` extra: `pip install 'pytr[playwright]' && playwright install chromium`).
The pure-Python alternative `--waf-token awswaf` exists but has been reported to no longer work reliably.
- **v2 (opt-in)**: `pytr login --v2`. Mirrors what
[app.traderepublic.com](https://app.traderepublic.com/) currently does. Instead of typing a four-digit code, you
confirm the login from a push notification in the Trade Republic mobile app. Accounts secured with an authenticator
app are asked for a code from that app instead. Useful if your account no longer issues a code via the app or SMS.
v2 does not require a WAF token; pytr skips it automatically when `--v2` is used.
Note that Trade Republic removed the SMS resend endpoint along with the v1 web login, so there is no SMS fallback
under `--v2`. The flag is available on every subcommand that performs a login, e.g. `pytr portfolio --v2`,
`pytr dl_docs --v2`.

### Web login (default)
Both variants keep you logged in on your primary device, but you may need to re-authenticate every so often when
running `pytr`.

Web login is the newer method that uses the same login method as [app.traderepublic.com](https://app.traderepublic.com/),
meaning you receive a four-digit code in the TradeRepublic app or via SMS. This will keep you logged in your primary
device, but means that you may need to repeat entering a new four-digit code ever so often when runnnig `pytr`.
### If web login suddenly stops working

### App login
The web login identifies itself to Trade Republic as their own web frontend, using a build version, a platform name
and a browser `User-Agent` that are pinned in `pytr`. Trade Republic can invalidate any of them at any time, and when
they do, login fails for everyone until a new release goes out. Three environment variables let you fix it yourself
in the meantime:

App login is the older method that uses the same login method as the TradeRepublic app. First you need to perform a
device reset - a private key will be generated that pins your "device". The private key is saved to your keyfile. This
procedure will log you out from your mobile device.
| Variable | Overrides | Use it when |
|---|---|---|
| `PYTR_TR_APP_VERSION` | The frontend build version sent as `X-TR-App-Version` | Login fails with `426 CLIENT_VERSION_OUTDATED` |
| `PYTR_TR_USER_AGENT` | The `User-Agent` sent on every request | Login is rejected or challenged in a way that looks like bot filtering |
| `PYTR_TR_PLATFORM` | The platform name sent as `X-Tr-Platform` | Login fails with a missing or invalid header error naming the platform |

```sh
pytr login
# or
pytr login --phone_no +49123456789 --pin 1234
PYTR_TR_APP_VERSION=2.2700.4 pytr login --v2
PYTR_TR_USER_AGENT='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36' pytr login
PYTR_TR_PLATFORM=web pytr login --v2
```

If no arguments are supplied pytr will look for them in the file `~/.pytr/credentials` (the first line must contain
the phone number, the second line the pin). If the file doesn't exist pytr will ask for for the phone number and pin.
Read the current values off [app.traderepublic.com](https://app.traderepublic.com/) in your browser's dev tools, on the
network request to `/api/v2/auth/web/login`. Leaving a variable unset, or setting it to an empty string, keeps the
built-in default. If you need one of these, please also open an issue so the default can be updated for everyone.

### Other accounts of your login

A Trade Republic login can hold more than its own account, e.g. company accounts or child accounts. Trade Republic
treats each of them as a customer of its own, and the web app switches between them after the login. Pass `--account`
to do the same, on any subcommand that performs a login:

```sh
pytr portfolio --account LEGAL_ENTITY
pytr dl_docs --account "Mustermann Holding GmbH" ./docs
```

The value is the account's type, its name or its customer id, as listed by `pytr accounts`. Without `--account`,
pytr uses your own account. The choice is not remembered between runs.

Unfortunately, it seems that this only works with company accounts, not with child accounts at the moment.

## Development

Expand Down
19 changes: 19 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import pytest

import pytr.utils as pytr_utils


@pytest.fixture(autouse=True)
def suppress_info_logs(monkeypatch):
# pytr loggers call coloredlogs.install(level=log_level, ...) with propagate=False,
# bypassing pytest's capture. Setting log_level to "warning" before tests run
# makes all subsequently created loggers install at WARNING level.
monkeypatch.setattr(pytr_utils, "log_level", "warning")
# Also raise the level on handlers already installed on existing loggers.
import logging

for lg in logging.root.manager.loggerDict.values():
if isinstance(lg, logging.Logger):
for handler in lg.handlers:
handler.setLevel(logging.WARNING)
yield
20 changes: 16 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "pytr"
version = "0.4.10"
version = "0.4.11"
description = "Use TradeRepublic in terminal"
readme = "README.md"
requires-python = ">=3.10"
Expand All @@ -29,27 +29,39 @@ dependencies = [
"curl_cffi",
"packaging",
"pathvalidate",
"playwright",
"pygments",
"reportlab",
"requests_futures",
"shtab",
"websockets>=14",
]

[project.optional-dependencies]
# Only `--waf-token playwright` (the CLI default) needs this, and it drags in a
# ~130 MB package plus a ~630 MB Chromium download that `playwright install`
# fetches separately. The pure-Python `--waf-token awswaf` path solves the same
# challenge without either, so deployments that use it — or that find their IP
# is not challenged at all — should not have to carry the browser.
playwright = [
"playwright>=1.62.0",
]

[project.scripts]
pytr = "pytr.main:main"
pytr-gui = "pytr.gui:main"

[tool.hatch.build.hooks.babel]
locale_dir = "pytr/locale"

[dependency-groups]
dev = [
"ruff>=0.9.4",
"ruff==0.9.6",
"pytest>=8.3.4",
"mypy>=1.15.0",
"types-babel>=2.11.0.15",
"types-requests>=2.32.0.20241016",
"types-pygments>=2.19.0.20250107",
"types-reportlab",
"types-requests>=2.32.0.20241016",
]

[tool.ruff]
Expand Down
79 changes: 62 additions & 17 deletions pytr/account.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import json
import os
import sys
import time
from getpass import getpass

import requests
from pygments import formatters, highlight, lexers

from .api import BASE_DIR, CREDENTIALS_FILE, TradeRepublicApi
from .api import BASE_DIR, CREDENTIALS_FILE, TradeRepublicApi, account_kind, account_name
from .utils import get_logger


Expand All @@ -18,10 +20,34 @@ def get_settings(tr):
return formatted_json


def login(phone_no=None, pin=None, store_credentials=False, waf_token="playwright"):
def print_accounts(tr):
"""List the accounts of this login, one per line: type, name, customer id and state.

`--account` takes the type, the name or, where those are not unique, the customer id.
"""
rows = [
(
account_kind(r),
account_name(r),
str(r.get("customerId") or ""),
"your own account" if r.get("relationshipType") == "SELF" else str(r.get("accountState") or ""),
)
for r in tr.relationships()
]
if not rows:
return ""
heading = ("TYPE", "NAME", "CUSTOMER ID", "STATE")
widths = [max(len(heading[i]), max(len(row[i]) for row in rows)) for i in range(4)]
all_rows = [heading] + rows
return "\n".join(" ".join(f"{cell:<{width}}" for cell, width in zip(row, widths)).rstrip() for row in all_rows)


def login(phone_no=None, pin=None, store_credentials=False, waf_token="playwright", v2=False, account=None):
"""
Handle credentials parameters and store to credentials file if requested.
If no parameters are set but are needed then ask for input

`account` selects another account of this login, e.g. a company account.
"""
log = get_logger(__name__)
save_cookies = True
Expand All @@ -47,12 +73,13 @@ def login(phone_no=None, pin=None, store_credentials=False, waf_token="playwrigh
if store_credentials:
with open(CREDENTIALS_FILE, "w") as f:
f.writelines([phone_no + "\n", pin + "\n"])
os.chmod(CREDENTIALS_FILE, 0o600)

log.info(f"Storing credentials/cookies in {BASE_DIR}")
else:
save_cookies = False

tr = TradeRepublicApi(phone_no=phone_no, pin=pin, save_cookies=save_cookies, waf_token=waf_token)
tr = TradeRepublicApi(phone_no=phone_no, pin=pin, save_cookies=save_cookies, waf_token=waf_token, use_v2_login=v2)

# Use same login as app.traderepublic.com
if not tr.resume_websession():
Expand All @@ -62,22 +89,40 @@ def login(phone_no=None, pin=None, store_credentials=False, waf_token="playwrigh
log.fatal(str(e))
sys.exit(1)
request_time = time.time()
print("Enter the code you received to your mobile app as a notification.")
print(f"Enter nothing if you want to receive the (same) code as SMS. (Countdown: {countdown})")
code = input("Code: ")
if code == "":
countdown = countdown - (time.time() - request_time)
for remaining in range(int(countdown)):
print(
f"Need to wait {int(countdown - remaining)} seconds before requesting SMS...",
end="\r",
)
time.sleep(1)
print()
tr.resend_weblogin()
code = input("SMS requested. Enter the confirmation code:")
if v2:
if tr.weblogin_needs_authenticator:
code = input("Enter the code from your authenticator app: ")
else:
print(f"Confirm the login in your Trade Republic app. (Countdown: {countdown})")
code = None
else:
print("Enter the code you received to your mobile app as a notification.")
print(f"Enter nothing if you want to receive the (same) code as SMS. (Countdown: {countdown})")
code = input("Code: ")
if code == "":
countdown = countdown - (time.time() - request_time)
for remaining in range(int(countdown)):
print(
f"Need to wait {int(countdown - remaining)} seconds before requesting SMS...",
end="\r",
)
time.sleep(1)
print()
tr.resend_weblogin()
code = input("SMS requested. Enter the confirmation code:")
tr.complete_weblogin(code)
log.info("Logged in.")

log.debug(get_settings(tr))

if account is not None:
try:
tr.switch_account(account)
except ValueError as e:
log.fatal(str(e))
sys.exit(1)
except requests.exceptions.HTTPError as e:
status = e.response.status_code if e.response is not None else "unknown"
log.fatal(f"Trade Republic refused to switch to account {account!r} (status {status}).")
sys.exit(1)
return tr
Loading