Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(trade-republic): read the exact share price from trade details (#4111)

Simone1e19a0365364
diff --git a/app/models/provider/trade_republic_client.rb b/app/models/provider/trade_republic_client.rb
index 4e8f714195..e7711d1d71 100644
--- a/app/models/provider/trade_republic_client.rb
+++ b/app/models/provider/trade_republic_client.rb
@@ -99,6 +99,9 @@ class Provider::TradeRepublicClient
"aktien entfernt", "shares removed", "aktien gesendet", "shares sent"
].freeze
TOTAL_TITLES = [ "gesamt", "total", "totaal", "gesamtbetrag" ].freeze
+ # The Overview row "0.626409 × €7.982" carries the exact share price that
+ # the rounded total is computed from.
+ TRANSACTION_TITLES = [ "transaction", "transaktion", "transactie" ].freeze
PRICE_TITLES = [
"share price", "aandelenkoers", "aktienkurs", "anteilskurs",
"execution price", "kurs"
@@ -132,6 +135,11 @@ class Provider::TradeRepublicClient
RETRY_INTERVAL = 1.day
RETRY_WINDOW = 30.days
PRICE_BACKFILL_ATTEMPTED_AT_KEY = "price_backfill_attempted_at"
+ # Marks a trade price read from the detail (a share price, quotation or
+ # Transaction row). A stored price without it was derived from the rounded
+ # total, so the price backfill fetches the detail again.
+ PRICE_SOURCE_KEY = "price_source"
+ PRICE_SOURCE_DETAIL = "detail"
SYMBOL_LOOKUP_ATTEMPTED_AT_KEY = "symbol_lookup_attempted_at"
SYMBOL_LOOKUP_FIRST_ATTEMPTED_AT_KEY = "symbol_lookup_first_attempted_at"
# Stored trades whose detail is still incomplete after a fetch; the backlog
@@ -540,13 +548,14 @@ class Provider::TradeRepublicClient
!(detail.is_a?(Hash) && detail.stringify_keys["isin"].present?)
end
- # Complete trades (isin + quantity) that still lack a share price — usually
- # stored before we parsed execution price / fees from timeline details.
+ # Complete trades (isin + quantity) without a price read from the detail:
+ # the price is missing, or was derived from the rounded total, usually
+ # because the trade was stored before its price rows were parsed.
# Trade Republic sometimes publishes the price late, so an unsuccessful
# attempt is retried at most once per RETRY_INTERVAL until the trade is
# RETRY_WINDOW old.
def trade_detail_needs_price_backfill?(event, now = Time.current)
- return false unless trade_detail_missing_price?(event)
+ return false unless trade_detail_price_unconfirmed?(event)
attempted_at = detail_time(event, PRICE_BACKFILL_ATTEMPTED_AT_KEY)
return true if attempted_at.nil?
@@ -579,13 +588,13 @@ class Provider::TradeRepublicClient
attempted_at <= now - RETRY_INTERVAL
end
- def trade_detail_missing_price?(event)
+ def trade_detail_price_unconfirmed?(event)
return false unless requires_trade_detail?(event)
return false unless Provider::TradeRepublicTimelineEvent.importable?(event)
return false unless trade_detail_complete?(event)
detail = (event["detail"] || event[:detail]).stringify_keys
- detail["price"].to_s.strip.blank?
+ detail["price"].to_s.strip.blank? || detail[PRICE_SOURCE_KEY].blank?
end
# Earlier syncs stored this listing on bond positions and trades.
@@ -1581,7 +1590,7 @@ class Provider::TradeRepublicClient
if kind == :backfill
result = fetched ? prefer_richer_event(item, fetched) : item
detail_backfill_count += 1 if detail_backfill_improved?(item, result)
- if self.class.trade_detail_missing_price?(result)
+ if self.class.trade_detail_price_unconfirmed?(result)
fetched = with_price_backfill_attempt(result)
elsif self.class.incomplete_trade_detail_event?(result) || self.class.dividend_detail_missing?(result)
fetched = with_detail_backfill_attempt(result)
@@ -1604,7 +1613,7 @@ class Provider::TradeRepublicClient
def detail_backfill_improved?(before, after)
return self.class.trade_detail_complete?(after) if self.class.incomplete_trade_detail_event?(before)
- self.class.trade_detail_missing_price?(before) && !self.class.trade_detail_missing_price?(after)
+ self.class.trade_detail_price_unconfirmed?(before) && !self.class.trade_detail_price_unconfirmed?(after)
end
def with_price_backfill_attempt(event) = with_attempt_marker(event, PRICE_BACKFILL_ATTEMPTED_AT_KEY)
@@ -1708,6 +1717,8 @@ class Provider::TradeRepublicClient
# par is 0.9267.
price ||= quotation / 100 if quotation
dividend_per_share = decimal_from_row(find_row(rows, DIVIDEND_PER_SHARE_TITLES))
+ price ||= transaction_unit_price(find_row(rows, TRANSACTION_TITLES))
+ price_source = PRICE_SOURCE_DETAIL if price
if price.nil? && quantity&.nonzero? && amount
# Provider cash totals embed costs: buy total = gross + fees/taxes,
# sell total = gross - fees/taxes. Recover share price accordingly.
@@ -1723,6 +1734,7 @@ class Provider::TradeRepublicClient
"name" => detail_name(item, raw),
"quantity" => decimal_string(quantity),
"price" => decimal_string(price),
+ PRICE_SOURCE_KEY => price_source,
"amount" => decimal_string(amount&.abs),
"currency" => currency_from_row(total) || currency_from_row(shares) || currency_from_row(price_row),
"fees" => decimal_string(fee_amount),
@@ -1747,8 +1759,24 @@ class Provider::TradeRepublicClient
def find_row(rows, titles) = rows.find { |row| titles.include?(row["title"].to_s.downcase.strip) }
+ # "0.626409 × €7.982"; Saveback writes "x". The displayValue holds the
+ # price alone. A bond's row quotes percent of par, not a unit price.
+ def transaction_unit_price(row)
+ return nil unless row
+
+ row_text = row.dig("detail", "text").to_s
+ text = row.dig("detail", "displayValue", "text").presence || row_text.split(/\s[×x]\s+/i, 2).second
+ return nil if text.blank? || text.include?("%") || row_text.include?("%")
+
+ price = decimal_from_text(text)
+ price if price&.positive?
+ end
+
def decimal_from_row(row)
- text = row&.dig("detail", "text") || row&.dig("detail", "value", "text")
+ decimal_from_text(row&.dig("detail", "text") || row&.dig("detail", "value", "text"))
+ end
+
+ def decimal_from_text(text)
return nil if text.blank?
normalized = text.to_s.gsub(/[^\d,.-]/, "")
diff --git a/app/models/trade_republic_item/importer.rb b/app/models/trade_republic_item/importer.rb
index c253117e0d..1e23913ebb 100644
--- a/app/models/trade_republic_item/importer.rb
+++ b/app/models/trade_republic_item/importer.rb
@@ -236,8 +236,8 @@ class TradeRepublicItem::Importer
portfolio_accounts.any? { |account| Array(account.raw_timeline_payload).blank? }
end
- # Incomplete trade-detail events, complete trades still missing a share
- # price (stored before execution price/fees were parsed) and dividends
+ # Incomplete trade-detail events, complete trades without a price read from
+ # the detail (missing, or derived from the rounded total) and dividends
# without their detail, in the client's backlog order.
def events_needing_detail_enrichment
portfolio = trade_republic_item.trade_republic_accounts.find_by(kind: "portfolio")
diff --git a/test/models/trade_republic_client_test.rb b/test/models/trade_republic_client_test.rb
index 793b3cdfb5..ebedf62912 100644
--- a/test/models/trade_republic_client_test.rb
+++ b/test/models/trade_republic_client_test.rb
@@ -1409,6 +1409,7 @@ class TradeRepublicClientTest < ActiveSupport::TestCase
}, item: { "title" => "Core S&P 500", "subtitle" => "Buy" })
assert_equal "511.96", detail["price"]
+ assert_nil detail["price_source"]
assert_equal "1.0", detail["fees"]
end
@@ -1432,17 +1433,130 @@ class TradeRepublicClientTest < ActiveSupport::TestCase
assert_equal "0.5", detail["taxes"]
end
- test "trade_detail_needs_price_backfill detects complete trades without price" do
+ test "normalize_event_detail reads the exact share price from the Transaction row" do
+ detail = @client.send(:normalize_event_detail, {
+ "sections" => [
+ { "title" => "Overview", "data" => [
+ {
+ "title" => "Transaction",
+ "detail" => { "text" => "1.25 × €8.123", "displayValue" => { "text" => "€8.123", "prefix" => "1.25 × " } }
+ },
+ { "title" => "Total", "detail" => { "text" => "€10.15" } }
+ ] }
+ ]
+ }, item: { "title" => "Core MSCI World", "subtitle" => "Savings plan executed" })
+
+ # The total is rounded to the cent: 10.15 / 1.25 would give 8.12.
+ assert_equal "1.25", detail["quantity"]
+ assert_equal "8.123", detail["price"]
+ assert_equal "detail", detail["price_source"]
+ assert_equal "10.15", detail["amount"]
+ end
+
+ test "normalize_event_detail reads a Saveback price from the Transaction text" do
+ detail = @client.send(:normalize_event_detail, {
+ "sections" => [
+ { "title" => "Overview", "data" => [
+ { "title" => "Transaction", "detail" => { "text" => "0.05 x €130.32" } },
+ { "title" => "Total", "detail" => { "text" => "+ €6.52" } }
+ ] }
+ ]
+ }, item: { "title" => "Core MSCI World", "subtitle" => "Saveback" })
+
+ assert_equal "0.05", detail["quantity"]
+ assert_equal "130.32", detail["price"]
+ end
+
+ test "normalize_event_detail does not read a percent quote as a share price" do
+ [
+ { "text" => "500 × 92.67 %" },
+ { "text" => "500 × 92.67 %", "displayValue" => { "text" => "92.67", "prefix" => "500 ×" } }
+ ].each do |row_detail|
+ detail = @client.send(:normalize_event_detail, {
+ "sections" => [
+ { "title" => "Overview", "data" => [
+ { "title" => "Transaction", "detail" => row_detail },
+ { "title" => "Total", "detail" => { "text" => "€463.35" } }
+ ] }
+ ]
+ }, item: { "title" => "Italy 3.1% Mar 2040", "subtitle" => "Buy" })
+
+ # The quote is skipped and the price falls back to total ÷ nominal, per
+ # unit of nominal like a bond's quotation.
+ assert_equal "500.0", detail["quantity"], row_detail.inspect
+ assert_equal "0.9267", detail["price"], row_detail.inspect
+ assert_nil detail["price_source"], row_detail.inspect
+ end
+ end
+
+ test "trade_detail_needs_price_backfill detects complete trades without a price read from the detail" do
+ trade = ->(detail) { { "category" => "orderExecution", "eventType" => "TRADING_TRADE_EXECUTED", "detail" => detail } }
+
assert Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(
- "category" => "orderExecution",
- "eventType" => "TRADING_TRADE_EXECUTED",
- "detail" => { "isin" => "IE00B5BMR087", "quantity" => "2", "amount" => "1024.92" }
+ trade.call("isin" => "IE00B5BMR087", "quantity" => "2", "amount" => "1024.92")
+ )
+ # Derived from the rounded total, or stored before the price rows were read.
+ assert Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(
+ trade.call("isin" => "IE00B5BMR087", "quantity" => "0.055", "price" => "182.54545454545454545454545454545")
)
refute Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(
+ trade.call("isin" => "IE00B5BMR087", "quantity" => "2", "price" => "511.96", "price_source" => "detail")
+ )
+ end
+
+ test "price backfill replaces a derived price with the Transaction row price" do
+ event = {
+ "id" => "trade-1",
+ "timestamp" => 200.days.ago.iso8601,
"category" => "orderExecution",
"eventType" => "TRADING_TRADE_EXECUTED",
- "detail" => { "isin" => "IE00B5BMR087", "quantity" => "2", "price" => "511.96" }
- )
+ "detail" => { "isin" => "US0378331005", "quantity" => "0.0428", "amount" => "10.11", "price" => "236.21495327102803738317757009346" }
+ }
+ @client.define_singleton_method(:subscribe) do |_websocket, **_payload|
+ { "sections" => [
+ { "title" => "Overview", "data" => [
+ {
+ "title" => "Transaction",
+ "detail" => { "text" => "0.0428 × € 236.15", "displayValue" => { "text" => "€ 236.15", "prefix" => "0.0428 ×" } }
+ },
+ { "title" => "Total", "detail" => { "text" => "€ 10.11" } }
+ ] },
+ { "data" => [ { "detail" => { "action" => { "payload" => { "instrumentId" => "US0378331005" } } } } ] }
+ ] }
+ end
+
+ events, _warnings, backfill_count = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ event ])
+
+ stored = events.find { |candidate| candidate["id"] == "trade-1" }
+ assert_equal 1, backfill_count
+ assert_equal "236.15", stored.dig("detail", "price")
+ assert_equal "detail", stored.dig("detail", "price_source")
+ refute Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(stored)
+ end
+
+ test "price backfill fetches an old derived price only once when the detail has no price row" do
+ event = {
+ "id" => "trade-1",
+ "timestamp" => 200.days.ago.iso8601,
+ "category" => "orderExecution",
+ "eventType" => "TRADING_TRADE_EXECUTED",
+ "detail" => { "isin" => "IE00B5BMR087", "quantity" => "2", "amount" => "1024.92", "price" => "512.46" }
+ }
+ @client.define_singleton_method(:subscribe) do |_websocket, **_payload|
+ { "sections" => [
+ { "title" => "Overview", "data" => [
+ { "title" => "Shares", "detail" => { "text" => "2" } },
+ { "title" => "Total", "detail" => { "text" => "€1,024.92" } }
+ ] }
+ ] }
+ end
+
+ events, _warnings, backfill_count = @client.send(:enrich_timeline_details, Object.new, [], enrich_events: [ event ])
+
+ stored = events.find { |candidate| candidate["id"] == "trade-1" }
+ assert_equal 0, backfill_count
+ assert stored.dig("detail", Provider::TradeRepublicClient::PRICE_BACKFILL_ATTEMPTED_AT_KEY).present?
+ refute Provider::TradeRepublicClient.trade_detail_needs_price_backfill?(stored, 2.days.from_now)
end
test "price backfill retries an unfixable trade at most once per day" do
diff --git a/test/models/trade_republic_item_importer_test.rb b/test/models/trade_republic_item_importer_test.rb
index 9a23479526..8aa2f5da73 100644
--- a/test/models/trade_republic_item_importer_test.rb
+++ b/test/models/trade_republic_item_importer_test.rb
@@ -753,7 +753,7 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCase
"timestamp" => "2026-08-01T10:00:00Z",
"eventType" => "SAVINGS_PLAN_INVOICE_CREATED",
"category" => "orderExecution",
- "detail" => { "amount" => -25.0, "isin" => "IE00B4L5Y983", "quantity" => "0.25", "price" => "100.00" }
+ "detail" => { "amount" => -25.0, "isin" => "IE00B4L5Y983", "quantity" => "0.25", "price" => "100.00", "price_source" => "detail" }
}
needs_price = {
"id" => "trade-needs-price",
@@ -1111,7 +1111,7 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCase
assert_equal %w[new-never-attempted needs-price old-early-attempt old-recent-attempt], enrich_ids
end
- test "events needing detail enrichment include complete trades missing share price" do
+ test "events needing detail enrichment include complete trades without a price read from the detail" do
@item.trade_republic_accounts.create!(
kind: "portfolio",
name: "Portfolio",
@@ -1140,6 +1140,20 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCase
"quantity" => "1",
"amount" => "500.00",
"price" => "500.00",
+ "price_source" => "detail",
+ "currency" => "EUR"
+ }
+ },
+ {
+ "id" => "derived-price",
+ "timestamp" => "2024-03-30T10:00:00Z",
+ "eventType" => "TRADING_TRADE_EXECUTED",
+ "category" => "orderExecution",
+ "detail" => {
+ "isin" => "IE00B5BMR087",
+ "quantity" => "0.055",
+ "amount" => "10.04",
+ "price" => "182.54545454545454545454545454545",
"currency" => "EUR"
}
}
@@ -1150,7 +1164,7 @@ class TradeRepublicItemImporterTest < ActiveSupport::TestCase
.send(:events_needing_detail_enrichment)
.map { |event| event["id"] || event[:id] }
- assert_equal [ "needs-price" ], enrich_ids
+ assert_equal [ "needs-price", "derived-price" ], enrich_ids
end
test "apply_instrument_symbols stamps merged timeline events that lacked a ticker" do