Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(trading212): book trades in the instrument currency (#4140)

stepanbeseda3bc7515a3fff
diff --git a/app/models/trading212_account/activities_processor.rb b/app/models/trading212_account/activities_processor.rb
index 4c2c8aa5ec..85ca04b2d3 100644
--- a/app/models/trading212_account/activities_processor.rb
+++ b/app/models/trading212_account/activities_processor.rb
@@ -4,7 +4,7 @@ class Trading212Account::ActivitiesProcessor
# T212 transaction types that map to cash flows
DEPOSIT_TYPE = "DEPOSIT".freeze
WITHDRAW_TYPE = "WITHDRAW".freeze
- INTEREST_TYPES = %w[INTEREST INTEREST_ON_FREE_CASH].freeze
+ INTEREST_TYPES = %w[INTEREST INTEREST_ON_FREE_CASH LENDING_INTEREST].freeze
FEE_TYPE = "FEE".freeze
def initialize(trading212_account)
@@ -54,10 +54,10 @@ class Trading212Account::ActivitiesProcessor
t212_ticker = instrument[:ticker].presence || order[:ticker].to_s
return false if t212_ticker.blank?
- filled_quantity = parse_decimal(fill[:quantity])
+ # T212 reports the fill quantity signed (negative for sells), so the
+ # direction comes from the order side alone.
+ filled_quantity = parse_decimal(fill[:quantity])&.abs
fill_price = parse_decimal(fill[:price])
- net_value = parse_decimal(fill.dig(:walletImpact, :netValue)) ||
- parse_decimal(order[:filledValue])
return false unless filled_quantity && fill_price
return false if filled_quantity.zero?
@@ -71,10 +71,11 @@ class Trading212Account::ActivitiesProcessor
is_buy = order[:side].to_s.upcase == "BUY"
activity_label = is_buy ? "Buy" : "Sell"
signed_quantity = is_buy ? filled_quantity : -filled_quantity
- amount = net_value ? net_value.abs : (fill_price * filled_quantity.abs)
+
+ instrument_ccy, fill_price = normalize_minor_units(instrument[:currency].presence || currency, fill_price)
+ amount, exchange_rate = trade_amount_and_rate(order, fill, instrument_ccy, fill_price * filled_quantity)
amount = is_buy ? amount : -amount
- instrument_ccy = instrument[:currency].presence || currency
date = parse_date(fill[:filledAt] || order[:createdAt]) || Date.current
order_id = (fill[:id] || order[:id]).to_s
external_id = "trading212_order_#{order_id}"
@@ -89,7 +90,8 @@ class Trading212Account::ActivitiesProcessor
date: date,
name: build_order_name(security.ticker, signed_quantity),
source: "trading212",
- activity_label: activity_label
+ activity_label: activity_label,
+ exchange_rate: exchange_rate
)
true
@@ -197,6 +199,23 @@ class Trading212Account::ActivitiesProcessor
false
end
+ # The trade is stored in the instrument's currency, like its price. T212
+ # reports what the fill moved in the wallet (walletImpact.netValue, fees
+ # included) in the account currency, so that figure becomes the exchange
+ # rate and the cash balance changes by exactly the amount T212 booked.
+ # Returns the unsigned amount and the rate into the account currency.
+ def trade_amount_and_rate(order, fill, instrument_ccy, gross_value)
+ wallet = (fill[:walletImpact] || {}).with_indifferent_access
+ net_value = (parse_decimal(wallet[:netValue]) || parse_decimal(order[:filledValue]))&.abs
+ wallet_ccy = wallet[:currency].presence || order[:currency].presence || currency
+
+ return [ gross_value, nil ] if net_value.nil? || net_value.zero?
+ return [ net_value, nil ] if wallet_ccy == instrument_ccy
+ return [ gross_value, nil ] if wallet_ccy != currency || gross_value.zero?
+
+ [ gross_value, (net_value / gross_value).to_f ]
+ end
+
def classify_transaction(type, amount)
case type
when DEPOSIT_TYPE
diff --git a/app/models/trading212_account/data_helpers.rb b/app/models/trading212_account/data_helpers.rb
index 18b60d0491..75fc489116 100644
--- a/app/models/trading212_account/data_helpers.rb
+++ b/app/models/trading212_account/data_helpers.rb
@@ -33,6 +33,19 @@ module Trading212Account::DataHelpers
nil
end
+ # T212 quotes London listings in pence (GBX). Prices and amounts are
+ # stored in the major unit, as the price providers do.
+ MINOR_UNIT_CURRENCIES = {
+ "GBX" => { currency: "GBP", multiplier: BigDecimal("0.01") }
+ }.freeze
+
+ def normalize_minor_units(currency_code, *amounts)
+ conversion = MINOR_UNIT_CURRENCIES[currency_code.to_s.upcase]
+ return [ currency_code, *amounts ] unless conversion
+
+ [ conversion[:currency], *amounts.map { |amount| amount && amount * conversion[:multiplier] } ]
+ end
+
# T212 tickers look like "AAPL_US_EQ". Derive a standard ticker by taking
# the first segment, which is the instrument symbol on its primary exchange.
def standard_ticker(t212_ticker)
diff --git a/app/models/trading212_account/holdings_processor.rb b/app/models/trading212_account/holdings_processor.rb
index 6e020f24bc..db94b22eb8 100644
--- a/app/models/trading212_account/holdings_processor.rb
+++ b/app/models/trading212_account/holdings_processor.rb
@@ -44,6 +44,10 @@ class Trading212Account::HoldingsProcessor
price = parse_decimal(position[:currentPrice])
return unless quantity && price && quantity > 0
+ position_ccy, price, cost_basis = normalize_minor_units(
+ position_ccy, price, parse_decimal(position[:averagePricePaid])
+ )
+
amount = quantity * price
date = Date.current
@@ -56,7 +60,7 @@ class Trading212Account::HoldingsProcessor
currency: position_ccy,
date: date,
price: price,
- cost_basis: parse_decimal(position[:averagePricePaid]),
+ cost_basis: cost_basis,
external_id: external_id,
source: "trading212",
account_provider_id: @trading212_account.account_provider&.id,
diff --git a/test/models/trading212_activities_processor_test.rb b/test/models/trading212_activities_processor_test.rb
index ee1c538229..8a88e4f3a0 100644
--- a/test/models/trading212_activities_processor_test.rb
+++ b/test/models/trading212_activities_processor_test.rb
@@ -92,6 +92,139 @@ class Trading212ActivitiesProcessorTest < ActiveSupport::TestCase
assert entry.entryable.qty.negative?
end
+ test "stores a foreign-currency fill in the instrument currency with the wallet rate" do
+ @account.update!(currency: "CZK")
+ @trading212_account.update!(
+ currency: "CZK",
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => 58204391732,
+ "status" => "FILLED",
+ "side" => "BUY",
+ "currency" => "CZK",
+ "filledValue" => 3000.0,
+ "instrument" => { "ticker" => "NET_US_EQ", "name" => "Cloudflare", "currency" => "USD" }
+ },
+ "fill" => {
+ "id" => 58209573886,
+ "quantity" => 0.4,
+ "price" => 350.0,
+ "filledAt" => "2026-10-01T13:30:03.000Z",
+ "walletImpact" => { "currency" => "CZK", "netValue" => 3000.0, "fxRate" => 0.04612801 }
+ }
+ }
+ ]
+ )
+
+ Trading212Account::ActivitiesProcessor.new(@trading212_account).process
+
+ entry = @account.entries.find_by(external_id: "trading212_order_58209573886")
+ assert_equal "USD", entry.currency
+ assert_equal BigDecimal("140"), entry.amount
+ assert_equal "USD", entry.entryable.currency
+ assert_equal BigDecimal("350"), entry.entryable.price
+ # 140 USD at the stored rate is the 3000 CZK the wallet was charged
+ assert_in_delta 3000, entry.amount * entry.entryable.exchange_rate, 0.001
+ end
+
+ test "treats a negative fill quantity on a sell order as a sale" do
+ @account.update!(currency: "CZK")
+ @trading212_account.update!(
+ currency: "CZK",
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => 49502407922,
+ "status" => "FILLED",
+ "side" => "SELL",
+ "currency" => "CZK",
+ "quantity" => -2.0,
+ "instrument" => { "ticker" => "IGLDd_EQ", "name" => "iShares Physical Gold", "currency" => "EUR" }
+ },
+ "fill" => {
+ "id" => 49504676344,
+ "quantity" => -2.0,
+ "price" => 80.0,
+ "filledAt" => "2026-04-13T10:17:54.000Z",
+ "walletImpact" => { "currency" => "CZK", "netValue" => 3900.0, "fxRate" => 0.041 }
+ }
+ }
+ ]
+ )
+
+ Trading212Account::ActivitiesProcessor.new(@trading212_account).process
+
+ entry = @account.entries.find_by(external_id: "trading212_order_49504676344")
+ assert_equal "Sell", entry.entryable.investment_activity_label
+ assert_equal BigDecimal("-2"), entry.entryable.qty
+ assert_equal BigDecimal("-160"), entry.amount
+ assert_equal "Sell 2.0 shares of IGLDD", entry.name
+ assert_in_delta(-3900, entry.amount * entry.entryable.exchange_rate, 0.001)
+ end
+
+ test "stores a pence-quoted fill in pounds" do
+ @account.update!(currency: "CZK")
+ @trading212_account.update!(
+ currency: "CZK",
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => "order_gbx",
+ "status" => "FILLED",
+ "side" => "BUY",
+ "currency" => "CZK",
+ "instrument" => { "ticker" => "SGLNl_EQ", "name" => "iShares Physical Gold", "currency" => "GBX" }
+ },
+ "fill" => {
+ "id" => "fill_gbx",
+ "quantity" => 0.5,
+ "price" => 5000.0,
+ "filledAt" => "2026-03-10T15:05:50.000Z",
+ "walletImpact" => { "currency" => "CZK", "netValue" => 750.0, "fxRate" => 3.5469545 }
+ }
+ }
+ ]
+ )
+
+ Trading212Account::ActivitiesProcessor.new(@trading212_account).process
+
+ entry = @account.entries.find_by(external_id: "trading212_order_fill_gbx")
+ assert_equal "GBP", entry.currency
+ assert_equal BigDecimal("25"), entry.amount
+ assert_equal BigDecimal("50"), entry.entryable.price
+ assert_in_delta 750, entry.amount * entry.entryable.exchange_rate, 0.001
+ end
+
+ test "books the wallet amount without a rate when the instrument is in the account currency" do
+ @trading212_account.update!(
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => "order_same_ccy",
+ "status" => "FILLED",
+ "side" => "BUY",
+ "currency" => "USD",
+ "instrument" => { "ticker" => "AAPL_US_EQ", "name" => "Apple", "currency" => "USD" }
+ },
+ "fill" => {
+ "id" => "fill_same_ccy",
+ "quantity" => 10,
+ "price" => 175.0,
+ "filledAt" => "2024-06-15T10:30:00Z",
+ "walletImpact" => { "currency" => "USD", "netValue" => 1751.5 }
+ }
+ }
+ ]
+ )
+
+ Trading212Account::ActivitiesProcessor.new(@trading212_account).process
+
+ entry = @account.entries.find_by(external_id: "trading212_order_fill_same_ccy")
+ assert_equal BigDecimal("1751.5"), entry.amount
+ assert_nil entry.entryable.exchange_rate
+ end
+
test "skips non-filled orders" do
@trading212_account.update!(
raw_orders_payload: [
@@ -297,6 +430,26 @@ class Trading212ActivitiesProcessorTest < ActiveSupport::TestCase
assert entry.amount.negative?
end
+ test "processes LENDING_INTEREST as Interest" do
+ @trading212_account.update!(
+ raw_transactions_payload: [
+ {
+ "reference" => "txn_lending",
+ "type" => "LENDING_INTEREST",
+ "amount" => "0.04",
+ "dateTime" => "2026-10-06T03:58:08.084Z"
+ }
+ ]
+ )
+
+ result = Trading212Account::ActivitiesProcessor.new(@trading212_account).process
+
+ assert_equal 1, result[:transactions]
+ entry = @account.entries.find_by(external_id: "trading212_transaction_txn_lending")
+ assert_equal "Interest", entry.entryable.investment_activity_label
+ assert entry.amount.negative?
+ end
+
test "processes FEE as Fee" do
@trading212_account.update!(
raw_transactions_payload: [
diff --git a/test/models/trading212_holdings_processor_test.rb b/test/models/trading212_holdings_processor_test.rb
index 8ab047b2ca..273ac0a750 100644
--- a/test/models/trading212_holdings_processor_test.rb
+++ b/test/models/trading212_holdings_processor_test.rb
@@ -74,6 +74,31 @@ class Trading212HoldingsProcessorTest < ActiveSupport::TestCase
assert_equal "provider", holding.cost_basis_source
end
+ test "processor stores a pence-quoted position in pounds" do
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ "instrument" => {
+ "ticker" => "SGLNl_EQ",
+ "name" => "iShares Physical Gold",
+ "currency" => "GBX"
+ },
+ "quantity" => "4",
+ "currentPrice" => "6141.0",
+ "averagePricePaid" => "5000.0"
+ }
+ ]
+ )
+
+ Trading212Account::HoldingsProcessor.new(@trading212_account).process
+
+ holding = @account.holdings.find_by(security: Security.find_by(ticker: "SGLNL"))
+ assert_equal "GBP", holding.currency
+ assert_equal BigDecimal("61.41"), holding.price
+ assert_equal BigDecimal("245.64"), holding.amount
+ assert_equal BigDecimal("50"), holding.cost_basis
+ end
+
test "processor skips position with blank ticker" do
@trading212_account.update!(
raw_positions_payload: [