Trade Republic: count transfers with the user's reference account as contributions and withdrawals
Follow-up to #5069 / #5070 (merged).
Summary
#5070 counts a Trade Republic Cash deposit as a contribution only when it is linked to a bank account in Sure, or labelled Contribution. Trade Republic Cash is often a current account, and a salary or a payment from someone else arrives there with the same event types as a deposit from the user's own bank (INCOMING_TRANSFER, INCOMING_TRANSFER_DELEGATION, BANK_TRANSACTION_INCOMING). So the event type alone can't tell them apart.
The payload already has what's needed:
-
The other party's IBAN. A transfer's
timelineDetailV2names the sender (transfer in) or the recipient (transfer out) in a row titledIBAN. Examples are pytr's anonymised fixturesincoming_transfer.json,bank_transaction_incoming.jsonandbank_transaction_outgoing.json, and thetransfer_detailhelper in our own client test. -
The user's reference accounts.
GET /api/v2/auth/account, whichProvider::TradeRepublicClient#sync_oncealready calls on every sync, returns them asreferenceAccountList[{iban,bic,bankName,logoUrl}],referenceAccountandreferenceAccountV2, pluscashAccount.iban. These are the accounts in the user's name that Trade Republic pays out to. Three unofficial clients record the same fields:- tr-cli's live probe notes;
- the strict schema in trade-republic-sdk;
- handelsrepublik's
src/schemas/registry.ts.
REFERENCE_ACCOUNT_CHANGEDcarries no IBAN (example), so it stays ignored.
A transfer between the Cash account and one of those reference accounts is the user moving their own money. This PR imports such transfers as funds movements.
The rule
On the Trade Republic Cash account, a payment event whose detail is read for its note (CASH_NOTE_EVENT_TYPES) imports as funds_movement when the detail shows exactly one distinct IBAN and that IBAN is a reference account. The reference accounts come from referenceAccountList, referenceAccountV2 and referenceAccount, without cashAccount.iban, normalised (all Unicode whitespace removed, upper case, IBAN-shaped).
CASH_NOTE_EVENT_TYPES covers BANK_TRANSACTION_INCOMING, INCOMING_TRANSFER(_DELEGATION), PAYMENT_INBOUND(_SEPA_DIRECT_DEBIT), BANK_TRANSACTION_OUTGOING(_DIRECT_DEBIT/_SCHEDULED), OUTGOING_TRANSFER(_DELEGATION) and PAYMENT_OUTBOUND.
The direction stays as it is today: money in is a contribution, money out is a withdrawal.
Any other payment stays a standard transaction. That includes a salary, a payment from someone else, rent, and a top-up by card, Apple Pay or Google Pay (their detail names no IBAN). Automatic transfer matching still links any of them to an account in Sure.
- Direct debits. A direct debit (
PAYMENT_INBOUND_SEPA_DIRECT_DEBIT,BANK_TRANSACTION_OUTGOING_DIRECT_DEBIT,PAYMENT_INBOUND) counts when its detail names the reference account's IBAN, because the money comes from the user's own account. That answers #3807's concern ("even when the money came from someone else or from a bank that is not in Sure") for these rows. The one direct-debit top-up detail we've seen shows no IBAN, so such a top-up only counts when Trade Republic shows one. - Why
funds_movementand not aContributionlabel. A label alone doesn't keep the row out of budgets. On a Cash account linked to a bank (Depository) account,Account::ProviderImportAdapterkeeps a labelled depositstandard(since #5735), so it counts as income. On one linked to an Investment account it booksinvestment_contribution, which budgets count as spending (#3770).funds_movementkeeps the row out of budgets, andrecorded_flow_sqlandPortfolio::FlowClassifier(from #5070, now on main) already count an unlinked funds movement by its sign.Totalsand the classifier are unchanged. - The Portfolio account is unchanged.
Privacy
Only the result of the match is stored: detail["counterparty"] = "reference_account" and a counterparty_checked_at marker. Neither the counterparty's IBAN nor the reference IBANs are written to raw_timeline_payload, to the transaction's extra, to logs or to warnings. The reference IBANs exist only in memory during the sync. The match result shows in extra.trade_republic.provider_detail, so a Rule can match on reference_account.
Changes
Provider::TradeRepublicClient:
reference_ibans(account)reads the reference accounts from the account response thatsync_oncealready fetches, and passes them throughcollect_all_timelinetoenrich_timeline_details.- For a transfer it reads for its note,
reference_account_counterparty?compares the detail'sIBANrows with them. A row whosedetailisn't a hash is skipped. counterparty_checked_atis set only when at least one reference account was listed. It is added toRETRY_MARKER_KEYS, so it stays out ofextra.- A transfer waits for the counterparty check only in a sync that has reference accounts (
cash_note_pending?/cash_note_read?takecheck_counterparty:).- Without them, the sync reads each new transfer's note as before, re-reads nothing for the check, and warns once if a transfer is waiting: "account response listed no reference accounts; transfer counterparties were not checked". The importer logs that as one
DebugLogEntryper sync. - A later sync that lists one picks the waiting transfers up from the detail backlog. That includes transfers on the catch-up page, which are read through their stored copy. Only the detail comes from that copy; the page's status, title and lifecycle flags win. A transfer the page shows as cancelled is not read.
- Without them, the sync reads each new transfer's note as before, re-reads nothing for the check, and warns once if a transfer is waiting: "account response listed no reference accounts; transfer counterparties were not checked". The importer logs that as one
- Transfers read before this change wait for the check the same way. In the backlog they sort after trades, dividends and transfers whose note was never read, so they can't crowd those out of the usual 200 details per sync.
TradeRepublicAccount::ActivitiesProcessor:
#own_funds_movement_kindapplies the rule on the Cash account and keeps the old rule on the Portfolio account.- The legacy reset uses the resolved kind. A deposit an older sync stored as
funds_movementkeeps that kind when it is a reference transfer, instead of being reset to standard. - A deposit stored as
investment_contributionbecomes a funds movement and loses the auto-assigned Investment Contributions category andContributionlabel, as the standard reset does, unless a Rule set them. - User-edited rows and confirmed transfers are left alone, as today.
What users will see
- On Trade Republic Cash, deposits from and payouts to the user's reference account become funds movements.
- The investment card counts them as contributions and withdrawals, also when the bank isn't in Sure. A deposit linked to a bank account in Sure still counts once, before and after the suggested transfer is confirmed.
- They leave budgets and the income statement: an own-bank deposit is no longer income.
- Rules with "transaction type = income" (or expense) no longer match them, because that filter excludes transfer kinds. "Type = transfer" now matches them.
- A salary, payments from other people, rent and card spending are unchanged.
Limits
- Reference accounts that changed. The match is decided when the detail is read. If the user later replaces their reference account, deposits from the old one match only if Trade Republic still lists it. We have not verified whether
referenceAccountListkeeps former reference accounts. Deposits that don't match stay standard, as today. - The
IBANrow title. The public fixtures are German. That Sure, which connects withlocale: "en", gets the row titledIBANhas not been checked against a live account. If it isn't, nothing matches and the rows stay standard. - Only one IBAN may appear. A detail with two distinct IBANs is not matched. That would include one that also showed the Cash account's own IBAN; the fixtures never do.
- Rejected or unmatched suggested transfers. If auto-matching suggests a transfer for a reference deposit and the user rejects it, or the bank leg is never linked, the Trade Republic leg stays a funds movement and counts on its own. The bank-side leg, if it is in Sure, is classified by its own account as before.
- Two Trade Republic logins in one family. Each connection matches against its own login's reference accounts. A transfer between the two logins' Cash accounts is matched only where the other login's Cash IBAN is a reference account, which it normally isn't.
- The marker is sticky. Once a transfer is checked, it isn't checked again. A reference account added later doesn't re-classify older transfers.
- When the account response lists no reference account, no transfer is checked. Every sync logs one warning while transfers wait, and nothing extra is read.
- Masked IBANs don't match. pytr's
incoming_transfer_delegation.jsonshowsDEXX XXXX ā¦, probably pytr's anonymisation. If Trade Republic itself masks an IBAN, that transfer stays standard. - Legacy rows move in two steps. A deposit an older sync stored as a funds movement or investment contribution is reset to standard first, as today, and becomes a funds movement once its detail is re-read from the backlog. Until then, monthly figures can differ.
- Legacy and unsupported types are not covered. Pre-migration
timeline_legacy_migrated_eventsrows, which show "Von/An" and IBAN (pytr'sdeposit.jsonandoutgoing_transfer_legacy.json), aren't imported by Sure at all today, so they are out of scope.
Open question for review
A user who runs Trade Republic Cash as a current account may top it up from their reference bank and then spend by card. Each top-up is now a contribution, and the card spending is deliberately not a withdrawal (#5070's recorded_flow_sql leaves unlinked card rows out). Contributions then keep growing with nothing lowering them. This is the other side of counting own-bank deposits at all. Is it acceptable as is, documented as a limit? Or should the rule apply only when the account isn't used for card spending? A per-account setting is one option, but it adds UI for one provider.
A related choice is also open. Card, Apple Pay and Google Pay top-ups are own money by construction, but this PR keeps them standard, as #3807 decided. Should they count too?
Tests
Provider::TradeRepublicClient:
- Reference IBANs:
- read from all three fields and from a single-object list;
- normalised, including non-breaking spaces;
- without the Cash account's own IBAN.
- The single-IBAN match:
- no match with two distinct IBANs, or with no reference account;
- a duplicate or empty
IBANrow still matches; - a non-hash row detail is skipped.
- A reference transfer and a direct debit are marked, and no IBAN appears in the stored event.
- With no reference account listed, the counterparty stays unchecked and one warning is emitted, also through a full
sync. A transfer read only for its note is not pending without reference accounts, and is pending with them. - No warning when the only transfers are already-checked ones on the catch-up page.
- On the catch-up page, the stored copy is checked and the page's newer status and title win; a cancelled one is not read.
- Transfers waiting only for the check sort last in the backlog.
- The backlog and pending tests use the new marker.
TradeRepublicAccount::ActivitiesProcessor:
- Own transfer in, own bank transaction in, own transfer out and own direct debits in and out become funds movements, with no label or category and the flag in
extra. A salary, rent and a card top-up stay standard. - A row imported before its counterparty was known becomes a funds movement on the next sync, unless the user edited it.
- A legacy
funds_movementreference deposit keeps its kind, and one from someone else is reset. - A legacy
investment_contributionreference deposit loses its stale category and label, and a Rule-assigned one keeps them.
TradeRepublicItem::Importer:
- The missing-reference warning is logged once per sync.
- A transfer read only for its note is passed as read and also offered for its check.
- 200 transfers waiting for the check don't crowd out one whose note was never read.
- Fixtures use the new marker.
InvestmentStatement:
- With the bank not in Sure, an own 1,000 in and 300 out give contributions 1,000 and withdrawals 300 (buys 800). A 2,500 salary, 40 from a friend and 900 rent are not counted.
- With the bank in Sure, the deposit counts once, before and after confirming the suggested transfer.
Each new test fails when its piece of the change is reverted (checked one by one). 698 runs, 0 failures, 0 errors, rebased onto main after #5070 merged, across:
- the Trade Republic model tests;
investment_statement*;test/models/portfolio;account/provider_import_adapter_test.rb.
bin/rubocop is clean on the changed files. InvestmentStatementTest#test_totals_cache_invalidates_when_an_exchange_rate_is_stored failed once in about five full runs and passed on every rerun. It doesn't touch this code.
Prepared with AI assistance (Claude Code).
š¤ Generated with Claude Code
Summary by cubic
Counts Trade Republic Cash deposits and payouts as investment contributions and withdrawals when a transfer's counterparty matches one of the login's reference accounts, so own-money flows show on the investment card even when the bank isn't linked in Sure.
The investment card now counts external inflows and outflows instead of summing trades, and reads a Trade Republic connection's Cash account alongside its Portfolio and Crypto accounts, so settlements are internal and a deposit counts once. Card and loan payments booked on the Cash account no longer count as withdrawals. Buy and sell sums stay available as PeriodTotals#buys and #sells, and the demo's recorded transfers are created confirmed so they count. A transfer becomes a funds movement when its detail names exactly one IBAN that matches one of the login's reference accounts (from the account response every sync already fetches); only the match result is stored. Transfers read before this check are re-read from the detail backlog once, and legacy rows are re-classified on the next sync. A sync that lists no reference accounts reads nothing extra, warns once, and checks waiting transfers in a later sync.
- Skips the check for transfers the page shows as cancelled, and keeps the page's newer status and title when reading a stored copy.
- Unmatched rows ā salary, third-party payments, rent, card top-ups ā stay standard transactions.
- Direct debits whose detail names the reference IBAN also count as the user's own money.
Summary by CodeRabbit
- Bug Fixes
- Trade Republic transfers to or from your reference account are classified as fund movements rather than ordinary income or expenses. Other transfers and payments retain their standard classification.
- Deposits and withdrawals involving a reference account are reflected correctly in investment summaries, whether or not the bank account is linked.
- When transfer details arrive later, classifications update while preserving user-edited entries and newer transaction information.
- Transfer matching handles normalized account details without exposing IBANs. When reference account details are unavailable, transfers remain unchecked and a warning is shown.