The personal finance app for everyone (by everyone)
Ruby
Import IBKR fund and bond positions and trades (#5118)
arnaurodondev14d8e040d0db
diff --git a/app/models/ibkr_account/activities_processor.rb b/app/models/ibkr_account/activities_processor.rbindex 6e4402587b..568f073c88 100644--- a/app/models/ibkr_account/activities_processor.rb+++ b/app/models/ibkr_account/activities_processor.rb@@ -22,6 +22,11 @@ class IbkrAccount::ActivitiesProcessorSUPPORTED_CASH_TRANSACTION_TYPES = [ "DEPOSITS/WITHDRAWALS", *CASH_TRANSACTION_LABELS.keys ].freeze+ # Stocks and ETFs (STK), mutual funds (FUND) and bonds (BOND). Others are+ # left out and reported (see capture_skipped_trade_types). A category added+ # here must resolve its trades to the security its positions resolve to.+ SUPPORTED_TRADE_ASSET_CATEGORIES = %w[STK FUND BOND].freeze+def initialize(ibkr_account)@ibkr_account = ibkr_accountend@@ -34,9 +39,12 @@ class IbkrAccount::ActivitiesProcessorcash_transactions = Array(activities[:cash_transactions])@failed_rows = []+ @skipped_trade_types = Hash.new(0)trade_results = trades.map { |trade| process_trade(trade.with_indifferent_access) }trades_count = trade_results.count { |r| r[:imported] }fee_count = trade_results.sum { |r| r[:fees] }+ capture_skipped_trade_types+ capture_bond_unit_disagreements@cash_transactions = cash_transactions.map(&:with_indifferent_access)@skipped_cash_types = Hash.new(0)@@ -66,6 +74,9 @@ class IbkrAccount::ActivitiesProcessornative_price = parse_decimal(row[:trade_price])return { imported: false, fees: 0 } if quantity.nil? || native_price.nil?+ quantity *= quantity_multiplier(row)+ native_price *= price_scale(row)+buy_sell = row[:buy_sell].to_s.upcasesigned_quantity = buy_sell == "SELL" ? -quantity.abs : quantity.absnative_amount = buy_sell == "SELL" ? -(native_price * quantity.abs) : (native_price * quantity.abs)@@ -95,7 +106,7 @@ class IbkrAccount::ActivitiesProcessoramount: native_amount + fee,currency: currency,date: date,- name: build_trade_name(security.ticker, signed_quantity),+ name: build_trade_name(security.ticker, signed_quantity, unit: bond?(row) ? "units" : "shares"),source: "ibkr",activity_label: buy_sell == "SELL" ? "Sell" : "Buy",exchange_rate: parse_decimal(row[:fx_rate_to_base])&.to_f,@@ -231,14 +242,21 @@ class IbkrAccount::ActivitiesProcessor!!resultend- def build_trade_name(ticker, signed_quantity)+ def build_trade_name(ticker, signed_quantity, unit: "shares")action = signed_quantity.negative? ? "Sell" : "Buy"- "#{action} #{signed_quantity.abs} shares of #{ticker}"+ "#{action} #{signed_quantity.abs} #{unit} of #{ticker}"enddef supported_trade?(row)- row[:asset_category].to_s == "STK" &&- row[:buy_sell].present? &&+ category = asset_category(row)+ unless SUPPORTED_TRADE_ASSET_CATEGORIES.include?(category)+ # A currency conversion (CASH) is not a position; its two legs are+ # already in IBKR's cash and balance, so it is not reported.+ @skipped_trade_types[category.presence || "unknown"] += 1 unless category == "CASH"+ return false+ end++ row[:buy_sell].present? &&row[:conid].present? &&row[:currency].present? &&row[:quantity].present? &&@@ -288,7 +306,7 @@ class IbkrAccount::ActivitiesProcessor# The row's asset category says so when the query includes it; otherwise a# bond interest row for the same conid in the statement does.def bond_withholding?(row)- return true if row[:asset_category].to_s.upcase.strip == "BOND"+ return true if bond?(row)@cash_transactions.any? do |other|other[:conid].to_s == row[:conid].to_s && other[:type].to_s.upcase.strip.start_with?("BOND INTEREST")@@ -311,6 +329,42 @@ class IbkrAccount::ActivitiesProcessor)end+ # A trade whose proceeds are not quantity x its quoted price (quoted per+ # unit, or principal-adjusted) has its price carried to the proceeds, which+ # the trade's price shows.+ def capture_bond_unit_disagreements+ disagreements = bond_unit_disagreements(:trades)+ return if disagreements.empty?++ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "IBKR bond trades priced to their reported value",+ source: self.class.name,+ provider_key: "ibkr",+ account_provider: @ibkr_account.account_provider,+ family: @ibkr_account.ibkr_item&.family,+ metadata: { ibkr_account_id: @ibkr_account.id, bonds: disagreements }+ )+ end++ # A skipped trade changed a position the holdings do not replay, so the+ # holdings history leaves it out.+ def capture_skipped_trade_types+ return if @skipped_trade_types.empty?++ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "Skipped IBKR trades of unsupported types",+ source: self.class.name,+ provider_key: "ibkr",+ account_provider: @ibkr_account.account_provider,+ family: @ibkr_account.ibkr_item&.family,+ metadata: { ibkr_account_id: @ibkr_account.id, skipped_trade_types: @skipped_trade_types }+ )+ end+def build_cash_transaction_name(row, label, security = nil)type = row[:type].to_s.upcase.stripreturn label if type == "DEPOSITS/WITHDRAWALS"@@ -321,25 +375,31 @@ class IbkrAccount::ActivitiesProcessor[ row[:type].to_s.strip, ticker ].compact.join(" for ")end+ # Resolved from the position or trade with the row's conid, so a coupon+ # lands on the same security as the bond it was paid on.def resolve_security_for_cash_transaction(row)- symbol = security_symbol_for_conid(row[:conid])- return nil if symbol.blank?+ source = security_row_for_conid(row[:conid])+ return nil if source.nil?- resolve_security({ symbol: symbol })+ resolve_security(source.slice(:symbol, :conid, :asset_category, :description))enddef security_symbol_for_conid(conid)+ security_row_for_conid(conid)&.dig(:symbol)+ end++ def security_row_for_conid(conid)return nil if conid.blank?- holding_symbol = Array(@ibkr_account.raw_holdings_payload).find do |holding|- holding.with_indifferent_access[:conid].to_s == conid.to_s- end&.with_indifferent_access&.dig(:symbol)- return holding_symbol if holding_symbol.present?+ holding = Array(@ibkr_account.raw_holdings_payload).map(&:with_indifferent_access).find do |row|+ row[:conid].to_s == conid.to_s && row[:symbol].present?+ end+ return holding if holdingactivities = (@ibkr_account.raw_activities_payload || {}).with_indifferent_access- Array(activities[:trades]).find do |trade|- trade.with_indifferent_access[:conid].to_s == conid.to_s- end&.with_indifferent_access&.dig(:symbol)+ Array(activities[:trades]).map(&:with_indifferent_access).find do |row|+ row[:conid].to_s == conid.to_s && row[:symbol].present?+ endenddef fx_rate_available?(row)diff --git a/app/models/ibkr_account/data_helpers.rb b/app/models/ibkr_account/data_helpers.rbindex 6135557a27..d12d981c52 100644--- a/app/models/ibkr_account/data_helpers.rb+++ b/app/models/ibkr_account/data_helpers.rb@@ -1,6 +1,36 @@module IbkrAccount::DataHelpersextend ActiveSupport::Concern+ # IBKR quotes a bond as a percentage of its face value, and a bond's position+ # or trade quantity is that face value; its multiplier (0.01) relates the two.+ # Sure counts every bond in units of 100 face, the unit its price is quoted+ # per, so the price reads as IBKR quotes it and quantity x price is its value.+ #+ # The unit is fixed rather than decided from the report. A sync imports only+ # its own window and never rescales a trade stored by an earlier one, so a+ # unit that depended on the rows of the current report could differ from the+ # unit a bond's earlier trades were stored in. What does depend on the row is+ # the price: it is the one that makes quantity x price the value IBKR reports+ # for the row (see #price_scale). That is the quoted price for an ordinary+ # bond, and carries an inflation index ratio, a pool factor or a quote per+ # unit instead of per 100 face into the price for any other.+ BOND_MULTIPLIER = BigDecimal("0.01")++ # How far a bond's price may sit from the quoted one, as a share of it,+ # before the row is reported. The reported value is rounded to cents, so a+ # lot of a few units can be reported from rounding alone.+ BOND_PRICE_TOLERANCE = BigDecimal("0.001")++ # A bond is tracked under this prefix, its IBKR symbol and its contract id+ # (conid), as "BOND:<symbol>:<conid>". Trades carry no ISIN, and two bonds+ # can share a symbol, so the conid keeps them apart. The prefix keeps a bond+ # off a listed security that shares the symbol, and off that security's prices.+ BOND_TICKER_PREFIX = "BOND:"++ # No price provider quotes a bond per 100 face, so a bond is offline and+ # valued at IBKR's mark and trade prices. The reason says which flow set it.+ BOND_OFFLINE_REASON = "ibkr_bond"+privatedef parse_decimal(value)@@ -50,6 +80,8 @@ module IbkrAccount::DataHelpersdef resolve_security(row)data = row.with_indifferent_access+ return resolve_bond_security(data) if bond?(data)+ticker = data[:symbol].to_s.strip.upcasereturn nil if ticker.blank?@@ -78,4 +110,91 @@ module IbkrAccount::DataHelpersdef create_security_from_row(ticker)Security.create!(ticker: ticker, name: ticker)end++ def bond?(row)+ asset_category(row) == "BOND"+ end++ # What one unit of the row's quantity counts as in Sure: a bond's face+ # value counts per 100 face, anything else as IBKR reports it.+ def quantity_multiplier(row)+ bond?(row) ? BOND_MULTIPLIER : BigDecimal("1")+ end++ # What a bond row's quoted price is multiplied by so that quantity x price+ # x 0.01 is the value the row reports (positionValue for a position,+ # proceeds or tradeMoney for a trade): 1 for a row quoted per 100 face, 100+ # for one quoted per unit, the index ratio or pool factor for a principal-+ # adjusted bond. Accrued interest is booked as its own cash row (see the+ # fixture), and the trade and position values are taken to be clean, so the+ # quoted price is not moved by it. If a value does include some, it is+ # carried into the price, a small deviation. 1 for a row with no usable+ # value, and for anything but a bond.+ def price_scale(row)+ return BigDecimal("1") unless bond?(row)++ data = row.with_indifferent_access+ quantity = parse_decimal(data[:position] || data[:quantity])+ price = parse_decimal(data[:mark_price] || data[:trade_price])+ value = [ data[:position_value], data[:proceeds], data[:trade_money] ]+ .filter_map { |v| parse_decimal(v) }.find { |v| v.finite? && !v.zero? }+ return BigDecimal("1") unless quantity&.finite? && price&.finite? && value && !quantity.zero? && !price.zero?++ scale = value.abs / (quantity.abs * BOND_MULTIPLIER * price.abs)+ scale.finite? && scale.positive? ? scale : BigDecimal("1")+ end++ # For each bond with rows of this kind (:positions or :trades) whose price+ # was moved off the quoted one: its ticker, its unit and the factors the+ # prices were multiplied by. What a debug entry reports.+ def bond_unit_disagreements(kind)+ rows = kind == :positions ? raw_position_rows.select { |row| row[:side].to_s == "Long" } : raw_trade_rows+ factors = bond_rows(rows).map { |row| [ bond_ticker(row), price_scale(row) ] }+ factors.group_by(&:first).filter_map do |ticker, pairs|+ moved = pairs.map(&:last).reject { |scale| (scale - 1).abs <= BOND_PRICE_TOLERANCE }+ { ticker: ticker, unit_factor: BOND_MULTIPLIER.to_s("F"), differing_rows: moved.size, row_price_factors: moved.uniq.map { |f| f.round(6).to_s("F") } } if moved.any?+ end+ end++ def raw_position_rows+ Array(@ibkr_account.raw_holdings_payload).map(&:with_indifferent_access)+ end++ def raw_trade_rows+ Array((@ibkr_account.raw_activities_payload || {}).with_indifferent_access[:trades]).map(&:with_indifferent_access)+ end++ def bond_rows(rows)+ rows.select { |row| bond?(row) && bond_ticker(row) }+ end++ def asset_category(row)+ row.with_indifferent_access[:asset_category].to_s.strip.upcase+ end++ # The ticker a bond's rows are tracked under, nil when the row lacks the+ # symbol or contract id that names it.+ def bond_ticker(row)+ symbol = row[:symbol].to_s.strip.upcase+ conid = row[:conid].to_s.strip+ "#{BOND_TICKER_PREFIX}#{symbol}:#{conid}" unless symbol.blank? || conid.blank?+ end++ # Securities are global, so an existing row is reused as it stands. The+ # savepoint keeps a lost create race from aborting the import around it.+ def resolve_bond_security(data)+ return nil unless bond_ticker(data)++ ticker = bond_ticker(data)+ Security.find_by(ticker: ticker) || Security.transaction(requires_new: true) do+ Security.create!(+ ticker: ticker,+ name: data[:description].to_s.strip.presence || data[:symbol].to_s.strip.upcase,+ offline: true,+ offline_reason: BOND_OFFLINE_REASON+ )+ end+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique+ Security.find_by(ticker: ticker)+ endenddiff --git a/app/models/ibkr_account/holdings_processor.rb b/app/models/ibkr_account/holdings_processor.rbindex 0409cf0929..ee85965ab1 100644--- a/app/models/ibkr_account/holdings_processor.rb+++ b/app/models/ibkr_account/holdings_processor.rb@@ -1,12 +1,14 @@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.+ # Categories this importer accepts, held long. STK, FUND (mutual funds) and+ # BOND resolve to a security by what IBKR reports for them. 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.+ # Anything else is left out and reported (see capture_skipped_positions):+ # Sure has no model for a short position or for a derivative's contract.UNLISTED_ASSET_CATEGORIES = %w[CRYPTO CMDTY].freeze- SUPPORTED_ASSET_CATEGORIES = (%w[STK] + UNLISTED_ASSET_CATEGORIES).freeze+ SUPPORTED_ASSET_CATEGORIES = (%w[STK FUND BOND] + 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@@ -32,9 +34,12 @@ class IbkrAccount::HoldingsProcessordef processreturn unless account.present?+ @skipped_positions = Hash.new(0)grouped_positions.each do |(_, _, report_date), group|process_group(group, report_date)end+ capture_skipped_positions+ capture_bond_unit_disagreementsendprivate@@ -50,6 +55,7 @@ class IbkrAccount::HoldingsProcessordef grouped_positionsArray(@ibkr_account.raw_holdings_payload).each_with_object({}) do |position, groups|data = position.with_indifferent_access+ next if unsupported_kind?(data)next unless supported_position?(data)currency = extract_currency(data, fallback: @ibkr_account.currency)@@ -104,7 +110,9 @@ class IbkrAccount::HoldingsProcessor## 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.+ # price is the weighted average that amount and quantity imply. A bond lot+ # whose value is not its quantity x quoted price has its prices carried to+ # it, so its value stays what IBKR reports.def valid_lots(rows)total_quantity = BigDecimal("0")total_cost = BigDecimal("0")@@ -123,9 +131,11 @@ class IbkrAccount::HoldingsProcessornextend- total_quantity += row_quantity.abs- total_cost += row_quantity.abs * row_cost_basis- total_value += row_quantity.abs * row_price+ units = row_quantity.abs * quantity_multiplier(row)+ scale = price_scale(row)+ total_quantity += units+ total_cost += lot_cost(row, units, row_cost_basis, scale)+ total_value += units * row_price * scaleendreturn nil if total_quantity.zero?@@ -138,6 +148,17 @@ class IbkrAccount::HoldingsProcessor}end+ # What a lot cost. A bond's costBasisMoney is IBKR's own figure, so it is+ # taken as it stands: its price is carried to the lot's current value, which+ # a value factor has moved off what was paid. Without it, the cost price is+ # carried the way the mark price is.+ def lot_cost(row, units, cost_basis_price, scale)+ money = parse_decimal(row[:cost_basis_money]) if bond?(row)+ return money.abs if money&.finite? && money.positive?++ units * cost_basis_price * scale+ end+def resolve_position_security(row)return resolve_security(row) unless unlisted?(row)@@ -148,14 +169,14 @@ class IbkrAccount::HoldingsProcessorenddef unlisted?(row)- UNLISTED_ASSET_CATEGORIES.include?(row[:asset_category].to_s)+ UNLISTED_ASSET_CATEGORIES.include?(asset_category(row))enddef unlisted_ticker(row)symbol = row[:symbol].to_s.strip.upcasereturn nil if symbol.blank?- prefix = TICKER_PREFIXES[row[:asset_category].to_s]+ prefix = TICKER_PREFIXES[asset_category(row)]symbol.start_with?(prefix) ? symbol : "#{prefix}#{symbol}"end@@ -176,7 +197,7 @@ class IbkrAccount::HoldingsProcessorenddef pricing_attributes(row)- return { offline: true, offline_reason: COMMODITY_OFFLINE_REASON } unless row[:asset_category].to_s == "CRYPTO"+ return { offline: true, offline_reason: COMMODITY_OFFLINE_REASON } unless asset_category(row) == "CRYPTO"{exchange_operating_mic: Provider::BinancePublic::BINANCE_MIC,@@ -184,10 +205,59 @@ class IbkrAccount::HoldingsProcessor}end+ # A position of a category or side Sure does not import, counted so the+ # sync can report it.+ def unsupported_kind?(row)+ category = asset_category(row)+ kind = if !SUPPORTED_ASSET_CATEGORIES.include?(category)+ category.presence || "unknown"+ elsif row[:side].to_s != "Long"+ "#{category} #{row[:side].to_s.strip.presence || "unknown"}"+ end+ return false unless kind++ @skipped_positions[kind] += 1+ true+ end++ # The holdings leave a skipped position out, while the balance is IBKR's+ # figure, so whatever value it includes for one shows as cash.+ def capture_skipped_positions+ return if @skipped_positions.empty?++ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "Skipped IBKR positions of unsupported types",+ source: self.class.name,+ provider_key: "ibkr",+ account_provider: @ibkr_account.account_provider,+ family: @ibkr_account.ibkr_item&.family,+ metadata: { ibkr_account_id: @ibkr_account.id, skipped_position_types: @skipped_positions }+ )+ end++ # A position whose value is not quantity x its quoted price (quoted per+ # unit, or principal-adjusted) has its price carried to the value, which+ # the holding's price shows.+ def capture_bond_unit_disagreements+ disagreements = bond_unit_disagreements(:positions)+ return if disagreements.empty?++ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "IBKR bond positions priced to their reported value",+ source: self.class.name,+ provider_key: "ibkr",+ account_provider: @ibkr_account.account_provider,+ family: @ibkr_account.ibkr_item&.family,+ metadata: { ibkr_account_id: @ibkr_account.id, bonds: disagreements }+ )+ end+def supported_position?(row)- SUPPORTED_ASSET_CATEGORIES.include?(row[:asset_category].to_s) &&- row[:side].to_s == "Long" &&- row[:conid].present? &&+ row[:conid].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? &&diff --git a/app/models/ibkr_item/report_parser.rb b/app/models/ibkr_item/report_parser.rbindex 133f7e9989..7d5b3ff171 100644--- a/app/models/ibkr_item/report_parser.rb+++ b/app/models/ibkr_item/report_parser.rb@@ -130,12 +130,16 @@ class IbkrItem::ReportParserparse_decimal(row&.fetch("ending_cash", nil)) || BigDecimal("0")end+ # IBKR reports a row per asset category, so the positions are worth the sum+ # of those rows, in base currency when it gives one. A row with no category+ # is already the total of them.def extract_current_balance(position_values, account_currency)- base_summary = position_values.find { |row| row["currency"] == "BASE_SUMMARY" }- account_row = position_values.find { |row| row["currency"] == account_currency }- row = base_summary || account_row+ rows = position_values.select { |row| row["currency"] == "BASE_SUMMARY" }+ rows = position_values.select { |row| row["currency"] == account_currency } if rows.empty?+ total_row = rows.find { |row| row["asset_category"].blank? }+ rows = [ total_row ] if total_row- parse_decimal(row&.fetch("end_of_period_value", nil)) || BigDecimal("0")+ rows.sum(BigDecimal("0")) { |row| parse_decimal(row["end_of_period_value"]) || BigDecimal("0") }end# IBKR's own net asset value, which covers every asset class the accountdiff --git a/test/fixtures/files/ibkr/flex_statement_funds_bonds.xml b/test/fixtures/files/ibkr/flex_statement_funds_bonds.xmlnew file mode 100644index 0000000000..18649994d8--- /dev/null+++ b/test/fixtures/files/ibkr/flex_statement_funds_bonds.xml@@ -0,0 +1,40 @@+<FlexQueryResponse queryName="Sure Test" type="AF">+ <FlexStatements count="1">+ <FlexStatement accountId="U0000042" fromDate="2025-05-08" toDate="2026-05-08" whenGenerated="2026-05-08;12:00:00">+ <AccountInformation accountId="U0000042" currency="EUR" />+ <ChangeInPositionValues>+ <ChangeInPositionValue accountId="U0000042" currency="BASE_SUMMARY" assetCategory="BOND" endOfPeriodValue="9850.00" />+ <ChangeInPositionValue accountId="U0000042" currency="EUR" assetCategory="BOND" endOfPeriodValue="9850.00" />+ <ChangeInPositionValue accountId="U0000042" currency="BASE_SUMMARY" assetCategory="FUND" endOfPeriodValue="2500.00" />+ <ChangeInPositionValue accountId="U0000042" currency="EUR" assetCategory="FUND" endOfPeriodValue="2500.00" />+ <ChangeInPositionValue accountId="U0000042" currency="BASE_SUMMARY" assetCategory="OPT" endOfPeriodValue="300.00" />+ <ChangeInPositionValue accountId="U0000042" currency="EUR" assetCategory="OPT" endOfPeriodValue="300.00" />+ <ChangeInPositionValue accountId="U0000042" currency="BASE_SUMMARY" assetCategory="STK" endOfPeriodValue="1500.00" />+ <ChangeInPositionValue accountId="U0000042" currency="EUR" assetCategory="STK" endOfPeriodValue="1500.00" />+ </ChangeInPositionValues>+ <CashReport>+ <CashReportCurrency currency="BASE_SUMMARY" endingCash="1000.00" />+ <CashReportCurrency currency="EUR" endingCash="1000.00" />+ </CashReport>+ <EquitySummaryInBase>+ <EquitySummaryByReportDateInBase currency="EUR" reportDate="2026-05-08" cash="1000.00" stock="1500.00" bonds="9850.00" funds="2500.00" options="300.00" total="15150.00" />+ </EquitySummaryInBase>+ <OpenPositions>+ <OpenPosition assetCategory="STK" conid="900001" securityID="XX0000000011" securityIDType="ISIN" symbol="SURETST" description="SURE TEST WORLD ETF" position="20" multiplier="1" markPrice="100.00" positionValue="2000.00" currency="EUR" fxRateToBase="1" costBasisPrice="90.00" costBasisMoney="1800.00" reportDate="2026-05-08" side="Long" />+ <OpenPosition assetCategory="FUND" conid="900002" securityID="XX0000000029" securityIDType="ISIN" symbol="SURFUND" description="SURE TEST GLOBAL FUND ACC" position="12.5" multiplier="1" markPrice="200.00" positionValue="2500.00" currency="EUR" fxRateToBase="1" costBasisPrice="180.00" costBasisMoney="2250.00" reportDate="2026-05-08" side="Long" />+ <OpenPosition assetCategory="BOND" conid="900003" securityID="XX0000000037" securityIDType="ISIN" symbol="SURCO 3 1/2 06/15/30" description="SURCO 3 1/2 06/15/30" position="10000" multiplier="0.01" markPrice="98.50" positionValue="9850.00" currency="EUR" fxRateToBase="1" costBasisPrice="97.25" costBasisMoney="9725.00" reportDate="2026-05-08" side="Long" />+ <OpenPosition assetCategory="OPT" conid="900004" securityID="" securityIDType="" symbol="SURETST 260619C00110000" description="SURETST 19JUN26 110 C" position="2" multiplier="100" markPrice="1.50" positionValue="300.00" currency="EUR" fxRateToBase="1" costBasisPrice="1.20" costBasisMoney="240.00" reportDate="2026-05-08" side="Long" />+ <OpenPosition assetCategory="STK" conid="900005" securityID="XX0000000045" securityIDType="ISIN" symbol="SURSHRT" description="SURE TEST SHORTED CO" position="-5" multiplier="1" markPrice="100.00" positionValue="-500.00" currency="EUR" fxRateToBase="1" costBasisPrice="110.00" costBasisMoney="-550.00" reportDate="2026-05-08" side="Short" />+ </OpenPositions>+ <Trades>+ <Trade assetCategory="FUND" tradeID="9101" transactionID="9101a" conid="900002" symbol="SURFUND" quantity="12.5" multiplier="1" tradePrice="180.00" proceeds="-2250.00" currency="EUR" fxRateToBase="1" buySell="BUY" tradeDate="2026-04-01" ibCommission="0" ibCommissionCurrency="EUR" />+ <Trade assetCategory="BOND" tradeID="9102" transactionID="9102a" conid="900003" symbol="SURCO 3 1/2 06/15/30" quantity="10000" multiplier="0.01" tradePrice="97.25" proceeds="-9725.00" currency="EUR" fxRateToBase="1" buySell="BUY" tradeDate="2026-04-02" ibCommission="-5.00" ibCommissionCurrency="EUR" />+ <Trade assetCategory="OPT" tradeID="9103" transactionID="9103a" conid="900004" symbol="SURETST 260619C00110000" quantity="2" multiplier="100" tradePrice="1.20" proceeds="-240.00" currency="EUR" fxRateToBase="1" buySell="BUY" tradeDate="2026-04-03" ibCommission="-1.30" ibCommissionCurrency="EUR" />+ <Trade assetCategory="CASH" tradeID="9104" transactionID="9104a" conid="900006" symbol="EUR.USD" quantity="1000" tradePrice="1.10" proceeds="-1100.00" currency="USD" fxRateToBase="0.91" buySell="BUY" tradeDate="2026-04-04" ibCommission="-2.00" ibCommissionCurrency="EUR" />+ </Trades>+ <CashTransactions>+ <CashTransaction transactionID="9201" type="Bond Interest Paid" amount="-15.00" currency="EUR" fxRateToBase="1" reportDate="2026-04-02" conid="900003" />+ </CashTransactions>+ </FlexStatement>+ </FlexStatements>+</FlexQueryResponse>diff --git a/test/models/ibkr_account/funds_and_bonds_test.rb b/test/models/ibkr_account/funds_and_bonds_test.rbnew file mode 100644index 0000000000..0de6f31444--- /dev/null+++ b/test/models/ibkr_account/funds_and_bonds_test.rb@@ -0,0 +1,635 @@+require "test_helper"++# A statement holding a stock, a mutual fund, a bond, a long option and a short+# stock (test/fixtures/files/ibkr/flex_statement_funds_bonds.xml), run through+# the parser and the processor the way a sync runs it.+class IbkrAccount::FundsAndBondsTest < ActiveSupport::TestCase+ BOND_TICKER = "BOND:SURCO 3 1/2 06/15/30:900003".freeze++ # The bond as a later sync reports it: 10,000 face at 98.50% of par, and a+ # sale of 5,000 of it, both with IBKR's 0.01 multiplier.+ BOND_POSITION = {+ "asset_category" => "BOND", "conid" => "900003", "security_id" => "XX0000000037", "security_id_type" => "ISIN",+ "symbol" => "SURCO 3 1/2 06/15/30", "description" => "SURCO 3 1/2 06/15/30", "position" => "10000",+ "multiplier" => "0.01", "mark_price" => "98.50", "position_value" => "9850.00", "currency" => "EUR",+ "fx_rate_to_base" => "1", "cost_basis_price" => "97.25", "cost_basis_money" => "9725.00",+ "report_date" => "2026-05-20", "side" => "Long"+ }.freeze++ BOND_SALE = {+ "asset_category" => "BOND", "trade_id" => "9106", "transaction_id" => "9106a", "conid" => "900003",+ "symbol" => "SURCO 3 1/2 06/15/30", "quantity" => "-5000", "multiplier" => "0.01", "trade_price" => "98.00",+ "proceeds" => "4900.00", "currency" => "EUR", "fx_rate_to_base" => "1", "buy_sell" => "SELL",+ "trade_date" => "2026-05-15", "ib_commission" => "0", "ib_commission_currency" => "EUR"+ }.freeze++ fixtures :families, :ibkr_items, :ibkr_accounts, :accounts, :securities++ setup do+ @family = families(:dylan_family)+ @ibkr_account = ibkr_accounts(:main_account)+ @account = @family.accounts.create!(+ name: "IBKR Investment",+ balance: 0,+ cash_balance: 0,+ currency: "EUR",+ accountable: Investment.new(subtype: "brokerage")+ )+ @ibkr_account.ensure_account_provider!(@account)++ @statement = IbkrItem::ReportParser.new(file_fixture("ibkr/flex_statement_funds_bonds.xml").read).parse[:accounts].first+ @report_date = Date.new(2026, 5, 8)+ end++ test "the current balance sums every asset category's position value" do+ # 9850 bond + 2500 fund + 300 option + 1500 stock, plus 1000 cash: IBKR's NAV.+ assert_equal BigDecimal("15150.00"), @statement[:current_balance]+ end++ test "a position value row with no category is taken as the total" do+ rows = [+ { "currency" => "BASE_SUMMARY", "asset_category" => "STK", "end_of_period_value" => "1500" },+ { "currency" => "BASE_SUMMARY", "asset_category" => "", "end_of_period_value" => "1800" },+ { "currency" => "BASE_SUMMARY", "asset_category" => "BOND", "end_of_period_value" => "300" }+ ]++ assert_equal BigDecimal("1800"), IbkrItem::ReportParser.new("<x/>").send(:extract_current_balance, rows, "EUR")+ end++ test "fund and bond positions are imported at IBKR's value and cost" do+ process!++ fund = holding_for("SURFUND")+ assert_equal BigDecimal("12.5"), fund.qty+ assert_equal BigDecimal("200"), fund.price+ assert_equal BigDecimal("2500"), fund.amount+ assert_equal BigDecimal("180"), fund.cost_basis++ # 10,000 face at 98.50% of par, counted in units of 100 face.+ bond = holding_for("BOND:SURCO 3 1/2 06/15/30:900003")+ assert_equal BigDecimal("100"), bond.qty+ assert_equal BigDecimal("98.5"), bond.price+ assert_equal BigDecimal("9850"), bond.amount+ assert_equal BigDecimal("97.25"), bond.cost_basis+ assert_equal BigDecimal("9725"), bond.qty * bond.cost_basis++ stock = holding_for("SURETST")+ assert_equal BigDecimal("2000"), stock.amount+ end++ test "imported holdings and the skipped positions add up to the balance" do+ process!++ @account.reload+ assert_equal BigDecimal("15150"), @account.balance+ assert_equal 3, @account.holdings.where(date: @report_date).count++ holdings_value = @account.holdings.where(date: @report_date).sum(:amount)+ assert_equal BigDecimal("14350"), holdings_value++ # What is left of the balance is IBKR's cash plus the skipped long call+ # (+300) and short stock (-500).+ assert_equal BigDecimal("1000") + 300 - 500, @account.balance - holdings_value+ end++ test "a bond is its own offline security, not a listed one sharing its symbol" do+ listed = Security.create!(ticker: "SURCO 3 1/2 06/15/30", name: "Listed lookalike")++ process!++ bond = Security.find_by!(ticker: "BOND:SURCO 3 1/2 06/15/30:900003")+ assert_not_equal listed, bond+ assert bond.offline?+ assert_equal "ibkr_bond", bond.offline_reason+ assert_equal "SURCO 3 1/2 06/15/30", bond.name+ assert_empty @account.holdings.where(security: listed)+ end++ test "two bonds sharing a symbol are kept apart by their contract id" do+ bond_position = @statement[:open_positions].find { |row| row["conid"] == "900003" }+ @statement[:open_positions] << bond_position.merge(+ "conid" => "900007", "security_id" => "XX0000000052", "position" => "5000",+ "mark_price" => "101.00", "position_value" => "5050.00",+ "cost_basis_price" => "99.00", "cost_basis_money" => "4950.00"+ )+ bond_trade = @statement[:trades].find { |row| row["conid"] == "900003" }+ @statement[:trades] << bond_trade.merge(+ "trade_id" => "9105", "transaction_id" => "9105a", "conid" => "900007",+ "quantity" => "5000", "trade_price" => "99.00", "proceeds" => "-4950.00"+ )+ @statement[:cash_transactions] << @statement[:cash_transactions].first.merge(+ "transaction_id" => "9202", "amount" => "-7.00", "conid" => "900007"+ )++ process!++ bonds = @account.holdings.joins(:security).where(date: @report_date, securities: { offline_reason: "ibkr_bond" })+ assert_equal [ BigDecimal("5050"), BigDecimal("9850") ], bonds.map(&:amount).sort++ first = holding_for("BOND:SURCO 3 1/2 06/15/30:900003")+ assert_equal BigDecimal("100"), first.qty+ assert_equal BigDecimal("9850"), first.amount+ assert_equal BigDecimal("97.25"), first.cost_basis++ second = holding_for("BOND:SURCO 3 1/2 06/15/30:900007")+ assert_equal BigDecimal("50"), second.qty+ assert_equal BigDecimal("5050"), second.amount+ assert_equal BigDecimal("99"), second.cost_basis+ assert_not_equal first.security, second.security++ assert_equal first.security, @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable.security+ assert_equal second.security, @account.entries.find_by!(external_id: "ibkr_trade_9105").entryable.security+ assert_equal first.security.id, @account.entries.find_by!(external_id: "ibkr_cash_9201").entryable.extra["security_id"]+ assert_equal second.security.id, @account.entries.find_by!(external_id: "ibkr_cash_9202").entryable.extra["security_id"]+ end++ test "a bond without the multiplier field is counted per 100 face" do+ @statement[:open_positions].each { |row| row.delete("multiplier") }+ @statement[:trades].each { |row| row.delete("multiplier") }++ process!++ bond = holding_for("BOND:SURCO 3 1/2 06/15/30:900003")+ assert_equal BigDecimal("100"), bond.qty+ assert_equal BigDecimal("9850"), bond.amount++ trade = @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable+ assert_equal BigDecimal("100"), trade.qty+ end++ test "a bond reported with multiplier 1 is still counted per 100 face" do+ bond_rows(@statement).each { |row| row["multiplier"] = "1" }++ process!++ bond = holding_for("BOND:SURCO 3 1/2 06/15/30:900003")+ assert_equal BigDecimal("100"), bond.qty+ assert_equal BigDecimal("98.5"), bond.price+ assert_equal BigDecimal("9850"), bond.amount+ assert_equal BigDecimal("9725"), bond.qty * bond.cost_basis+ end++ test "a bond reported with multiplier 0.01 is counted per 100 face" do+ bond_rows(@statement).each { |row| row["multiplier"] = "0.01" }++ process!++ bond = holding_for("BOND:SURCO 3 1/2 06/15/30:900003")+ assert_equal BigDecimal("100"), bond.qty+ assert_equal BigDecimal("9850"), bond.amount+ end++ test "a bond price quoted per unit, not per 100 face, is carried into 100 face at the same value" do+ # positionValue = position x markPrice, so the face value is the quantity,+ # and the price is carried to per 100 face: 0.985 a unit is 98.50.+ per_unit_position!++ process!++ bond = holding_for(BOND_TICKER)+ assert_equal BigDecimal("100"), bond.qty+ assert_equal BigDecimal("98.5"), bond.price+ assert_equal BigDecimal("9850"), bond.amount+ assert_equal BigDecimal("97.25"), bond.cost_basis+ end++ # A bond is always counted per 100 face, whatever its position says, so its+ # trades and its position share a unit in every sync.+ test "a bond's trade is counted per 100 face whatever unit its open position is quoted in" do+ per_unit_position!++ process!++ trade = @account.entries.find_by!(external_id: "ibkr_trade_9102")+ assert_equal BigDecimal("100"), trade.entryable.qty+ assert_equal BigDecimal("97.25"), trade.entryable.price+ assert_equal BigDecimal("9730"), trade.amount++ assert_equal BigDecimal("97.25"), holding_for(BOND_TICKER).cost_basis+ end++ test "a trade quoted per unit is carried into 100 face" do+ # This trade says 10,000 face at 0.9725 a unit: 100 units at 97.25.+ trade = @statement[:trades].find { |row| row["asset_category"] == "BOND" }+ trade.merge!("multiplier" => "1", "trade_price" => "0.9725")++ process!++ entry = @account.entries.find_by!(external_id: "ibkr_trade_9102")+ assert_equal BigDecimal("100"), entry.entryable.qty+ assert_equal BigDecimal("97.25"), entry.entryable.price+ assert_equal BigDecimal("100"), holding_for(BOND_TICKER).qty+ end++ test "a position quoted per unit and a trade per 100 face reverse to nothing before the purchase" do+ per_unit_position!++ process!+ materialize!++ bond = Security.find_by!(ticker: BOND_TICKER)+ assert_no_units_before_the_purchase(bond)++ on_trade_day = @account.holdings.find_by!(security: bond, date: Date.new(2026, 4, 2))+ assert_equal BigDecimal("100"), on_trade_day.qty+ # The trade's price is the day's price; units x price is what was paid.+ assert_equal BigDecimal("9725"), on_trade_day.amount++ today = @account.holdings.where(security: bond).order(:date).last+ assert_equal BigDecimal("100"), today.qty+ end++ test "a trade quoted per unit leaves the holding history in one unit with a position per 100 face" do+ trade = @statement[:trades].find { |row| row["asset_category"] == "BOND" }+ trade.merge!("multiplier" => "1", "trade_price" => "0.9725")++ process!+ materialize!++ bond = Security.find_by!(ticker: BOND_TICKER)+ assert_no_units_before_the_purchase(bond)+ on_trade_day = @account.holdings.find_by!(security: bond, date: Date.new(2026, 4, 2))+ assert_equal BigDecimal("100"), on_trade_day.qty+ assert_equal BigDecimal("9725"), on_trade_day.amount+ end++ # An inflation-indexed or amortising bond is worth its face x price x a+ # factor. IBKR reports the factored value in proceeds and positionValue and+ # leaves the quantity at face, so the price is carried to what makes+ # quantity x price the reported value.+ test "a bond trade whose proceeds carry a value factor is imported at the proceeds" do+ trade = @statement[:trades].find { |row| row["asset_category"] == "BOND" }+ trade.merge!("proceeds" => "-11670.00", "ib_commission" => "0")++ process!++ entry = @account.entries.find_by!(external_id: "ibkr_trade_9102")+ assert_equal BigDecimal("100"), entry.entryable.qty+ assert_equal BigDecimal("116.7"), entry.entryable.price+ assert_equal BigDecimal("11670"), entry.amount+ assert_equal entry.amount, entry.entryable.qty * entry.entryable.price+ end++ test "a bond position whose value carries a value factor is imported at the position value" do+ @statement[:open_positions].find { |row| row["asset_category"] == "BOND" }+ .merge!("mark_price" => "97.25", "position_value" => "11670.00", "cost_basis_price" => "97.25", "cost_basis_money" => "9725.00")+ @statement[:trades].find { |row| row["asset_category"] == "BOND" }+ .merge!("proceeds" => "-11670.00", "ib_commission" => "0")++ process!+ materialize!++ bond = holding_for(BOND_TICKER)+ assert_equal BigDecimal("100"), bond.qty+ assert_equal BigDecimal("11670"), bond.amount+ # What was paid stays IBKR's cost, not the value factor's.+ assert_equal BigDecimal("9725"), bond.qty * bond.cost_basis++ security = Security.find_by!(ticker: BOND_TICKER)+ assert_no_units_before_the_purchase(security)+ on_trade_day = @account.holdings.find_by!(security: security, date: Date.new(2026, 4, 2))+ assert_equal BigDecimal("11670"), on_trade_day.amount++ entry = DebugLogEntry.find_by!(provider_key: "ibkr", message: "IBKR bond positions priced to their reported value")+ assert_equal [ "1.2" ], entry.metadata["bonds"].sole["row_price_factors"]+ end++ test "a value that is zero or not a number leaves the quoted price" do+ position = @statement[:open_positions].find { |row| row["asset_category"] == "BOND" }+ position["position_value"] = "NaN"+ @statement[:trades].find { |row| row["asset_category"] == "BOND" }.merge!("proceeds" => "0", "trade_money" => "0")++ process!++ assert_equal [ BigDecimal("100"), BigDecimal("98.5") ], holding_for(BOND_TICKER).then { |h| [ h.qty, h.price ] }+ assert_equal BigDecimal("97.25"), @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable.price+ end++ test "a row priced to a value other than its quoted price is reported" do+ per_unit_position!++ process!++ entry = DebugLogEntry.find_by!(provider_key: "ibkr", message: "IBKR bond positions priced to their reported value")+ assert_equal "warn", entry.level+ bond = entry.metadata["bonds"].sole+ assert_equal BOND_TICKER, bond["ticker"]+ assert_equal "0.01", bond["unit_factor"]+ assert_equal [ "100.0" ], bond["row_price_factors"]+ assert_nil DebugLogEntry.find_by(provider_key: "ibkr", message: "IBKR bond trades priced to their reported value")+ end++ test "rows quoted per 100 face report nothing" do+ assert_no_difference -> { DebugLogEntry.where(provider_key: "ibkr", message: [ "IBKR bond trades priced to their reported value", "IBKR bond positions priced to their reported value" ]).count } do+ process!+ end+ end++ test "two lots of one bond quoted in different units are carried into one" do+ # 10,000 face at 98.50 per 100 face (the fixture), plus 5,000 at 1.01 a unit.+ lot = @statement[:open_positions].find { |row| row["asset_category"] == "BOND" }+ @statement[:open_positions] << lot.merge(+ "position" => "5000", "multiplier" => "1", "mark_price" => "1.01", "position_value" => "5050.00",+ "cost_basis_price" => "0.99", "cost_basis_money" => "4950.00"+ )++ process!++ bond = holding_for(BOND_TICKER)+ assert_equal BigDecimal("150"), bond.qty+ assert_equal BigDecimal("14900"), bond.amount+ assert_in_delta 14675, bond.qty * bond.cost_basis, 0.01++ entry = DebugLogEntry.find_by!(provider_key: "ibkr", message: "IBKR bond positions priced to their reported value")+ assert_equal [ "100.0" ], entry.metadata["bonds"].sole["row_price_factors"]+ assert_equal "0.01", entry.metadata["bonds"].sole["unit_factor"]+ end++ test "a short bond position, which is not imported, is not reported" do+ short = @statement[:open_positions].find { |row| row["asset_category"] == "BOND" }+ @statement[:open_positions].delete(short)+ @statement[:open_positions] << short.merge(+ "side" => "Short", "position" => "-10000", "multiplier" => "1", "mark_price" => "0.985", "position_value" => "-9850.00"+ )++ process!++ assert_equal BigDecimal("100"), @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable.qty+ assert_equal BigDecimal("97.25"), @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable.price+ assert_nil DebugLogEntry.find_by(provider_key: "ibkr", message: "IBKR bond positions priced to their reported value")+ end++ test "a bond sold since has no position and counts in the unit its trades imply" do+ @statement[:open_positions].reject! { |row| row["asset_category"] == "BOND" }+ @statement[:trades].find { |row| row["asset_category"] == "BOND" }.merge!("multiplier" => "1")+ @statement[:trades] << @statement[:trades].find { |row| row["asset_category"] == "BOND" }.merge(+ "trade_id" => "9106", "transaction_id" => "9106a", "buy_sell" => "SELL", "quantity" => "-10000",+ "trade_price" => "98.00", "proceeds" => "9800.00", "trade_date" => "2026-04-20", "ib_commission" => "0"+ )++ process!++ buy = @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable+ sell = @account.entries.find_by!(external_id: "ibkr_trade_9106").entryable+ assert_equal [ BigDecimal("100"), BigDecimal("-100") ], [ buy.qty, sell.qty ]+ assert_equal [ BigDecimal("97.25"), BigDecimal("98") ], [ buy.price, sell.price ]+ end++ test "trades of one bond quoted in different units, with no position, are carried into one" do+ @statement[:open_positions].reject! { |row| row["asset_category"] == "BOND" }+ template = @statement[:trades].find { |row| row["asset_category"] == "BOND" }+ # Two trades per 100 face (the fixture's and the next), one per unit.+ @statement[:trades] << template.merge("trade_id" => "9106", "transaction_id" => "9106a", "trade_date" => "2026-04-03")+ @statement[:trades] << template.merge(+ "trade_id" => "9107", "transaction_id" => "9107a", "multiplier" => "1", "trade_date" => "2026-04-04",+ "trade_price" => "0.9725"+ )++ process!++ %w[9102 9106 9107].each do |id|+ trade = @account.entries.find_by!(external_id: "ibkr_trade_#{id}").entryable+ assert_equal BigDecimal("100"), trade.qty, "trade #{id}"+ assert_equal BigDecimal("97.25"), trade.price, "trade #{id}"+ end+ end++ test "a bond trade reported with multiplier 1 is counted per 100 face" do+ bond_rows(@statement).each { |row| row["multiplier"] = "1" }++ process!++ trade = @account.entries.find_by!(external_id: "ibkr_trade_9102")+ assert_equal BigDecimal("100"), trade.entryable.qty+ assert_equal BigDecimal("97.25"), trade.entryable.price+ assert_equal BigDecimal("9730"), trade.amount+ end++ test "a bond trade without proceeds is checked against its trade money" do+ trade = @statement[:trades].find { |row| row["asset_category"] == "BOND" }+ trade.merge!("multiplier" => "1", "trade_money" => "9725.00")+ trade.delete("proceeds")++ process!++ assert_equal BigDecimal("100"), @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable.qty+ end++ test "a bond row with nothing to check the unit against falls back to 100 face" do+ bond_rows(@statement).each do |row|+ row["multiplier"] = "1"+ row.delete("position_value")+ row.delete("proceeds")+ end++ process!++ assert_equal BigDecimal("100"), holding_for("BOND:SURCO 3 1/2 06/15/30:900003").qty+ assert_equal BigDecimal("100"), @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable.qty+ end++ test "a multiplier on a fund or stock changes nothing" do+ @statement[:open_positions].each { |row| row["multiplier"] = "0.01" if %w[STK FUND].include?(row["asset_category"]) }+ @statement[:trades].each { |row| row["multiplier"] = "0.01" if row["asset_category"] == "FUND" }++ process!++ assert_equal BigDecimal("12.5"), holding_for("SURFUND").qty+ assert_equal BigDecimal("20"), holding_for("SURETST").qty+ assert_equal BigDecimal("12.5"), @account.entries.find_by!(external_id: "ibkr_trade_9101").entryable.qty+ end++ test "bond, fund, stock and commodity in one account each keep their own unit" do+ @statement[:open_positions] << {+ "asset_category" => "CMDTY", "conid" => "900006", "security_id" => "", "security_id_type" => "",+ "symbol" => "SURMETAL", "description" => "SURE TEST METAL", "position" => "3", "multiplier" => "0.01",+ "mark_price" => "50.00", "position_value" => "150.00", "currency" => "EUR", "fx_rate_to_base" => "1",+ "cost_basis_price" => "40.00", "report_date" => "2026-05-08", "side" => "Long"+ }+ bond_rows(@statement).each { |row| row["multiplier"] = "1" }++ process!++ assert_equal BigDecimal("100"), holding_for("BOND:SURCO 3 1/2 06/15/30:900003").qty+ assert_equal BigDecimal("12.5"), holding_for("SURFUND").qty+ assert_equal BigDecimal("20"), holding_for("SURETST").qty+ assert_equal BigDecimal("3"), holding_for("CMDTY:SURMETAL").qty+ assert_equal BigDecimal("150"), holding_for("CMDTY:SURMETAL").amount+ end++ test "a lowercase category is treated like its upper-case form" do+ @statement[:open_positions] << {+ "asset_category" => "cmdty", "conid" => "900006", "security_id" => "", "security_id_type" => "",+ "symbol" => "SURMETAL", "description" => "SURE TEST METAL", "position" => "3", "multiplier" => "1",+ "mark_price" => "50.00", "position_value" => "150.00", "currency" => "EUR", "fx_rate_to_base" => "1",+ "cost_basis_price" => "40.00", "report_date" => "2026-05-08", "side" => "Long"+ }++ process!++ assert_equal BigDecimal("3"), holding_for("CMDTY:SURMETAL").qty+ assert_nil Security.find_by(ticker: "SURMETAL")+ end++ test "fund and bond trades are imported in the holdings' units" do+ process!++ fund_trade = @account.entries.find_by!(external_id: "ibkr_trade_9101")+ assert_equal BigDecimal("12.5"), fund_trade.entryable.qty+ assert_equal BigDecimal("180"), fund_trade.entryable.price+ assert_equal BigDecimal("2250"), fund_trade.amount+ assert_equal "SURFUND", fund_trade.entryable.security.ticker++ bond_trade = @account.entries.find_by!(external_id: "ibkr_trade_9102")+ assert_equal BigDecimal("100"), bond_trade.entryable.qty+ assert_equal BigDecimal("97.25"), bond_trade.entryable.price+ assert_equal BigDecimal("5"), bond_trade.entryable.fee+ # IBKR's proceeds (9725) plus the commission.+ assert_equal BigDecimal("9730"), bond_trade.amount+ assert_equal "Buy 100.0 units of BOND:SURCO 3 1/2 06/15/30:900003", bond_trade.name+ assert_equal holding_for("BOND:SURCO 3 1/2 06/15/30:900003").security, bond_trade.entryable.security+ end++ test "accrued interest paid on a bond lands on the bond's security" do+ process!++ entry = @account.entries.find_by!(external_id: "ibkr_cash_9201")+ assert_equal "Interest", entry.entryable.investment_activity_label+ assert_equal Security.find_by!(ticker: "BOND:SURCO 3 1/2 06/15/30:900003").id, entry.entryable.extra["security_id"]+ end++ test "positions and trades of unsupported types are reported, one entry each" do+ assert_difference -> { DebugLogEntry.where(provider_key: "ibkr").count }, 2 do+ process!+ end++ positions = DebugLogEntry.find_by!(provider_key: "ibkr", message: "Skipped IBKR positions of unsupported types")+ assert_equal "warn", positions.level+ assert_equal @family, positions.family+ assert_equal({ "OPT" => 1, "STK Short" => 1 }, positions.metadata["skipped_position_types"])++ trades = DebugLogEntry.find_by!(provider_key: "ibkr", message: "Skipped IBKR trades of unsupported types")+ assert_equal({ "OPT" => 1 }, trades.metadata["skipped_trade_types"])++ assert_nil @account.entries.find_by(external_id: "ibkr_trade_9103")+ assert_nil Security.find_by(ticker: "SURETST 260619C00110000")+ end++ test "a statement with only supported positions and trades reports nothing" do+ @statement[:open_positions].reject! { |row| row["asset_category"] == "OPT" || row["side"] == "Short" }+ @statement[:trades].reject! { |row| row["asset_category"] == "OPT" }++ assert_no_difference -> { DebugLogEntry.where(provider_key: "ibkr").count } do+ process!+ end+ end++ # A sync imports only its own window: the trades already stored are not+ # imported again, and are not rescaled. So a bond's unit must come from the+ # row alone, or one window would count a bond in another unit than the last.+ test "a later window counts a bond in the unit of the earlier one" do+ per_unit_position!+ per_unit_trade!+ process!++ next_window!(+ positions: [ bond_position(position: "5000", mark_price: "98.50", position_value: "4925.00", cost_basis_price: "97.25") ],+ trades: [ bond_sale(quantity: "-5000", trade_price: "98.00", proceeds: "4900.00") ]+ )+ process!+ materialize!++ buy = @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable+ sale = @account.entries.find_by!(external_id: "ibkr_trade_9106").entryable+ assert_equal [ BigDecimal("100"), BigDecimal("97.25") ], [ buy.qty, buy.price ]+ assert_equal [ BigDecimal("-50"), BigDecimal("98") ], [ sale.qty, sale.price ]++ bond = Security.find_by!(ticker: BOND_TICKER)+ assert_no_units_before_the_purchase(bond)+ assert_equal BigDecimal("100"), @account.holdings.find_by!(security: bond, date: Date.new(2026, 4, 2)).qty+ assert_equal BigDecimal("50"), @account.holdings.where(security: bond).order(:date).last.qty+ end++ test "a later window with only a sale quoted per unit is counted per 100 face like the purchase" do+ process!++ next_window!(positions: [], trades: [ bond_sale(quantity: "-5000", trade_price: "0.98", proceeds: "4900.00", multiplier: "1") ])+ process!++ sale = @account.entries.find_by!(external_id: "ibkr_trade_9106")+ assert_equal [ BigDecimal("-50"), BigDecimal("98") ], [ sale.entryable.qty, sale.entryable.price ]+ assert_equal BigDecimal("-4900"), sale.amount+ assert_equal BigDecimal("50"), @account.trades.joins(:security).where(securities: { ticker: BOND_TICKER }).sum(:qty)+ end++ test "a bond first imported by its trades only and later by its position is in one unit" do+ @statement[:open_positions].reject! { |row| row["asset_category"] == "BOND" }+ process!++ per_unit = bond_position(multiplier: "1", mark_price: "0.985", cost_basis_price: "0.9725")+ next_window!(positions: [ per_unit ], trades: [])+ process!+ materialize!++ assert_equal BigDecimal("100"), @account.entries.find_by!(external_id: "ibkr_trade_9102").entryable.qty+ bond = Security.find_by!(ticker: BOND_TICKER)+ today = @account.holdings.where(security: bond).order(:date).last+ assert_equal [ BigDecimal("100"), BigDecimal("98.5"), BigDecimal("9850") ], [ today.qty, today.price, today.amount ]+ assert_no_units_before_the_purchase(bond)+ end++ private++ def process!+ @ibkr_account.upsert_from_ibkr_statement!(@statement)+ IbkrAccount::Processor.new(@ibkr_account).process+ end++ # Undoing the one purchase from today's position leaves nothing: no opening+ # lot of units that no trade explains.+ def assert_no_units_before_the_purchase(bond)+ opening = @account.holding_lots.opening.where(security: bond).sum(:qty)+ assert_equal 0, opening, "undoing the purchase leaves #{opening} units"+ end++ def materialize!+ Holding::Materializer.new(@account.reload, strategy: :reverse).materialize_holdings+ end++ # The position counted per unit, at 0.985 a unit, while the trade is+ # quoted per 100 face as in the fixture.+ def per_unit_position!+ @statement[:open_positions].find { |row| row["asset_category"] == "BOND" }+ .merge!("multiplier" => "1", "mark_price" => "0.985", "cost_basis_price" => "0.9725")+ end++ # The next sync's report: only the given bond positions and trades, a+ # later report date, and what IBKR sends in every window left as it was.+ def next_window!(positions:, trades:)+ @statement[:open_positions] = positions+ @statement[:trades] = trades+ @statement[:cash_transactions] = []+ @statement[:report_date] = Date.new(2026, 5, 20)+ end++ def bond_position(overrides = {})+ BOND_POSITION.merge(overrides.stringify_keys)+ end++ def bond_sale(overrides = {})+ BOND_SALE.merge(overrides.stringify_keys)+ end++ def per_unit_trade!+ @statement[:trades].find { |row| row["asset_category"] == "BOND" }+ .merge!("multiplier" => "1", "trade_price" => "0.9725")+ end++ def bond_rows(statement)+ (statement[:open_positions] + statement[:trades]).select { |row| row["asset_category"] == "BOND" }+ end++ def holding_for(ticker)+ @account.holdings.joins(:security).find_by!(securities: { ticker: ticker }, date: @report_date)+ end+end