The personal finance app for everyone (by everyone)
Ruby
fix(trade-republic): Trade Republic bond valuation using percent-of-par prices (#4020)
Simone196355b17151
diff --git a/app/models/provider/trade_republic_client.rb b/app/models/provider/trade_republic_client.rbindex 5d7074f9e3..bd9f624e41 100644--- a/app/models/provider/trade_republic_client.rb+++ b/app/models/provider/trade_republic_client.rb@@ -769,11 +769,19 @@ class Provider::TradeRepublicClientprivate_market = position["categoryType"].to_s == "privateMarkets"price = position_price(websocket, isin, position["categoryType"])+ # Bond tickers are quoted in percent of par (e.g. 84.04 = 84.04%),+ # while netSize is the nominal amount in currency units. Convert the+ # ticker quote to a per-unit price so quantity * price yields the+ # market value. Fallback prices below are already per unit.+ price = bond_unit_price(price) if price.present? && position["categoryType"].to_s == "bonds"price = private_market_quotes[isin] if price.blank? && private_market_quotes.present?# Private-market funds have no exchange quote. Without a# privateMarketsPositions unit price, value them at the average buy-in# rather than zero. Other categories keep the unpriced warning.price = decimal_string(position["averageBuyIn"] || position["avgCost"]) if price.blank? && private_market+ # Non-numeric quotes ("N/A") and non-finite ones ("NaN", "Infinity")+ # would corrupt the balance; keep the position unvalued instead.+ price = nil unless finite_decimal(price)if price.present?prices[isin] = price@@ -812,6 +820,20 @@ class Provider::TradeRepublicClient[ positions, warnings ]end+ def bond_unit_price(percent_price)+ value = finite_decimal(percent_price)+ (value / 100).to_s("F") if value+ end++ def finite_decimal(value)+ return nil if value.blank?++ decimal = BigDecimal(value.to_s)+ decimal if decimal.finite?+ rescue ArgumentError+ nil+ end+def position_price(websocket, isin, category_type)home_exchange = home_instrument_exchange_id(websocket, isin)if home_exchange.present?diff --git a/app/models/trade_republic_item/importer.rb b/app/models/trade_republic_item/importer.rbindex 3be0088994..db74cabc6b 100644--- a/app/models/trade_republic_item/importer.rb+++ b/app/models/trade_republic_item/importer.rb@@ -453,7 +453,8 @@ class TradeRepublicItem::Importerdef parse_decimal(value)return nil if value.blank?- BigDecimal(value.to_s)+ decimal = BigDecimal(value.to_s)+ decimal if decimal.finite?rescue ArgumentErrornilenddiff --git a/db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices.rb b/db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices.rbnew file mode 100644index 0000000000..2f48e94c71--- /dev/null+++ b/db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices.rb@@ -0,0 +1,116 @@+# frozen_string_literal: true++# Trade Republic quotes bonds in percent of par (84.04 = 84.04%) while the+# position size is the nominal amount in currency units. Syncs before the+# percent-of-par fix stored that quote as the per-unit price, so every bond+# holding snapshot they wrote is valued 100x too high. A sync only rewrites+# today's snapshot, which leaves the bond's history inflated for good.+#+# Every snapshot that exists when this runs was written by the old code, so+# the only question is which rows are bonds. Bonds and interest products+# share the `interest_products` category, and only bonds were ever quoted in+# percent. A percent quote sits around 100x the per-unit average buy-in, a+# per-unit price around 1x, so a price at least 10x the buy-in tells them+# apart. That check also leaves an already corrected row alone, so running+# this twice is harmless.+#+# Bonds still held are found through the stored portfolio payload. Sold bonds+# are no longer in it, but the old code put every bond on the shared BOND+# listing on Hamburg (Trade Republic's LSX), so those rows are found by that+# security instead.+#+# The stored payload keeps the percent quote as well, and a sync that gets+# no quote reuses it, which would write a 100x snapshot again. Its bond+# prices are rescaled under the same check.+#+# Balances and the account's current value were computed from the inflated+# prices too; the item sync scheduled at the end refreshes them.+class RescaleTradeRepublicBondHoldingPrices < ActiveRecord::Migration[8.1]+ PERCENT_QUOTE_RATIO = 10+ SHARED_BOND_TICKER = "BOND"+ SHARED_BOND_MIC = "XHAM"++ def up+ bond_security_ids = Security.where(ticker: SHARED_BOND_TICKER, exchange_operating_mic: SHARED_BOND_MIC).pluck(:id)+ item_ids = []++ TradeRepublicAccount.where(kind: "portfolio").includes(:account_provider).find_each do |trade_republic_account|+ account = trade_republic_account.current_account+ provider_id = trade_republic_account.account_provider&.id+ next if account.nil? || provider_id.nil?++ snapshots = account.holdings+ .where(account_provider_id: provider_id)+ .where("external_id LIKE ?", "#{snapshot_prefix(trade_republic_account)}%")+ bond_positions = Array(trade_republic_account.raw_positions_payload).map { |position| position.to_h.with_indifferent_access }+ .select { |position| position[:isin].present? && position[:category].to_s == "interest_products" }++ rescaled = bond_positions.sum do |position|+ rescale_percent_quotes(+ snapshots.where("external_id LIKE ?", "#{snapshot_prefix(trade_republic_account, position[:isin])}%"),+ fallback_cost: parse_decimal(position[:average_cost])+ )+ end+ rescaled += rescale_percent_quotes(snapshots.where(security_id: bond_security_ids)) if bond_security_ids.any?+ payload_rescaled = rescale_payload_prices(trade_republic_account)+ next if rescaled.zero? && !payload_rescaled++ say "Rescaled #{rescaled} Trade Republic bond holdings on account #{account.id}"+ item_ids << trade_republic_account.trade_republic_item_id+ end++ schedule_syncs(item_ids.uniq)+ end++ # The old prices were wrong; restoring them would bring back the 100x error.+ def down+ raise ActiveRecord::IrreversibleMigration+ end++ private++ def snapshot_prefix(trade_republic_account, isin = nil)+ ActiveRecord::Base.sanitize_sql_like(+ "trade_republic_position_#{trade_republic_account.trade_republic_account_id}_#{isin.present? ? "#{isin}_" : ""}"+ )+ end++ def rescale_percent_quotes(holdings, fallback_cost: nil)+ holdings+ .where("price >= NULLIF(COALESCE(cost_basis, ?), 0) * ?", fallback_cost, PERCENT_QUOTE_RATIO)+ .update_all("price = price / 100, amount = amount / 100, updated_at = CURRENT_TIMESTAMP")+ end++ def rescale_payload_prices(trade_republic_account)+ changed = false+ payload = Array(trade_republic_account.raw_positions_payload).map do |position|+ next position unless position.is_a?(Hash) && position["category"].to_s == "interest_products"++ price = parse_decimal(position["price"])+ average_cost = parse_decimal(position["average_cost"])+ next position unless price && average_cost&.positive? && price >= average_cost * PERCENT_QUOTE_RATIO++ changed = true+ position.merge("price" => (price / 100).to_s("F"))+ end+ trade_republic_account.update_column(:raw_positions_payload, payload) if changed+ changed+ end++ def schedule_syncs(item_ids)+ TradeRepublicItem.syncable.where(id: item_ids).find_each do |item|+ item.sync_later+ rescue => e+ say "Could not schedule a sync for Trade Republic item #{item.id} (#{e.message}); it refreshes on its next sync"+ end+ end++ def parse_decimal(value)+ return nil if value.blank?++ decimal = BigDecimal(value.to_s)+ decimal if decimal.finite?+ rescue ArgumentError+ nil+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex ac9def769e..3b3752fa5a 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_10_05_120000) do+ActiveRecord::Schema[8.1].define(version: 2026_10_08_090000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"diff --git a/test/migrations/rescale_trade_republic_bond_holding_prices_migration_test.rb b/test/migrations/rescale_trade_republic_bond_holding_prices_migration_test.rbnew file mode 100644index 0000000000..283435fc42--- /dev/null+++ b/test/migrations/rescale_trade_republic_bond_holding_prices_migration_test.rb@@ -0,0 +1,124 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices")++class RescaleTradeRepublicBondHoldingPricesMigrationTest < ActiveSupport::TestCase+ BOND_ISIN = "IT0005377152"+ STOCK_ISIN = "US0378331005"+ INTEREST_ISIN = "LU0000000001"++ setup do+ @family = families(:dylan_family)+ @item = trade_republic_items(:configured_item)+ @item.trade_republic_accounts.destroy_all++ @tr_account = @item.trade_republic_accounts.create!(+ name: "Bond Test",+ trade_republic_account_id: "DEBOND1",+ currency: "EUR",+ raw_positions_payload: [+ { "isin" => BOND_ISIN, "category" => "interest_products", "quantity" => "2677.95", "average_cost" => "0.93", "price" => "84.04" },+ { "isin" => STOCK_ISIN, "category" => "brokerage", "quantity" => "10", "average_cost" => "1.50", "price" => "183.94" },+ { "isin" => INTEREST_ISIN, "category" => "interest_products", "quantity" => "5", "average_cost" => "100.00", "price" => "101.20" }+ ]+ )+ @account = @family.accounts.create!(+ name: "Trade Republic Bond Test", balance: 0, cash_balance: 0, currency: "EUR", accountable: Investment.new+ )+ @tr_account.ensure_account_provider!(@account)+ @tr_account.reload+ end++ test "rescales bond snapshots stored at percent of par" do+ older = create_snapshot(BOND_ISIN, 3.days.ago.to_date, qty: "2677.95", price: "83.10", cost_basis: "0.93")+ latest = create_snapshot(BOND_ISIN, Date.current, qty: "2677.95", price: "84.04", cost_basis: "0.93")++ run_migration++ assert_equal BigDecimal("0.831"), older.reload.price+ assert_equal BigDecimal("2225.3765"), older.amount+ assert_equal BigDecimal("0.8404"), latest.reload.price+ assert_equal BigDecimal("2250.5492"), latest.amount+ end++ test "falls back to the position's average buy-in when the snapshot has no cost basis" do+ holding = create_snapshot(BOND_ISIN, Date.current, qty: "2677.95", price: "84.04", cost_basis: nil)++ run_migration++ assert_equal BigDecimal("0.8404"), holding.reload.price+ end++ test "leaves per-unit prices, other categories and other providers alone" do+ corrected = create_snapshot(BOND_ISIN, Date.current, qty: "2677.95", price: "0.8404", cost_basis: "0.93")+ stock = create_snapshot(STOCK_ISIN, Date.current, qty: "10", price: "183.94", cost_basis: "1.50")+ interest = create_snapshot(INTEREST_ISIN, Date.current, qty: "5", price: "101.20", cost_basis: "100.00")+ calculated = create_snapshot(BOND_ISIN, 5.days.ago.to_date, qty: "2677.95", price: "84.04", cost_basis: "0.93",+ external_id: nil, account_provider_id: nil)++ run_migration++ assert_equal BigDecimal("0.8404"), corrected.reload.price+ assert_equal BigDecimal("183.94"), stock.reload.price+ assert_equal BigDecimal("101.2"), interest.reload.price+ assert_equal BigDecimal("84.04"), calculated.reload.price+ end++ test "rescales sold bonds kept on the shared BOND security" do+ shared_bond = Security.create!(ticker: "BOND", exchange_operating_mic: "XHAM", name: "Bond")+ sold = create_snapshot("DE0001102580", 30.days.ago.to_date, qty: "1000", price: "97.50", cost_basis: "0.96",+ security: shared_bond)+ sold_without_cost = create_snapshot("DE0001102598", 31.days.ago.to_date, qty: "1000", price: "97.50", cost_basis: nil,+ security: shared_bond)++ run_migration++ assert_equal BigDecimal("0.975"), sold.reload.price+ assert_equal BigDecimal("975"), sold.amount+ assert_equal BigDecimal("97.5"), sold_without_cost.reload.price+ end++ test "rescales percent quotes in the stored portfolio payload" do+ run_migration++ prices = @tr_account.reload.raw_positions_payload.to_h { |position| [ position["isin"], position["price"] ] }+ assert_equal "0.8404", prices[BOND_ISIN]+ assert_equal "183.94", prices[STOCK_ISIN]+ assert_equal "101.20", prices[INTEREST_ISIN]+ end++ test "schedules a sync only for items with rescaled holdings" do+ create_snapshot(BOND_ISIN, Date.current, qty: "2677.95", price: "84.04", cost_basis: "0.93")++ assert_difference -> { @item.syncs.count }, 1 do+ run_migration+ end+ assert_no_difference -> { @item.syncs.count } do+ run_migration+ end+ end++ private++ def create_snapshot(isin, date, qty:, price:, cost_basis:, **attributes)+ security = attributes.delete(:security) || Security.find_or_create_by!(ticker: isin) { |s| s.name = isin }+ @account.holdings.create!({+ security: security,+ date: date,+ qty: BigDecimal(qty),+ price: BigDecimal(price),+ amount: BigDecimal(qty) * BigDecimal(price),+ cost_basis: cost_basis && BigDecimal(cost_basis),+ currency: "EUR",+ external_id: "trade_republic_position_DEBOND1_#{isin}_#{date}",+ account_provider_id: @tr_account.account_provider.id+ }.merge(attributes))+ end++ def run_migration+ ActiveRecord::Migration.suppress_messages do+ RescaleTradeRepublicBondHoldingPrices.new.up+ end+ end+enddiff --git a/test/models/trade_republic_client_test.rb b/test/models/trade_republic_client_test.rbindex 62b59dedcc..9b35f1c1a2 100644--- a/test/models/trade_republic_client_test.rb+++ b/test/models/trade_republic_client_test.rb@@ -408,6 +408,91 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_equal "private_markets", positions.first["category"]end+ test "converts bond ticker prices from percent of par to a per-unit price" do+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|+ { "last" => { "price" => "84.04" } }+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "bonds", "positions" => [+ {+ "instrumentId" => "IT0005377152",+ "name" => "Italy 3.1% Mar 2040",+ "netSize" => "2677.95",+ "averageBuyIn" => "0.93"+ }+ ] }+ ]+ })++ assert_empty warnings+ assert_equal "0.8404", positions.first["price"]+ assert_equal "2677.95", positions.first["quantity"]+ assert_equal "interest_products", positions.first["category"]+ end++ test "keeps bond positions without valuation when the ticker price is non-numeric" do+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|+ { "last" => { "price" => "N/A" } }+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "bonds", "positions" => [+ { "instrumentId" => "IT0005377152", "name" => "Italy 3.1% Mar 2040", "netSize" => "2677.95" }+ ] }+ ]+ })++ assert_equal [ "price unavailable for IT0005377152; position kept without valuation" ], warnings+ assert_nil positions.first["price"]+ assert_equal "2677.95", positions.first["quantity"]+ end++ test "keeps positions without valuation when the ticker price is not finite" do+ [ [ "bonds", "NaN" ], [ "bonds", "Infinity" ], [ "stocksAndETFs", "-Infinity" ] ].each do |category, quote|+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|+ { "last" => { "price" => quote } }+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => category, "positions" => [+ { "instrumentId" => "IT0005377152", "name" => "Instrument", "netSize" => "2677.95" }+ ] }+ ]+ })++ assert_equal [ "price unavailable for IT0005377152; position kept without valuation" ], warnings, quote+ assert_nil positions.first["price"], quote+ assert_equal "2677.95", positions.first["quantity"], quote+ end+ end++ test "does not convert private markets fallback prices for bonds" do+ @client.define_singleton_method(:subscribe) do |_websocket, *_args, **_kwargs|+ raise Provider::TradeRepublicClient::ProviderUnavailable+ end+ @client.define_singleton_method(:private_markets_unit_prices) do |_websocket, _sec_acc_no|+ { "IT0005377152" => "0.8404" }+ end++ positions, warnings = @client.send(:normalize_positions, Object.new, {+ "categories" => [+ { "categoryType" => "bonds", "positions" => [+ { "instrumentId" => "IT0005377152", "name" => "Italy 3.1% Mar 2040", "netSize" => "2677.95" }+ ] },+ { "categoryType" => "privateMarkets", "positions" => [+ { "instrumentId" => "LU3176111881", "name" => "Private Equity", "netSize" => "1.01", "averageBuyIn" => "100.0" }+ ] }+ ]+ }, sec_acc_no: "0717713602")++ assert_empty warnings+ assert_equal "0.8404", positions.find { |p| p["isin"] == "IT0005377152" }["price"]+ end+test "prefers homeInstrumentExchange ticker before the hardcoded exchange list" dorequested = []@client.define_singleton_method(:subscribe) do |_websocket, *args, **kwargs|diff --git a/test/models/trade_republic_item_importer_test.rb b/test/models/trade_republic_item_importer_test.rbindex c25aff62f2..1cc61617a3 100644--- a/test/models/trade_republic_item_importer_test.rb+++ b/test/models/trade_republic_item_importer_test.rb@@ -265,6 +265,32 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCaseassert_equal "617.28", portfolio.raw_positions_payload.first["price"]end+ test "non-finite position prices preserve the last known portfolio balance" do+ portfolio = @item.trade_republic_accounts.create!(+ kind: "portfolio",+ name: "Existing portfolio",+ currency: "EUR",+ trade_republic_account_id: "DE5555",+ current_balance: BigDecimal("1234.56"),+ raw_positions_payload: [ { "isin" => "KEEP", "quantity" => "2", "price" => "617.28" } ]+ )++ provider = mock("trade_republic_provider")+ provider.expects(:sync).returns(client_result(+ "status" => "ok",+ "session_txt" => "# refreshed cookies",+ "account" => { "brokerage_account_id" => "DE5555", "currency" => "EUR" },+ "cash" => { "amount" => "0", "currency" => "EUR" },+ "positions" => [ { "isin" => "KEEP", "quantity" => "2", "price" => "NaN" } ],+ "events" => [],+ "warnings" => []+ ))++ TradeRepublicItem::Importer.new(@item, provider: provider).import++ assert_equal BigDecimal("1234.56"), portfolio.reload.current_balance+ end+test "cash success with timeline failure updates cash but preserves timeline and cursor" doportfolio = @item.trade_republic_accounts.create!(kind: "portfolio",