The personal finance app for everyone (by everyone)
Ruby
fix(ibkr): import crypto and commodity positions, anchor the balance on NAV (#4714)
Ferran Celades4f8ad4da1ebb
diff --git a/app/models/ibkr_account/holdings_processor.rb b/app/models/ibkr_account/holdings_processor.rbindex 8d5ebc704a..0409cf0929 100644--- a/app/models/ibkr_account/holdings_processor.rb+++ b/app/models/ibkr_account/holdings_processor.rb@@ -1,6 +1,30 @@class IbkrAccount::HoldingsProcessorinclude IbkrAccount::DataHelpers+ # Categories this importer accepts. STK resolves to an exchange-listed+ # security by symbol. CRYPTO (custodied at Paxos) and CMDTY (spot metals)+ # have no listing to resolve against and carry no securityID, so they are+ # tracked under a namespace of their own.+ UNLISTED_ASSET_CATEGORIES = %w[CRYPTO CMDTY].freeze+ SUPPORTED_ASSET_CATEGORIES = (%w[STK] + UNLISTED_ASSET_CATEGORIES).freeze++ # "CRYPTO:" is the ticker namespace every crypto integration here shares, so+ # a coin lives in one Security row across providers. The prefix is also what+ # keeps the position off an exchange-listed stock of the same symbol, which a+ # bare-symbol lookup would match and then price. Spot metals take the+ # symmetric "CMDTY:".+ TICKER_PREFIXES = { "CRYPTO" => "CRYPTO:", "CMDTY" => "CMDTY:" }.freeze++ # Crypto under this namespace is quotable, and is bound to the provider that+ # quotes it the way Onchain::SecurityResolver binds it, so a row this importer+ # creates first still gets price history for every other integration.+ CRYPTO_PRICE_PROVIDER = "binance_public"++ # Spot metals are quoted by nobody: the statement's mark price is the only+ # price they have. Offline keeps the daily price fetch off them, and the+ # reason says which flow decided that.+ COMMODITY_OFFLINE_REASON = "ibkr_commodity"+def initialize(ibkr_account)@ibkr_account = ibkr_accountend@@ -28,41 +52,44 @@ class IbkrAccount::HoldingsProcessordata = position.with_indifferent_accessnext unless supported_position?(data)- # conid is guaranteed present by supported_position?, so no fallbacks neededcurrency = extract_currency(data, fallback: @ibkr_account.currency)report_date = parse_date(data[:report_date]) || @ibkr_account.report_date || Date.current- key = [ data[:conid], currency, report_date ]+ key = [ position_key(data), currency, report_date ]groups[key] ||= []groups[key] << dataendend+ # conid, guaranteed present by supported_position?, identifies a listed+ # position. An unlisted one groups by the ticker it resolves to: IBKR can+ # report one asset under more than one conid, and a holding is keyed on+ # (security, date, currency), so a second group for the same security would+ # overwrite the first instead of summing with it.+ def position_key(row)+ unlisted?(row) ? unlisted_ticker(row) : row[:conid]+ end+def process_group(rows, report_date)sample = rows.first- security = resolve_security(sample)- return unless security-- price = parse_decimal(sample[:mark_price])- # quantity and cost_basis are derived from the same set of valid lots so- # they are always consistent — a lot with an unparseable cost_basis_price- # is excluded from both counts rather than inflating qty while shrinking basis.aggregate = valid_lots(rows)- return unless price && aggregate+ return unless aggregate++ # Resolved after the lots, so a group with nothing importable in it does+ # not leave a security behind with no holding on it.+ security = resolve_position_security(sample)+ return unless security- quantity = aggregate[:quantity]- cost_basis = aggregate[:cost_basis]- amount = quantity * pricecurrency = extract_currency(sample, fallback: @ibkr_account.currency)- external_id = [ "ibkr", @ibkr_account.ibkr_account_id, sample[:conid], report_date, currency ].join("_")+ external_id = [ "ibkr", @ibkr_account.ibkr_account_id, position_key(sample), report_date, currency ].join("_")import_adapter.import_holding(security: security,- quantity: quantity,- amount: amount,+ quantity: aggregate[:quantity],+ amount: aggregate[:amount],currency: currency,date: report_date,- price: price,- cost_basis: cost_basis,+ price: aggregate[:price],+ cost_basis: aggregate[:cost_basis],external_id: external_id,source: "ibkr",account_provider_id: @ibkr_account.account_provider&.id,@@ -70,41 +97,99 @@ class IbkrAccount::HoldingsProcessor)end- # Aggregates only the lots that have both a parseable position and cost_basis_price.- # Returns { quantity:, cost_basis: } so the caller uses a consistent lot set for- # both values — a lot skipped here is excluded from quantity too, preventing the- # case where qty covers more shares than the cost basis was computed from.+ # Aggregates only the lots carrying a parseable position, cost_basis_price and+ # mark_price. Every returned figure comes from that one lot set, so a lot+ # skipped here is out of the quantity as well — otherwise qty would cover+ # more shares than the cost basis and the value were computed from.+ #+ # Each lot is valued at its own mark: a group holds every lot of one asset,+ # which for an unlisted position can span conids that IBKR marks separately.+ # price is the weighted average that amount and quantity imply.def valid_lots(rows)total_quantity = BigDecimal("0")total_cost = BigDecimal("0")+ total_value = BigDecimal("0")rows.each do |row|row_quantity = parse_decimal(row[:position])row_cost_basis = parse_decimal(row[:cost_basis_price])+ row_price = parse_decimal(row[:mark_price])- unless row_quantity && row_cost_basis+ unless row_quantity && row_cost_basis && row_priceRails.logger.warn(- "IbkrAccount::HoldingsProcessor - Skipping lot with missing position or cost_basis_price " \- "for conid=#{row[:conid].inspect}"+ "IbkrAccount::HoldingsProcessor - Skipping lot with missing position, cost_basis_price " \+ "or mark_price for conid=#{row[:conid].inspect}")nextendtotal_quantity += row_quantity.abstotal_cost += row_quantity.abs * row_cost_basis+ total_value += row_quantity.abs * row_priceendreturn nil if total_quantity.zero?- { quantity: total_quantity, cost_basis: total_cost / total_quantity }+ {+ quantity: total_quantity,+ cost_basis: total_cost / total_quantity,+ amount: total_value,+ price: total_value / total_quantity+ }+ end++ def resolve_position_security(row)+ return resolve_security(row) unless unlisted?(row)++ ticker = unlisted_ticker(row)+ return nil if ticker.blank?++ Security.find_by(ticker: ticker) || create_unlisted_security(ticker, row)+ end++ def unlisted?(row)+ UNLISTED_ASSET_CATEGORIES.include?(row[:asset_category].to_s)+ end++ def unlisted_ticker(row)+ symbol = row[:symbol].to_s.strip.upcase+ return nil if symbol.blank?++ prefix = TICKER_PREFIXES[row[:asset_category].to_s]+ symbol.start_with?(prefix) ? symbol : "#{prefix}#{symbol}"+ end++ # Securities are global, so an existing row is reused exactly as it stands:+ # its price provider and its offline state belong to whichever flow set+ # them. The savepoint is what keeps a lost create race from aborting the+ # surrounding transaction and taking the rest of the import with it.+ def create_unlisted_security(ticker, row)+ Security.transaction(requires_new: true) do+ Security.create!(+ ticker: ticker,+ name: row[:description].presence || ticker,+ **pricing_attributes(row)+ )+ end+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique+ Security.find_by(ticker: ticker)+ end++ def pricing_attributes(row)+ return { offline: true, offline_reason: COMMODITY_OFFLINE_REASON } unless row[:asset_category].to_s == "CRYPTO"++ {+ exchange_operating_mic: Provider::BinancePublic::BINANCE_MIC,+ price_provider: CRYPTO_PRICE_PROVIDER+ }enddef supported_position?(row)- row[:asset_category].to_s == "STK" &&+ SUPPORTED_ASSET_CATEGORIES.include?(row[:asset_category].to_s) &&row[:side].to_s == "Long" &&row[:conid].present? &&- row[:security_id].present? &&- row[:security_id_type].present? &&+ # conid identifies an unlisted position; IBKR sends it no securityID.+ (unlisted?(row) || (row[:security_id].present? && row[:security_id_type].present?)) &&row[:symbol].present? &&row[:currency].present? &&row[:fx_rate_to_base].present? &&diff --git a/app/models/ibkr_item/report_parser.rb b/app/models/ibkr_item/report_parser.rbindex edab81812b..133f7e9989 100644--- a/app/models/ibkr_item/report_parser.rb+++ b/app/models/ibkr_item/report_parser.rb@@ -70,7 +70,8 @@ class IbkrItem::ReportParsername: account_id,currency: currency,cash_balance: extract_cash_balance(cash_report, currency),- current_balance: extract_total_balance(position_values, cash_report, currency),+ current_balance: extract_nav_balance(equity_summary_in_base, currency, report_date) ||+ extract_total_balance(position_values, cash_report, currency),report_date: report_date,statement: statement_data,cash_report: cash_report,@@ -137,6 +138,45 @@ class IbkrItem::ReportParserparse_decimal(row&.fetch("end_of_period_value", nil)) || BigDecimal("0")end+ # IBKR's own net asset value, which covers every asset class the account+ # holds. ChangeInPositionValues is reported per asset category and omits+ # crypto and spot metals, so position values plus cash is the fallback only+ # for a Flex Query configured without an equity summary. This is also the+ # section IbkrAccount::HistoricalBalancesSync reads, which keeps the+ # current balance and the balance history on one figure.+ #+ # Only a row on or before report_date is eligible, so the balance is never a+ # value the account reached after the date IbkrAccount::Processor anchors it+ # on. report_date normally has its own row; when it does not, the most recent+ # one before it is carried forward, as HistoricalBalancesSync#fill_gaps+ # carries a total across the days IBKR does not report. A statement whose+ # equity summary begins after its positions has no NAV that can stand for+ # that date, and takes the fallback.+ #+ # Rows are filtered as HistoricalBalancesSync filters them: BASE_SUMMARY+ # aggregates across currencies instead of stating a day's value, and a row+ # with no currency at all is implicitly in base currency.+ def extract_nav_balance(equity_rows, account_currency, report_date)+ totals_by_date = equity_rows.each_with_object({}) do |row, totals|+ next unless nav_row_in_currency?(row, account_currency)++ date = parse_date(row["report_date"])+ total = parse_decimal(row["total"])+ next unless date && total++ totals[date] = total+ end++ totals_by_date.select { |date, _| date <= report_date }.max_by(&:first)&.last+ end++ def nav_row_in_currency?(row, account_currency)+ currency = row["currency"].presence&.upcase+ return false if currency == "BASE_SUMMARY"++ currency.blank? || currency == account_currency+ end+def extract_total_balance(position_values, cash_rows, account_currency)extract_current_balance(position_values, account_currency) + extract_cash_balance(cash_rows, account_currency)enddiff --git a/test/models/ibkr_account/holdings_processor_test.rb b/test/models/ibkr_account/holdings_processor_test.rbnew file mode 100644index 0000000000..189ef6aae9--- /dev/null+++ b/test/models/ibkr_account/holdings_processor_test.rb@@ -0,0 +1,219 @@+require "test_helper"++class IbkrAccount::HoldingsProcessorTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ @account = @family.accounts.create!(+ name: "IBKR Brokerage",+ balance: 0,+ cash_balance: 0,+ currency: "USD",+ accountable: Investment.new(subtype: "brokerage")+ )+ @ibkr_account = @family.ibkr_items.create!(+ name: "IBKR",+ query_id: "QUERY123",+ token: "TOKEN123"+ ).ibkr_accounts.create!(+ name: "Main",+ ibkr_account_id: "U1234567",+ currency: "USD",+ report_date: Date.new(2026, 5, 8)+ )+ @ibkr_account.ensure_account_provider!(@account)+ end++ test "imports crypto and commodity positions alongside stocks" do+ @ibkr_account.update!(raw_holdings_payload: [ stock_position, crypto_position, metal_position ])++ IbkrAccount::HoldingsProcessor.new(@ibkr_account).process++ assert_equal %w[AAPL CMDTY:USGOLD CRYPTO:BTC], holdings_by_ticker.keys.sort++ bitcoin = holdings_by_ticker["CRYPTO:BTC"]+ assert_equal 0.5, bitcoin.qty+ assert_equal 60_000, bitcoin.price+ assert_equal 30_000, bitcoin.amount++ gold = holdings_by_ticker["CMDTY:USGOLD"]+ assert_equal 2, gold.qty+ assert_equal 4_000, gold.amount+ end++ # The crypto namespace is quotable, so the row stays eligible for the price+ # history every other integration sharing it expects. A spot metal is quoted+ # by nobody, and offline keeps the daily fetch off it.+ test "crypto is bound to the crypto price provider and a commodity is offline" do+ @ibkr_account.update!(raw_holdings_payload: [ crypto_position, metal_position ])++ IbkrAccount::HoldingsProcessor.new(@ibkr_account).process++ bitcoin = Security.find_by!(ticker: "CRYPTO:BTC")+ assert_not_predicate bitcoin, :offline?+ assert_equal "binance_public", bitcoin.price_provider+ assert_equal Provider::BinancePublic::BINANCE_MIC, bitcoin.exchange_operating_mic+ assert_equal "BITCOIN", bitcoin.name++ gold = Security.find_by!(ticker: "CMDTY:USGOLD")+ assert_predicate gold, :offline?+ assert_equal "ibkr_commodity", gold.offline_reason+ assert_equal "Gold (London Fix) USD/oz", gold.name+ end++ # Securities are global: whichever flow created the row chose its pricing.+ test "an unlisted position reuses an existing security as it stands" do+ existing = Security.create!(+ ticker: "CRYPTO:BTC",+ name: "Bitcoin",+ exchange_operating_mic: "XCBS",+ price_provider: "twelve_data"+ )+ @ibkr_account.update!(raw_holdings_payload: [ crypto_position ])++ assert_no_difference -> { Security.count } do+ IbkrAccount::HoldingsProcessor.new(@ibkr_account).process+ end++ assert_equal existing, holdings_by_ticker["CRYPTO:BTC"].security+ existing.reload+ assert_equal "twelve_data", existing.price_provider+ assert_equal "XCBS", existing.exchange_operating_mic+ end++ # A holding is keyed on (security, date, currency), so two groups for one+ # security would overwrite each other rather than sum.+ test "one symbol reported under two conids sums into a single holding" do+ @ibkr_account.update!(raw_holdings_payload: [+ crypto_position,+ crypto_position.merge("conid" => "641027225", "position" => "1.5", "cost_basis_price" => "50000.00")+ ])++ bitcoin = process_and_find("CRYPTO:BTC")++ assert_equal 1, @account.holdings.count+ assert_equal 2, bitcoin.qty+ assert_equal 120_000, bitcoin.amount+ end++ # A group holds every lot of one asset, and IBKR marks each conid on its own.+ test "each lot is valued at its own mark price" do+ @ibkr_account.update!(raw_holdings_payload: [+ crypto_position,+ crypto_position.merge("conid" => "641027225", "position" => "1.5", "mark_price" => "40000.00")+ ])++ bitcoin = process_and_find("CRYPTO:BTC")++ assert_equal 2, bitcoin.qty+ assert_equal 90_000, bitcoin.amount, "0.5 at 60,000 plus 1.5 at 40,000"+ assert_equal 45_000, bitcoin.price, "the weighted average the amount implies"+ end++ # supported_position? only asks that mark_price be present, and a group's+ # other lots carry it past that check, so an unparseable one would otherwise+ # add its quantity to the group at no value.+ test "a lot with an unusable mark price does not inflate its group's quantity" do+ @ibkr_account.update!(raw_holdings_payload: [+ crypto_position,+ crypto_position.merge("mark_price" => "N/A", "position" => "9"),+ crypto_position.merge("mark_price" => "", "position" => "7")+ ])++ bitcoin = process_and_find("CRYPTO:BTC")++ assert_equal 0.5, bitcoin.qty+ assert_equal 30_000, bitcoin.amount+ end++ # A group that cannot be imported must not leave a security behind with no+ # holding on it.+ test "an unparseable mark price creates no security" do+ @ibkr_account.update!(raw_holdings_payload: [ crypto_position.merge("mark_price" => "N/A") ])++ assert_no_difference -> { Security.count } do+ IbkrAccount::HoldingsProcessor.new(@ibkr_account).process+ end++ assert_empty @account.holdings+ end++ # Only the securityID requirement is lifted for an unlisted position.+ test "unsupported categories and incomplete rows are still skipped" do+ @ibkr_account.update!(raw_holdings_payload: [+ crypto_position.merge("asset_category" => "OPT"),+ crypto_position.merge("symbol" => "ETH", "conid" => "99", "side" => "Short"),+ crypto_position.merge("symbol" => "SOL", "conid" => "98", "mark_price" => "")+ ])++ IbkrAccount::HoldingsProcessor.new(@ibkr_account).process++ assert_empty @account.holdings+ end++ private++ def process_and_find(ticker)+ IbkrAccount::HoldingsProcessor.new(@ibkr_account).process+ holdings_by_ticker.fetch(ticker)+ end++ def holdings_by_ticker+ @account.holdings.includes(:security).index_by { |holding| holding.security.ticker }+ end++ def stock_position+ {+ "asset_category" => "STK",+ "conid" => "265598",+ "security_id" => "US0378331005",+ "security_id_type" => "ISIN",+ "symbol" => "AAPL",+ "description" => "APPLE INC",+ "position" => "10",+ "mark_price" => "150.00",+ "currency" => "USD",+ "fx_rate_to_base" => "1",+ "cost_basis_price" => "125.50",+ "report_date" => "2026-05-08",+ "side" => "Long"+ }+ end++ # IBKR sends securityID and securityIDType through empty for both of these.+ # Rows as reported in #3946.+ def crypto_position+ {+ "asset_category" => "CRYPTO",+ "conid" => "530091182",+ "security_id" => "",+ "security_id_type" => "",+ "symbol" => "BTC",+ "description" => "BITCOIN",+ "position" => "0.5",+ "mark_price" => "60000.00",+ "currency" => "USD",+ "fx_rate_to_base" => "1",+ "cost_basis_price" => "40000.00",+ "report_date" => "2026-05-08",+ "side" => "Long"+ }+ end++ def metal_position+ {+ "asset_category" => "CMDTY",+ "conid" => "474636065",+ "security_id" => "",+ "security_id_type" => "",+ "symbol" => "USGOLD",+ "description" => "Gold (London Fix) USD/oz",+ "position" => "2",+ "mark_price" => "2000.00",+ "currency" => "USD",+ "fx_rate_to_base" => "1",+ "cost_basis_price" => "1800.00",+ "report_date" => "2026-05-08",+ "side" => "Long"+ }+ end+enddiff --git a/test/models/ibkr_item_report_parser_test.rb b/test/models/ibkr_item_report_parser_test.rbindex 7a73937fb6..45fa9cb759 100644--- a/test/models/ibkr_item_report_parser_test.rb+++ b/test/models/ibkr_item_report_parser_test.rb@@ -26,6 +26,46 @@ class IbkrItemReportParserTest < ActiveSupport::TestCaseassert_equal 1, second_account[:equity_summary_in_base].sizeend+ # ChangeInPositionValues covers the listed positions only, so a statement+ # that also holds crypto or spot metals totals short of IBKR's own NAV.+ test "reads the current balance from the latest NAV row" do+ parsed = IbkrItem::ReportParser.new(nav_statement_xml).parse+ account = parsed[:accounts].first++ assert_equal BigDecimal("1500.00"), account[:current_balance]+ assert_equal BigDecimal("200.00"), account[:cash_balance]+ end++ # The balance is anchored on the statement's report date, so the figure has+ # to be the NAV of that date rather than of whichever row is newest.+ test "prefers the NAV row dated with the statement's report date" do+ xml = nav_statement_xml(open_positions: open_positions_on("2026-05-07"))++ account = IbkrItem::ReportParser.new(xml).parse[:accounts].first++ assert_equal Date.new(2026, 5, 7), account[:report_date]+ assert_equal BigDecimal("1400.00"), account[:current_balance]+ end++ # A NAV dated after report_date is a value the account did not hold on that+ # date, and the balance is written to report_date.+ test "ignores a NAV row dated after the statement's report date" do+ xml = nav_statement_xml(open_positions: open_positions_on("2026-05-06"))++ account = IbkrItem::ReportParser.new(xml).parse[:accounts].first++ assert_equal Date.new(2026, 5, 6), account[:report_date]+ assert_equal BigDecimal("1000.00"), account[:current_balance]+ end++ test "falls back to position values plus cash when the statement carries no NAV" do+ xml = nav_statement_xml.sub(%r{<EquitySummaryInBase>.*</EquitySummaryInBase>}m, "")++ account = IbkrItem::ReportParser.new(xml).parse[:accounts].first++ assert_equal BigDecimal("1000.00"), account[:current_balance]+ end+test "raises parse error for malformed xml" doerror = assert_raises(IbkrItem::ReportParser::ParseError) doIbkrItem::ReportParser.new("<FlexQueryResponse><FlexStatement>").parse@@ -57,4 +97,42 @@ class IbkrItemReportParserTest < ActiveSupport::TestCaseassert_equal "Invalid IBKR Flex XML: missing account identifier in FlexStatement.", error.messageend++ private++ # Positions (800) plus cash (200) come to 1000; the NAV says 1500, the+ # difference being whatever the statement holds outside ChangeInPositionValues.+ # The BASE_SUMMARY row shares the latest date, so it would be picked if it+ # were not skipped.+ def nav_statement_xml(open_positions: "")+ <<~XML+ <FlexQueryResponse queryName="Sure Test">+ <FlexStatement accountId="U1234567" fromDate="2026-05-07" toDate="2026-05-08">+ <AccountInformation accountId="U1234567" currency="USD" />+ <ChangeInPositionValues>+ <ChangeInPositionValue accountId="U1234567" currency="BASE_SUMMARY" endOfPeriodValue="800.00" />+ </ChangeInPositionValues>+ <CashReport>+ <CashReportCurrency currency="BASE_SUMMARY" endingCash="200.00" />+ </CashReport>+ #{open_positions}+ <EquitySummaryInBase>+ <EquitySummaryByReportDateInBase currency="USD" reportDate="2026-05-07" total="1400.00" />+ <EquitySummaryByReportDateInBase currency="USD" reportDate="2026-05-08" total="1500.00" />+ <EquitySummaryByReportDateInBase currency="BASE_SUMMARY" reportDate="2026-05-08" total="9999.00" />+ </EquitySummaryInBase>+ </FlexStatement>+ </FlexQueryResponse>+ XML+ end++ # report_date follows the open positions when the statement has any, so a+ # date of their own is what puts it out of step with the latest NAV row.+ def open_positions_on(date)+ <<~XML+ <OpenPositions>+ <OpenPosition assetCategory="STK" conid="265598" securityID="US0378331005" securityIDType="ISIN" symbol="AAPL" position="10" markPrice="150.00" currency="USD" fxRateToBase="1" costBasisPrice="125.50" reportDate="#{date}" side="Long" />+ </OpenPositions>+ XML+ endend