The personal finance app for everyone (by everyone)
Ruby
Import IBKR Flex history older than the query's 365-day window (#5041)
arnaurodondev0050bdeb1055
diff --git a/app/models/ibkr_account.rb b/app/models/ibkr_account.rbindex eb491f96a9..97fae3c19b 100644--- a/app/models/ibkr_account.rb+++ b/app/models/ibkr_account.rb@@ -58,7 +58,7 @@ class IbkrAccount < ApplicationRecordprovider_name: "Interactive Brokers",statement_from_date: data.dig(:statement, :from_date),statement_to_date: data.dig(:statement, :to_date)- }.compact,+ }.compact.merge(institution_metadata.to_h.slice("history")),report_date: data[:report_date],raw_holdings_payload: data[:open_positions] || [],raw_activities_payload: {diff --git a/app/models/ibkr_account/activities_processor.rb b/app/models/ibkr_account/activities_processor.rbindex 6499fe77ed..6e4402587b 100644--- a/app/models/ibkr_account/activities_processor.rb+++ b/app/models/ibkr_account/activities_processor.rb@@ -27,12 +27,13 @@ class IbkrAccount::ActivitiesProcessorenddef process- return { trades: 0, transactions: 0 } unless account.present?+ return { trades: 0, transactions: 0, failed_rows: [] } unless account.present?activities = (@ibkr_account.raw_activities_payload || {}).with_indifferent_accesstrades = Array(activities[:trades])cash_transactions = Array(activities[:cash_transactions])+ @failed_rows = []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] }@@ -42,7 +43,7 @@ class IbkrAccount::ActivitiesProcessorcash_count = @cash_transactions.sum { |t| process_cash_transaction(t) ? 1 : 0 }capture_skipped_cash_types- { trades: trades_count, transactions: cash_count + fee_count }+ { trades: trades_count, transactions: cash_count + fee_count, failed_rows: @failed_rows }endprivate@@ -112,6 +113,7 @@ class IbkrAccount::ActivitiesProcessorfees = separate && import_commission_transaction(row, security, date) ? 1 : 0{ imported: true, fees: fees }rescue => e+ @failed_rows << "trade #{row[:trade_id]}"Rails.logger.error("IbkrAccount::ActivitiesProcessor - Failed to process trade #{row[:trade_id]}: #{e.message}"){ imported: false, fees: 0 }end@@ -152,6 +154,7 @@ class IbkrAccount::ActivitiesProcessortruerescue => e+ @failed_rows << "cash #{row[:transaction_id]}"Rails.logger.error("IbkrAccount::ActivitiesProcessor - Failed to process cash transaction #{row[:transaction_id]}: #{e.message}")falseenddiff --git a/app/models/ibkr_account/processor.rb b/app/models/ibkr_account/processor.rbindex dbb424e79b..4932ad1c51 100644--- a/app/models/ibkr_account/processor.rb+++ b/app/models/ibkr_account/processor.rb@@ -12,6 +12,7 @@ class IbkrAccount::ProcessorIbkrAccount::HoldingsProcessor.new(ibkr_account).processIbkrAccount::ActivitiesProcessor.new(ibkr_account).processrepair_default_opening_anchor!+ move_opening_anchor_before_entries!account.broadcast_sync_completeend@@ -98,6 +99,22 @@ class IbkrAccount::Processordateend+ # Captured rather than raised, as the anchor repair below is:+ # broadcast_sync_complete still has to run.+ def move_opening_anchor_before_entries!+ account.ensure_opening_anchor_precedes_entries+ rescue => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to move the opening anchor before the oldest entry: #{e.message}",+ source: self.class.name,+ provider_key: "ibkr",+ account_provider: ibkr_account.account_provider,+ family: ibkr_account.ibkr_item&.family+ )+ end+def repair_default_opening_anchor!return unless account&.linked_to?("IbkrAccount")return unless account.has_opening_anchor?diff --git a/app/models/ibkr_item/importer.rb b/app/models/ibkr_item/importer.rbindex 30a5916daa..57ee889393 100644--- a/app/models/ibkr_item/importer.rb+++ b/app/models/ibkr_item/importer.rb@@ -1,4 +1,17 @@class IbkrItem::Importer+ # A Flex request covers at most 365 days, so history older than the saved+ # query's period is fetched one window at a time, walking back up to the+ # four previous calendar years (IBKR doesn't document its reach). New windows are+ # only started this long into the import (IBKR's pacing makes each one take+ # a while), and the next sync resumes.+ HISTORY_TIME_BUDGET = 1.minute+ # Syncs a window is tried before it is given up (IBKR refuses it or has no+ # statements for it) or its failing rows are skipped. XML that does not+ # parse is more often a cut-off transfer, so it gets more tries before the+ # window is skipped.+ MAX_HISTORY_FAILURES = 3+ MAX_PARSE_FAILURES = MAX_HISTORY_FAILURES * 2+attr_reader :ibkr_item, :ibkr_providerdef initialize(ibkr_item, ibkr_provider:)@@ -7,6 +20,7 @@ class IbkrItem::Importerenddef import+ deadline = HISTORY_TIME_BUDGET.from_nowxml_body = ibkr_provider.download_statementparsed_report = IbkrItem::ReportParser.new(xml_body).parse@@ -25,9 +39,142 @@ class IbkrItem::Importeribkr_item.update!(status: :good)end+ loop { break unless Time.current < deadline && import_history_window }+{success: true,accounts_imported: accounts_imported}end++ private++ # Fetches the most recent missing window (so an account linked later+ # catches up without a hole) and imports it like the regular statement.+ # A window is recorded only once all its rows are imported, so one cut+ # short or with a row that failed is fetched again, up to+ # MAX_HISTORY_FAILURES syncs for the row. Returns whether the walk can go+ # on in this sync.+ def import_history_window+ pending = ibkr_item.linked_ibkr_accounts.includes(account_provider: :account).filter_map do |ibkr_account|+ state = history_state(ibkr_account)+ [ ibkr_account, state ] if state+ end+ return false if pending.empty?++ to_date = pending.map { |_, state| state["from"].to_date }.max - 1.day+ from_date = [ to_date - 364.days, oldest_available_date ].max+ pending.select! { |_, state| state["from"].to_date > to_date }+ statements = IbkrItem::ReportParser.new(ibkr_provider.download_statement(from_date: from_date, to_date: to_date)).parse[:accounts]++ complete = true+ until pending.empty?+ ibkr_account, state = pending.first+ data = statements.find { |row| row[:ibkr_account_id] == ibkr_account.ibkr_account_id }+ # Done once IBKR's reach is covered, the account did not exist yet, or+ # IBKR answered for another range than the one asked (it ignored fd/td).+ done = from_date == oldest_available_date || data.nil? || data[:statement]["from_date"].to_s.to_date != from_date+ failed_rows = data ? import_history_rows(ibkr_account, data) : []+ if failed_rows.empty? || rows_skipped?(ibkr_account, state, failed_rows)+ save_history_state(ibkr_account, state.merge("from" => from_date.iso8601, "done" => done, "failures" => 0, "row_failures" => 0, "parse_failures" => 0))+ else+ complete = false+ end+ pending.shift+ end+ complete+ rescue => e+ # Never fails the sync. A window IBKR keeps refusing (1003) or answering without+ # statements is given up after MAX_HISTORY_FAILURES syncs, and one whose XML does+ # not parse is skipped after MAX_PARSE_FAILURES; any other error (busy, "try+ # again shortly", network) only stops this one.+ DebugLogEntry.capture(+ category: "provider_sync_error", level: "warn", message: "IBKR history import stopped: #{e.class}: #{e.message}",+ source: self.class.name, provider_key: "ibkr", family: ibkr_item.family, metadata: { error_code: e.try(:error_code) }.compact+ )+ return skip_unparseable_window(pending, from_date, to_date) if e.is_a?(IbkrItem::ReportParser::ParseError) && e.cause.is_a?(Nokogiri::XML::SyntaxError)+ return false unless no_statements_error?(e)++ pending&.each do |ibkr_account, state|+ failures = state["failures"].to_i + 1+ save_history_state(ibkr_account, state.merge("failures" => failures, "done" => failures >= MAX_HISTORY_FAILURES))+ end+ false+ end++ # IBKR refused the window (1003), or answered it with well-formed XML that+ # holds no statements.+ def no_statements_error?(error)+ return error.error_code.to_s == "1003" if error.respond_to?(:error_code)++ error.is_a?(IbkrItem::ReportParser::ParseError)+ end++ # Rows that keep failing are given up after MAX_HISTORY_FAILURES syncs, so+ # they don't hold back the rest of the window or the older ones. Until+ # then the account keeps the window, and the next sync fetches it again.+ def rows_skipped?(ibkr_account, state, failed_rows)+ row_failures = state["row_failures"].to_i + 1+ skipped = row_failures >= MAX_HISTORY_FAILURES+ save_history_state(ibkr_account, state.merge("row_failures" => row_failures)) unless skipped++ DebugLogEntry.capture(+ category: "provider_sync_error", level: skipped ? "error" : "warn",+ message: "IBKR history rows #{skipped ? "skipped" : "to retry"} after #{row_failures} failed imports: #{failed_rows.join(", ")}",+ source: self.class.name, provider_key: "ibkr", account_provider: ibkr_account.account_provider, family: ibkr_item.family,+ metadata: { ibkr_account_id: ibkr_account.ibkr_account_id, failed_rows: failed_rows }+ )+ skipped+ end++ # A window whose XML still does not parse after MAX_PARSE_FAILURES syncs+ # is skipped, and the walk goes on with the older ones.+ def skip_unparseable_window(pending, from_date, to_date)+ pending.each do |ibkr_account, state|+ parse_failures = state["parse_failures"].to_i + 1+ if parse_failures < MAX_PARSE_FAILURES+ save_history_state(ibkr_account, state.merge("parse_failures" => parse_failures))+ next+ end++ DebugLogEntry.capture(+ category: "provider_sync_error", level: "error",+ message: "IBKR history window #{from_date}..#{to_date} skipped: its XML did not parse in #{parse_failures} syncs",+ source: self.class.name, provider_key: "ibkr", account_provider: ibkr_account.account_provider, family: ibkr_item.family,+ metadata: { ibkr_account_id: ibkr_account.ibkr_account_id }+ )+ save_history_state(ibkr_account, state.merge("from" => from_date.iso8601, "done" => from_date == oldest_available_date,+ "failures" => 0, "row_failures" => 0, "parse_failures" => 0))+ end+ false+ end++ # Kept per linked Sure account, so linking another one walks back again.+ # nil when there is nothing left to fetch or the account is not synced.+ def history_state(ibkr_account)+ account = ibkr_account.current_account+ return if account.nil? || account.pending_deletion? || account.disabled?++ metadata = ibkr_account.institution_metadata.to_h+ state = metadata["history"].to_h+ state = { "account_id" => account.id, "from" => metadata["statement_from_date"] } unless state["account_id"] == account.id+ state if state["from"].present? && !state["done"] && state["from"].to_date > oldest_available_date+ end++ def oldest_available_date+ Date.current.beginning_of_year - 4.years+ end++ # The window's trades and cash, through the same processor as the+ # regular statement; the stored payload stays the current statement's.+ def import_history_rows(ibkr_account, data)+ ibkr_account.raw_activities_payload = data.slice(:trades, :cash_transactions)+ IbkrAccount::ActivitiesProcessor.new(ibkr_account).process[:failed_rows]+ ensure+ ibkr_account.restore_attributes([ :raw_activities_payload ])+ end++ def save_history_state(ibkr_account, state)+ ibkr_account.update!(institution_metadata: ibkr_account.institution_metadata.to_h.merge("history" => state))+ endenddiff --git a/app/models/provider/ibkr_flex.rb b/app/models/provider/ibkr_flex.rbindex 16da5b8037..1f73556697 100644--- a/app/models/provider/ibkr_flex.rb+++ b/app/models/provider/ibkr_flex.rb@@ -23,9 +23,15 @@ class Provider::IbkrFlexMAX_RETRIES = 3INITIAL_RETRY_DELAY = 2MAX_RETRY_DELAY = 30- POLL_INTERVAL = 3MAX_POLL_ATTEMPTS = 20PENDING_ERROR_CODES = %w[1004 1019].freeze+ # IBKR allows 10 requests a minute per token, so polling waits REQUEST_INTERVAL+ # (20 attempts, no less time than before). 1018 says that limit was hit,+ # 1001 and 1009 that the server is busy: all three mean "try again shortly".+ REQUEST_INTERVAL = 6+ THROTTLED_ERROR_CODES = %w[1001 1009 1018].freeze+ THROTTLE_RETRY_DELAY = 10+ MAX_THROTTLE_RETRIES = 3RETRYABLE_ERRORS = [SocketError,@@ -47,19 +53,20 @@ class Provider::IbkrFlex@token = token.to_s.stripend- def download_statement- reference_code = request_reference_code+ # Without dates IBKR uses the period saved on the query; fd/td (yyyymmdd)+ # ask for that range instead, at most 365 days.+ def download_statement(from_date: nil, to_date: nil)+ query = { t: token, q: query_id, v: 3 }+ query.merge!(fd: from_date.strftime("%Y%m%d"), td: to_date.strftime("%Y%m%d")) if from_date++ reference_code = request_reference_code(query)poll_statement(reference_code)endprivate- def request_reference_code- response = with_retries("SendRequest") do- self.class.get("/SendRequest", query: { t: token, q: query_id, v: 3 })- end-- xml = parse_xml(response.body)+ def request_reference_code(query)+ response, xml = flex_get("SendRequest", query)error = response_error(xml, response)raise error if error@@ -74,18 +81,13 @@ class Provider::IbkrFlexloop doattempts += 1- response = with_retries("GetStatement") do- self.class.get("/GetStatement", query: { t: token, q: reference_code, v: 3 })- end-- xml = parse_xml(response.body)+ response, xml = flex_get("GetStatement", { t: token, q: reference_code, v: 3 })return response.body if xml.at_xpath("//FlexQueryResponse")error = response_error(xml, response)if error.is_a?(ApiError) && PENDING_ERROR_CODES.include?(error.error_code.to_s)raise ApiError.new("IBKR Flex statement is still being generated.", error_code: error.error_code) if attempts >= MAX_POLL_ATTEMPTS- sleep(POLL_INTERVAL)nextend@@ -93,6 +95,30 @@ class Provider::IbkrFlexendend+ # Every call, network retries included, is spaced REQUEST_INTERVAL from+ # the previous one, which also paces the polling, and retried a few times+ # while IBKR is throttling.+ def flex_get(operation, query)+ throttled = 0+ loop do+ response = with_retries(operation) do+ wait_for_request_slot+ self.class.get("/#{operation}", query: query)+ end+ xml = parse_xml(response.body)+ return [ response, xml ] unless THROTTLED_ERROR_CODES.include?(xml.at_xpath("//ErrorCode")&.text.to_s.strip) && throttled < MAX_THROTTLE_RETRIES++ throttled += 1+ sleep(THROTTLE_RETRY_DELAY)+ end+ end++ def wait_for_request_slot+ wait = @last_request_at && @last_request_at + REQUEST_INTERVAL - Process.clock_gettime(Process::CLOCK_MONOTONIC)+ sleep(wait) if wait&.positive?+ @last_request_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)+ end+def response_error(xml, response)error_code = xml.at_xpath("//ErrorCode")&.text.to_s.strip.presenceerror_message = xml.at_xpath("//ErrorMessage")&.text.to_s.strip.presencediff --git a/config/locales/views/ibkr_items/en.yml b/config/locales/views/ibkr_items/en.ymlindex 40be221d61..3121328d58 100644--- a/config/locales/views/ibkr_items/en.yml+++ b/config/locales/views/ibkr_items/en.yml@@ -34,7 +34,7 @@ en:item_1: Holdings with current prices and quantitiesitem_2: Cost basis per positionitem_3: Trades, dividends, commissions, and cash deposits or withdrawals- warning: Historical activity is limited to the report window of the Flex Query+ warning: Activity older than the Flex Query's period is imported over the next syncs, up to four years backstatus:fetching_accounts: Fetching accounts from Interactive Brokers...no_accounts_found_title: No accounts found.diff --git a/test/models/ibkr_account/processor_test.rb b/test/models/ibkr_account/processor_test.rbindex fd7e50eb03..ae70880c9d 100644--- a/test/models/ibkr_account/processor_test.rb+++ b/test/models/ibkr_account/processor_test.rb@@ -137,4 +137,13 @@ class IbkrAccount::ProcessorTest < ActiveSupport::TestCaseIbkrAccount::Processor.new(@ibkr_account.reload).processassert_equal Date.current, @account.valuations.current_anchor.first.entry.dateend++ test "a failed move of the opening anchor is reported and the sync still completes" do+ Account.any_instance.stubs(:ensure_opening_anchor_precedes_entries).raises(StandardError, "Opening balance date must be before the oldest entry")+ Account.any_instance.expects(:broadcast_sync_complete).once++ assert_difference -> { DebugLogEntry.where(source: "IbkrAccount::Processor", provider_key: "ibkr").count }, 1 do+ IbkrAccount::Processor.new(@ibkr_account).process+ end+ endenddiff --git a/test/models/ibkr_item/importer_history_test.rb b/test/models/ibkr_item/importer_history_test.rbnew file mode 100644index 0000000000..e9c8aeddf4--- /dev/null+++ b/test/models/ibkr_item/importer_history_test.rb@@ -0,0 +1,294 @@+require "test_helper"++class IbkrItem::ImporterHistoryTest < ActiveSupport::TestCase+ fixtures :families, :ibkr_items, :ibkr_accounts, :securities++ # Stands in for Provider::IbkrFlex: answers per requested range and records+ # every call. nil/nil is the query's own period.+ class FakeFlex+ attr_reader :calls++ def initialize(responses)+ @responses = responses+ @calls = []+ end++ def download_statement(from_date: nil, to_date: nil)+ @calls << [ from_date, to_date ]+ response = @responses.fetch([ from_date, to_date ])+ response = response.call if response.respond_to?(:call)+ raise response if response.is_a?(Exception)++ response+ end+ end++ CURRENT = [ nil, nil ].freeze+ WINDOW_1 = [ Date.new(2024, 5, 8), Date.new(2025, 5, 7) ].freeze+ WINDOW_2 = [ Date.new(2023, 5, 9), Date.new(2024, 5, 7) ].freeze+ WINDOW_3 = [ Date.new(2022, 5, 9), Date.new(2023, 5, 8) ].freeze+ WINDOW_4 = [ Date.new(2022, 1, 1), Date.new(2022, 5, 8) ].freeze # IBKR keeps the four previous calendar years++ setup do+ travel_to Time.zone.local(2026, 5, 9, 10)+ @ibkr_item = ibkr_items(:configured_item)+ @ibkr_account = ibkr_accounts(:main_account)+ @account = new_account+ @ibkr_account.ensure_account_provider!(@account)+ @current = file_fixture("ibkr/flex_statement.xml").read # fromDate 2025-05-08+ Security.any_instance.stubs(:import_provider_prices)+ end++ # A quiet year (no trades, cash or NAV rows) does not end the walk.+ test "imports each older window as it is fetched, back to the oldest year IBKR keeps" do+ provider = history_provider++ import(provider)++ assert_equal [ CURRENT, WINDOW_1, WINDOW_2, WINDOW_3, WINDOW_4 ], provider.calls+ assert @account.entries.exists?(external_id: "ibkr_trade_901", source: "ibkr")+ # The stored payload and balance stay the current statement's.+ @ibkr_account.reload+ assert_equal %w[1001 1002], @ibkr_account.raw_activities_payload["trades"].map { |row| row["trade_id"] }+ assert_equal BigDecimal("3351.0"), @ibkr_account.current_balance++ # Once complete, a sync is a single request again.+ import(provider)+ assert_equal [ CURRENT, WINDOW_1, WINDOW_2, WINDOW_3, WINDOW_4, CURRENT ], provider.calls+ end++ test "a statement for another range than the one asked ends the walk" do+ provider = FakeFlex.new(CURRENT => @current, WINDOW_1 => @current)++ 2.times { import(provider) }++ assert_equal [ CURRENT, WINDOW_1, CURRENT ], provider.calls+ end++ test "backfilled history older than the default opening anchor moves the anchor before it" do+ @ibkr_account.account_provider.destroy!+ account = Account.create_from_ibkr_account(@ibkr_account.reload)+ @ibkr_account.ensure_account_provider!(account)+ assert_equal Date.new(2024, 5, 9), account.reload.opening_anchor_date++ deposit = %(<CashTransaction transactionID="7001" type="Deposits/Withdrawals" amount="10000.00" currency="CHF" fxRateToBase="1" reportDate="2023-06-01" />)+ provider = FakeFlex.new(CURRENT => window_xml(Date.new(2025, 5, 8), Date.new(2026, 5, 8), nav_date: "2026-05-08", total: "10000.00", cash: "10000.00"),+ WINDOW_1 => window_xml(*WINDOW_1), WINDOW_2 => window_xml(*WINDOW_2, cash_transaction: deposit),+ WINDOW_3 => window_xml(*WINDOW_3), WINDOW_4 => window_xml(*WINDOW_4))+ import(provider)+ @ibkr_item.reload.process_accounts++ account = Account.find(account.id)+ Balance::Materializer.new(account, strategy: :reverse).materialize_balances+ balances = account.balances.where(currency: "CHF").index_by(&:date)+ assert_in_delta 10000, balances[Date.new(2024, 1, 1)].balance, 0.01, "after the 2023-06-01 deposit the account held 10k"+ assert_in_delta 0, balances[Date.new(2023, 6, 1)].start_balance, 0.01, "the day of the deposit starts from zero"+ end++ # Progress is recorded only once the window's rows are imported, not when it is fetched.+ test "a window is imported in the sync that fetched it, even if that sync stops before processing" do+ import(history_provider)+ import(FakeFlex.new(CURRENT => @current))+ @ibkr_item.process_accounts++ assert @account.entries.exists?(external_id: "ibkr_trade_901")+ end++ test "a failing window never fails the sync, is retried, and is given up only after repeated permanent errors" do+ provider = FakeFlex.new(CURRENT => @current, WINDOW_1 => window_xml(*WINDOW_1, trade_id: "901", nav_date: "2024-06-03"),+ WINDOW_2 => OpenSSL::SSL::SSLError.new("SSL_read: unexpected eof"))++ assert_equal true, import(provider)[:success]+ assert @account.entries.exists?(external_id: "ibkr_trade_901"), "the window before the failure is kept"+ assert DebugLogEntry.where(source: "IbkrItem::Importer", provider_key: "ibkr").exists?++ # Busy, "try again shortly", unknown or code-less (HTML page) errors only stop this sync, however often.+ [ "1019", "1021", "1005", "1018", "9999", nil ].each do |code|+ error = Provider::IbkrFlex::ApiError.new("Please try again shortly.", error_code: code)+ IbkrItem::Importer::MAX_HISTORY_FAILURES.times { import(FakeFlex.new(CURRENT => @current, WINDOW_2 => error)) }+ end++ unavailable = Provider::IbkrFlex::ApiError.new("Statement is not available.", error_code: "1003")+ provider = FakeFlex.new(CURRENT => @current, WINDOW_2 => unavailable)+ (IbkrItem::Importer::MAX_HISTORY_FAILURES + 1).times { import(provider) }++ assert_equal [ CURRENT, WINDOW_2 ] * IbkrItem::Importer::MAX_HISTORY_FAILURES + [ CURRENT ], provider.calls+ end++ test "a window IBKR answers without statements is given up eventually" do+ empty = "<FlexQueryResponse queryName=\"Sure Test\" type=\"AF\"><FlexStatements count=\"0\" /></FlexQueryResponse>"+ provider = FakeFlex.new(CURRENT => @current, WINDOW_1 => empty)++ 6.times { import(provider) }++ assert_operator provider.calls.count(WINDOW_1), :<=, IbkrItem::Importer::MAX_HISTORY_FAILURES,+ "WINDOW_1 requested #{provider.calls.count(WINDOW_1)} times in 6 syncs"+ end++ test "a cut-off statement is retried, never counted as one IBKR has no statements for" do+ truncated = window_xml(*WINDOW_1, trade_id: "901", nav_date: "2024-06-03")[0, 200]+ provider = FakeFlex.new(CURRENT => @current, WINDOW_1 => truncated)++ (IbkrItem::Importer::MAX_HISTORY_FAILURES + 1).times { import(provider) }+ assert_equal [ CURRENT, WINDOW_1 ] * (IbkrItem::Importer::MAX_HISTORY_FAILURES + 1), provider.calls++ import(history_provider)+ assert @account.entries.exists?(external_id: "ibkr_trade_901", source: "ibkr")+ end++ test "a window whose rows fail to import is fetched again by the next sync" do+ Account::ProviderImportAdapter.any_instance.stubs(:import_trade).raises(ActiveRecord::ConnectionNotEstablished, "connection lost")+ provider = history_provider+ assert_equal true, import(provider)[:success]+ assert_equal [ CURRENT, WINDOW_1 ], provider.calls+ assert DebugLogEntry.where(source: "IbkrItem::Importer", provider_key: "ibkr").exists?++ Account::ProviderImportAdapter.any_instance.unstub(:import_trade)+ provider = history_provider+ import(provider)++ assert_equal [ CURRENT, WINDOW_1, WINDOW_2, WINDOW_3, WINDOW_4 ], provider.calls+ assert @account.entries.exists?(external_id: "ibkr_trade_901", source: "ibkr")+ end++ test "a row that keeps failing is skipped after repeated syncs and the walk goes on" do+ bad = %(<CashTransaction type="Deposits/Withdrawals" transactionID="77" amount="100" currency="CHF" fxRateToBase="1" reportDate="2024-06-03" />)+ Account::ProviderImportAdapter.any_instance.stubs(:import_transaction).raises(ActiveRecord::RecordInvalid.new(Entry.new))+ provider = history_provider(WINDOW_1 => window_xml(*WINDOW_1, trade_id: "901", nav_date: "2024-06-03", cash_transaction: bad))++ (IbkrItem::Importer::MAX_HISTORY_FAILURES + 2).times { import(provider) }++ assert_equal IbkrItem::Importer::MAX_HISTORY_FAILURES, provider.calls.count(WINDOW_1)+ assert_equal 1, provider.calls.count(WINDOW_4), "older windows are fetched once the row is skipped: #{provider.calls.inspect}"+ assert @account.entries.exists?(external_id: "ibkr_trade_901", source: "ibkr"), "the window's other rows are kept"+ skipped = DebugLogEntry.where(source: "IbkrItem::Importer", provider_key: "ibkr", level: "error").sole+ assert_includes skipped.message, "cash 77"+ end++ test "a row that keeps failing in one sub-account holds the others back only until it is skipped" do+ other_account = families(:dylan_family).accounts.create!(name: "IBKR Retirement", balance: 0, cash_balance: 0, currency: "USD",+ accountable: Investment.new(subtype: "brokerage"))+ ibkr_accounts(:secondary_account).ensure_account_provider!(other_account)+ bad = %(<CashTransaction type="Deposits/Withdrawals" transactionID="77" amount="100" currency="CHF" fxRateToBase="1" reportDate="2024-06-03" />)+ Account::ProviderImportAdapter.any_instance.stubs(:import_transaction).raises(ActiveRecord::RecordInvalid.new(Entry.new))+ provider = history_provider(+ WINDOW_1 => combined_xml(window_xml(*WINDOW_1, cash_transaction: bad),+ window_xml(*WINDOW_1, trade_id: "902", nav_date: "2024-06-03", account_id: "U7654321")),+ WINDOW_2 => combined_xml(window_xml(*WINDOW_2), window_xml(*WINDOW_2, trade_id: "802", nav_date: "2023-06-01", account_id: "U7654321"))+ )++ import(provider)+ assert other_account.entries.exists?(external_id: "ibkr_trade_902"), "the other sub-account's rows are imported in the first sync"++ (IbkrItem::Importer::MAX_HISTORY_FAILURES + 1).times { import(provider) }++ assert_equal IbkrItem::Importer::MAX_HISTORY_FAILURES, provider.calls.count(WINDOW_1)+ assert other_account.entries.exists?(external_id: "ibkr_trade_802"), "the other sub-account walks back too: #{provider.calls.inspect}"+ end++ test "a window whose XML never parses is skipped after more syncs than a refused one" do+ bad = window_xml(*WINDOW_1, trade_id: "901", nav_date: "2024-06-03").sub("<OpenPositions />", "<OpenPositions>&</OpenPositions>")+ provider = history_provider(WINDOW_1 => bad)++ (IbkrItem::Importer::MAX_PARSE_FAILURES + 1).times { import(provider) }++ assert_equal IbkrItem::Importer::MAX_PARSE_FAILURES, provider.calls.count(WINDOW_1)+ assert_equal 1, provider.calls.count(WINDOW_2), "older windows are fetched once it is skipped: #{provider.calls.inspect}"+ end++ test "the next sync resumes after the last imported window" do+ throttled = Provider::IbkrFlex::ApiError.new("Too many requests", error_code: "1018")+ import(FakeFlex.new(CURRENT => @current, WINDOW_1 => window_xml(*WINDOW_1, nav_date: "2024-06-03"), WINDOW_2 => throttled))++ provider = FakeFlex.new(CURRENT => @current, WINDOW_2 => window_xml(*WINDOW_2, trade_id: "801", nav_date: "2023-06-01"),+ WINDOW_3 => window_xml(*WINDOW_3), WINDOW_4 => window_xml(*WINDOW_4))+ import(provider)++ assert_equal [ CURRENT, WINDOW_2, WINDOW_3, WINDOW_4 ], provider.calls+ assert @account.entries.exists?(external_id: "ibkr_trade_801")+ end++ test "no new window is started once the time budget is spent" do+ provider = history_provider(CURRENT => -> { travel IbkrItem::Importer::HISTORY_TIME_BUDGET + 1.second; @current })++ import(provider)++ assert_equal [ CURRENT ], provider.calls+ end++ test "a disabled account is not walked back until it is enabled again" do+ @account.disable!+ provider = history_provider+ import(provider)+ assert_equal [ CURRENT ], provider.calls++ @account.enable!+ import(history_provider)++ assert @account.entries.exists?(external_id: "ibkr_trade_901")+ end++ test "linking the IBKR account to another Sure account walks its history back again" do+ import(history_provider)+ @ibkr_account.account_provider.destroy!+ fresh = new_account(name: "IBKR relinked")+ @ibkr_account.reload.ensure_account_provider!(fresh)++ import(history_provider)++ assert fresh.entries.exists?(external_id: "ibkr_trade_901")+ end++ test "accounts that are not linked are not walked back" do+ @ibkr_account.account_provider.destroy!+ provider = FakeFlex.new(CURRENT => @current)++ import(provider)++ assert_equal [ CURRENT ], provider.calls+ end++ private++ def new_account(name: "IBKR Investment")+ families(:dylan_family).accounts.create!(name: name, balance: 0, cash_balance: 0, currency: "CHF",+ accountable: Investment.new(subtype: "brokerage"))+ end++ def history_provider(overrides = {})+ FakeFlex.new({ CURRENT => @current, WINDOW_1 => window_xml(*WINDOW_1, trade_id: "901", nav_date: "2024-06-03"),+ WINDOW_2 => window_xml(*WINDOW_2), WINDOW_3 => window_xml(*WINDOW_3),+ WINDOW_4 => window_xml(*WINDOW_4) }.merge(overrides))+ end++ def import(provider)+ IbkrItem::Importer.new(@ibkr_item.reload, ibkr_provider: provider).import+ end++ def window_xml(from_date, to_date, trade_id: nil, nav_date: nil, total: "1000.00", cash: nil, cash_transaction: nil, account_id: "U1234567")+ trade = %(<Trade assetCategory="STK" tradeID="#{trade_id}" transactionID="#{trade_id}a" conid="265598" symbol="AAPL" quantity="1" tradePrice="120.00" currency="USD" fxRateToBase="0.90" buySell="BUY" tradeDate="#{nav_date}" ibCommission="-1.00" ibCommissionCurrency="USD" />) if trade_id+ nav = %(<EquitySummaryByReportDateInBase currency="CHF" reportDate="#{nav_date}" total="#{total}" />) if nav_date+ cash_report = %(<CashReport><CashReportCurrency currency="BASE_SUMMARY" endingCash="#{cash}" /><CashReportCurrency currency="CHF" endingCash="#{cash}" /></CashReport>) if cash++ <<~XML+ <FlexQueryResponse queryName="Sure Test" type="AF">+ <FlexStatements count="1">+ <FlexStatement accountId="#{account_id}" fromDate="#{from_date.iso8601}" toDate="#{to_date.iso8601}">+ <AccountInformation accountId="#{account_id}" currency="CHF" />+ #{cash_report}+ <EquitySummaryInBase>#{nav}</EquitySummaryInBase>+ <OpenPositions />+ <Trades>#{trade}</Trades>+ <CashTransactions>#{cash_transaction}</CashTransactions>+ </FlexStatement>+ </FlexStatements>+ </FlexQueryResponse>+ XML+ end++ # One response holding the statements of several sub-accounts.+ def combined_xml(first, *others)+ statements = others.map { |xml| xml[%r{<FlexStatement .*</FlexStatement>}m] }+ first.sub("</FlexStatements>", "#{statements.join}</FlexStatements>").sub(%(count="1"), %(count="#{others.size + 1}"))+ end+enddiff --git a/test/models/provider/ibkr_flex_test.rb b/test/models/provider/ibkr_flex_test.rbnew file mode 100644index 0000000000..3b4a5163ef--- /dev/null+++ b/test/models/provider/ibkr_flex_test.rb@@ -0,0 +1,97 @@+require "test_helper"++class Provider::IbkrFlexTest < ActiveSupport::TestCase+ BASE_URL = "https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService".freeze+ SUCCESS = "<FlexStatementResponse><Status>Success</Status><ReferenceCode>REF1</ReferenceCode></FlexStatementResponse>".freeze+ THROTTLED = "<FlexStatementResponse><Status>Fail</Status><ErrorCode>1018</ErrorCode>" \+ "<ErrorMessage>Too many requests have been made from this token. Please try again shortly.</ErrorMessage></FlexStatementResponse>".freeze+ STATEMENT = "<FlexQueryResponse><FlexStatements count=\"0\" /></FlexQueryResponse>".freeze++ setup do+ @provider = Provider::IbkrFlex.new(query_id: "QUERY123", token: "TOKEN123")+ @provider.stubs(:sleep)+ stub_request(:get, "#{BASE_URL}/GetStatement").with(query: hash_including("q" => "REF1")).to_return(body: STATEMENT)+ end++ test "uses the query's saved period when no dates are given" do+ send_request = stub_request(:get, "#{BASE_URL}/SendRequest")+ .with(query: { "t" => "TOKEN123", "q" => "QUERY123", "v" => "3" })+ .to_return(body: SUCCESS)++ assert_equal STATEMENT, @provider.download_statement+ assert_requested send_request, times: 1+ end++ test "requests a date range as fd and td in yyyymmdd" do+ send_request = stub_request(:get, "#{BASE_URL}/SendRequest")+ .with(query: { "t" => "TOKEN123", "q" => "QUERY123", "v" => "3", "fd" => "20240508", "td" => "20250507" })+ .to_return(body: SUCCESS)++ @provider.download_statement(from_date: Date.new(2024, 5, 8), to_date: Date.new(2025, 5, 7))++ assert_requested send_request, times: 1+ end++ test "waits and retries when IBKR says the token made too many requests" do+ send_request = stub_request(:get, "#{BASE_URL}/SendRequest")+ .with(query: hash_including("q" => "QUERY123"))+ .to_return({ body: THROTTLED }, { body: SUCCESS })+ @provider.expects(:sleep).with(Provider::IbkrFlex::THROTTLE_RETRY_DELAY).once++ assert_equal STATEMENT, @provider.download_statement+ assert_requested send_request, times: 2+ end++ test "a throttled GetStatement is retried too" do+ stub_request(:get, "#{BASE_URL}/SendRequest").with(query: hash_including("q" => "QUERY123")).to_return(body: SUCCESS)+ stub_request(:get, "#{BASE_URL}/GetStatement").with(query: hash_including("q" => "REF1"))+ .to_return({ body: THROTTLED }, { body: STATEMENT })++ assert_equal STATEMENT, @provider.download_statement+ end++ # 10 requests a minute per token, whatever IBKR answers.+ test "calls are spaced to IBKR's per-token limit" do+ sleeps = []+ @provider.stubs(:sleep).with { |seconds| sleeps << seconds }+ stub_request(:get, "#{BASE_URL}/SendRequest").with(query: hash_including("q" => "QUERY123")).to_return(body: SUCCESS)++ 6.times { |i| @provider.download_statement(from_date: Date.new(2024 - i, 1, 1), to_date: Date.new(2024 - i, 12, 31)) }++ assert_requested :get, /FlexWebService/, times: 12+ assert_operator sleeps.sum, :>=, 60, "12 requests in #{sleeps.sum}s"+ end++ test "a network retry is spaced to IBKR's per-token limit too" do+ sleeps = []+ @provider.stubs(:sleep).with { |seconds| sleeps << seconds }+ stub_request(:get, "#{BASE_URL}/SendRequest").with(query: hash_including("q" => "QUERY123"))+ .to_raise(EOFError).then.to_return(body: SUCCESS)++ assert_equal STATEMENT, @provider.download_statement++ assert_requested :get, /FlexWebService/, times: 3+ assert_operator sleeps.sum, :>=, 2 * Provider::IbkrFlex::REQUEST_INTERVAL - 1, "3 requests in #{sleeps.sum}s"+ end++ test "gives up on throttling after a bounded number of retries" do+ stub_request(:get, "#{BASE_URL}/SendRequest")+ .with(query: hash_including("q" => "QUERY123"))+ .to_return(body: THROTTLED)++ error = assert_raises(Provider::IbkrFlex::ApiError) { @provider.download_statement }++ assert_equal "1018", error.error_code+ assert_requested :get, "#{BASE_URL}/SendRequest", query: hash_including("q" => "QUERY123"),+ times: Provider::IbkrFlex::MAX_THROTTLE_RETRIES + 1+ end++ # A maintenance page or a cut-off transfer carries no IBKR code, so history import retries it+ test "an HTML page or a cut-off GetStatement raises an ApiError without an error code" do+ stub_request(:get, "#{BASE_URL}/SendRequest").with(query: hash_including("q" => "QUERY123")).to_return(body: SUCCESS)+ stub_request(:get, "#{BASE_URL}/GetStatement").with(query: hash_including("q" => "REF1"))+ .to_return({ body: "<!DOCTYPE html><html><body>Maintenance</body></html>" }).then.to_raise(EOFError)++ 2.times { assert_nil assert_raises(Provider::IbkrFlex::ApiError) { @provider.download_statement }.error_code }+ end+end