The personal finance app for everyone (by everyone)
Ruby
SnapTrade: clear positions the broker stopped reporting (#5026)
arnaurodondevd5c7dfb86410
diff --git a/app/models/snaptrade_account/holdings_processor.rb b/app/models/snaptrade_account/holdings_processor.rbindex a1a71aec96..b47256b54e 100644--- a/app/models/snaptrade_account/holdings_processor.rb+++ b/app/models/snaptrade_account/holdings_processor.rb@@ -9,6 +9,7 @@ class SnaptradeAccount::HoldingsProcessorreturn unless account.present?holdings_data = @snaptrade_account.raw_holdings_payload+ failed = falseif holdings_data.present?Rails.logger.info "SnaptradeAccount::HoldingsProcessor - Processing #{holdings_data.size} holdings"@@ -25,13 +26,20 @@ class SnaptradeAccount::HoldingsProcessorholdings_data.each_with_index do |holding_data, idx|Rails.logger.info "SnaptradeAccount::HoldingsProcessor - Processing holding #{idx + 1}/#{holdings_data.size}"- process_holding(holding_data.with_indifferent_access)+ failed = true unless process_holding(holding_data.with_indifferent_access)rescue => e+ failed = trueRails.logger.error "SnaptradeAccount::HoldingsProcessor - Failed to process holding #{idx + 1}: #{e.class} - #{e.message}"Rails.logger.error e.backtrace.first(5).join("\n") if e.backtraceendend+ # A row that failed or was skipped must not read as a closed position, nor a+ # list this sync didn't fetch, nor an empty list SnapTrade's own total contradicts.+ if !failed && @snaptrade_account.last_holdings_sync&.after?(1.hour.ago)+ holdings_data.blank? && positions_in_total? ? capture_kept_empty_snapshot : zero_vanished_positions+ end+# Always run, even with no security holdings — secondary-currency cash# should still be surfaced (issue #1809).process_cash_holdings@@ -39,6 +47,51 @@ class SnaptradeAccount::HoldingsProcessorprivate+ # The latest provider snapshot is the account's current holdings, so a+ # position the broker no longer reports (closed, expired) would stay+ # current forever. Write it a zero row today instead.+ def zero_vanished_positions+ provider_id = @snaptrade_account.account_provider&.id+ vanished_positions.find_each do |h|+ security = h.provider_security || h.security+ # The adapter matches a row without external_id by security, date and+ # currency alone, so never zero another provider's row for today. Rows without a+ # provider are Sure's own materialized ones, which the sync rewrites anyway.+ next if account.holdings.where(security: [ security, h.security ], date: Date.current, currency: h.currency)+ .where.not(account_provider_id: [ nil, provider_id ]).exists?++ # The materializer may have written today's row on the user's remapped security.+ account.holdings.where(security: h.security, date: Date.current, currency: h.currency, account_provider_id: nil).delete_all+ import_adapter.import_holding(security: security, quantity: 0, amount: 0, currency: h.currency,+ date: Date.current, price: h.price, account_provider_id: provider_id, source: "snaptrade", delete_future_holdings: false)+ end+ end++ def vanished_positions+ provider_id = @snaptrade_account.account_provider&.id or return Holding.none+ scope = account.holdings.where(account_provider_id: provider_id, external_id: nil)+ scope.where(date: scope.maximum(:date)).where.not(qty: 0).where.not(security_id: @imported.to_a)+ end++ def capture_kept_empty_snapshot+ # holdings_unavailable accounts always report an empty list; only log a surprising one.+ return if @snaptrade_account.institution_metadata&.dig("sync_status", "holdings", "holdings_unavailable")+ return unless vanished_positions.exists?++ Rails.logger.warn("SnapTrade: kept positions for account #{account.id}: the positions list is empty but the account total still reports holdings")+ end++ # Non-cash value in the account total (or no total) means positions exist --+ # for a few days only: value SnapTrade can't list (filtered futures,+ # unsupported assets, cash in other currencies) must not pin a sold position.+ def positions_in_total?+ return true if @snaptrade_account.institution_metadata&.dig("sync_status", "holdings", "holdings_unavailable")+ last = account.holdings.where(account_provider_id: @snaptrade_account.account_provider&.id, external_id: nil).maximum(:date)+ return false if last && last < 3.days.ago.to_date+ total = @snaptrade_account.current_balance or return true+ (total - @snaptrade_account.cash_balance.to_d).abs >= 0.01+ end+# Surface cash held in currencies other than the account's primary currency# as synthetic cash holdings (issue #1809). The primary currency stays in# account.cash_balance; without this, SnapTrade's secondary-currency cash@@ -92,7 +145,13 @@ class SnaptradeAccount::HoldingsProcessorticker = symbol_data["raw_symbol"] || symbol_data[:raw_symbol]end- return if ticker.blank?+ # A cash row carries no symbol; any other row without one is unreadable.+ return symbol_data[:kind].to_s.casecmp?("cash") if ticker.blank?++ # Holdings can't be negative; a short only counts in the account total.+ quantity = parse_decimal(data["units"] || data[:units])+ return if quantity.nil?+ return true if quantity.negative?Rails.logger.info "SnaptradeAccount::HoldingsProcessor - Processing holding for ticker: #{ticker}"@@ -102,10 +161,8 @@ class SnaptradeAccount::HoldingsProcessorsecurity = resolve_security(ticker, symbol_data, account: account, account_provider_id: @snaptrade_account.account_provider&.id, provider_row: true)return unless security- # Parse values- quantity = parse_decimal(data["units"] || data[:units])price = parse_decimal(data["price"] || data[:price])- return if quantity.nil? || price.nil?+ return if price.nil?# Calculate amountamount = quantity * price@@ -131,6 +188,7 @@ class SnaptradeAccount::HoldingsProcessorsource: "snaptrade",delete_future_holdings: false)+ (@imported ||= []) << holding.security_id# Store cost basis if available. Both fields are per-share, which is# what update_holding_cost_basis expects — unlike the identically named@@ -140,6 +198,7 @@ class SnaptradeAccount::HoldingsProcessorif avg_price.present?update_holding_cost_basis(holding&.security || security, avg_price)end+ trueenddef update_holding_cost_basis(security, avg_cost)diff --git a/app/models/snaptrade_account/processor.rb b/app/models/snaptrade_account/processor.rbindex 27e88e77a5..8c9c84ae7b 100644--- a/app/models/snaptrade_account/processor.rb+++ b/app/models/snaptrade_account/processor.rb@@ -21,14 +21,9 @@ class SnaptradeAccount::Processorholdings_count = snaptrade_account.raw_holdings_payload&.size || 0Rails.logger.info "SnaptradeAccount::Processor - Holdings payload has #{holdings_count} items"- # Run the holdings processor when there are security holdings OR- # non-primary-currency cash to surface as synthetic cash holdings (#1809).- if snaptrade_account.raw_holdings_payload.present? || snaptrade_account.non_primary_cash_entries.any?- Rails.logger.info "SnaptradeAccount::Processor - Processing holdings..."- SnaptradeAccount::HoldingsProcessor.new(snaptrade_account).process- else- Rails.logger.warn "SnaptradeAccount::Processor - No holdings payload to process"- end+ # Always run: an empty payload can clear sold positions, and non-primary+ # cash is surfaced as synthetic cash holdings (#1809).+ SnaptradeAccount::HoldingsProcessor.new(snaptrade_account).process# Process activities (trades, dividends, etc.)activities_count = snaptrade_account.raw_activities_payload&.size || 0diff --git a/test/models/snaptrade_account_processor_test.rb b/test/models/snaptrade_account_processor_test.rbindex abb3e17311..7449b45036 100644--- a/test/models/snaptrade_account_processor_test.rb+++ b/test/models/snaptrade_account_processor_test.rb@@ -234,6 +234,169 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("100"), @snaptrade_account.cash_equivalent_position_value("USD")end+ test "an empty snapshot clears positions the broker stopped reporting" do+ travel_to(Date.new(2026, 12, 18)) { sync_positions!([ stock_position ]) }+ travel_to(Date.new(2026, 12, 28)) { sync_positions!([]) }++ assert_empty current_tickers+ end++ test "a position closed between two syncs on the same day leaves current holdings" do+ sync_positions!([ stock_position, stock_position(securities(:msft).ticker) ])+ sync_positions!([ stock_position, stock_position(securities(:msft).ticker, units: "-5") ]) # now short: no holding++ assert_equal [ securities(:aapl).ticker ], current_tickers+ end++ test "a position that fails to import is not cleared" do+ travel_to(1.day.ago) { sync_positions!([ stock_position ]) }+ SnaptradeAccount::HoldingsProcessor.any_instance.stubs(:process_holding).raises(StandardError)+ sync_positions!([ stock_position ])++ assert_equal [ securities(:aapl).ticker ], current_tickers+ end++ test "a position skipped for a null units or price is not cleared" do+ [ { "price" => nil }, { "units" => nil } ].each do |gap|+ travel_to(1.day.ago) { sync_positions!([ stock_position ]) }+ sync_positions!([ stock_position.merge(gap) ])++ assert_equal [ securities(:aapl).ticker ], current_tickers+ end+ end++ test "an empty snapshot is not trusted while the account total holds non-cash value" do+ travel_to(1.day.ago) { sync_positions!([ stock_position ]) }+ sync_positions!([], total: 2500)++ assert_equal [ securities(:aapl).ticker ], current_tickers+ assert_not @account.holdings.exists?(qty: 0)+ end++ test "an empty snapshot is trusted after 3 days whatever the total" do+ usd_only = [ { "currency" => { "code" => "USD" }, "cash" => 1000 } ]+ # Unlisted futures value, cents of unavailable cash, no total, CAD total vs USD cash+ [ { total: 1000.37 }, { total: 1000.42 }, { total: nil }, { total: 1360, currency: "CAD", raw_balances_payload: usd_only } ].each_with_index do |shape, i|+ travel_to(Date.new(2026, 12, 18) + i.months) { sync_positions!([ stock_position ], **shape) }+ travel_to(Date.new(2026, 12, 21) + i.months) { sync_positions!([], **shape) }+ assert_equal [ securities(:aapl).ticker ], current_tickers, shape.inspect++ travel_to(Date.new(2026, 12, 22) + i.months) { sync_positions!([], **shape) }+ assert_empty current_tickers, shape.inspect+ end+ end++ test "an empty snapshot does not clear positions on an account SnapTrade flags holdings_unavailable" do+ meta = { "sync_status" => { "holdings" => { "holdings_unavailable" => true } } }+ travel_to(Date.new(2026, 12, 18)) { sync_positions!([ stock_position ]) }+ travel_to(Date.new(2026, 12, 28)) { sync_positions!([], institution_metadata: meta) }++ assert_equal [ securities(:aapl).ticker ], current_tickers+ end++ test "a positions list this sync did not fetch does not clear positions" do+ travel_to(Date.new(2026, 12, 18)) { sync_positions!([ stock_position ]) }+ travel_to(Date.new(2026, 12, 28)) { sync_positions!([], last_holdings_sync: 2.hours.ago) }++ assert_equal [ securities(:aapl).ticker ], current_tickers+ end++ test "a row without a symbol that is not cash does not clear the other positions" do+ sync_positions!([ stock_position, stock_position(securities(:msft).ticker) ])+ sync_positions!([ stock_position, { "instrument" => { "kind" => "stock" }, "units" => "5", "price" => "300", "currency" => "USD" } ])++ assert_equal [ securities(:aapl).ticker, securities(:msft).ticker ].sort, current_tickers+ end++ test "a cash row without a symbol still lets sold positions clear" do+ sync_positions!([ stock_position, stock_position(securities(:msft).ticker) ])+ sync_positions!([ stock_position, { "instrument" => { "kind" => "cash", "code" => "USD" }, "units" => "1", "price" => "1", "currency" => "USD" } ])++ assert_equal [ securities(:aapl).ticker ], current_tickers+ end++ test "clearing a sold position leaves another source's row for the same security today" do+ travel_to(1.day.ago) { sync_positions!([ stock_position ]) }+ plaid = AccountProvider.create!(account: @account, provider: plaid_accounts(:one))+ other = @account.holdings.create!(security: securities(:aapl), date: Date.current, currency: "USD", qty: 5, price: 150, amount: 750,+ account_provider_id: plaid.id)+ sync_positions!([])++ assert_equal 5, other.reload.qty+ end++ test "an empty list kept against the account total is logged for support" do+ travel_to(1.day.ago) { sync_positions!([ stock_position ]) }++ Rails.logger.stubs(:warn)+ Rails.logger.expects(:warn).with(regexp_matches(/kept positions/)).at_least_once+ sync_positions!([], total: 2500)+ assert_equal [ securities(:aapl).ticker ], current_tickers+ end++ test "a calculated holding without a provider does not stop a sold position from clearing" do+ travel_to(1.day.ago) { sync_positions!([ stock_position ]) }+ sync_positions!([], total: 2500) # kept: the total still reports holdings+ @account.holdings.create!(security: securities(:aapl), date: Date.current, currency: "USD", qty: 10, price: 150, amount: 1500)+ sync_positions!([])++ assert_empty current_tickers+ end++ test "clearing a remapped position does not collide with today's calculated row" do+ travel_to(Date.new(2026, 12, 17)) do+ sync_positions!([ stock_position ])+ @account.holdings.find_by!(security: securities(:aapl)).remap_security!(securities(:msft))+ end+ travel_to(Time.zone.local(2026, 12, 18, 9)) do+ sync_positions!([], total: 2500)+ Holding::Materializer.new(@account.reload, strategy: :reverse).materialize_holdings+ end+ travel_to(Time.zone.local(2026, 12, 18, 15)) do+ assert_nothing_raised { sync_positions!([], total: 1000) }+ assert_empty current_tickers+ end+ end++ test "clearing a position keeps the user's cost-basis lock" do+ travel_to(Date.new(2026, 12, 17)) do+ sync_positions!([ stock_position ])+ @account.holdings.find_by!(security: securities(:aapl)).update!(cost_basis: 42, cost_basis_source: "manual", cost_basis_locked: true)+ end+ travel_to(Time.zone.local(2026, 12, 18, 9)) do+ sync_positions!([], total: 2500)+ Holding::Materializer.new(@account.reload, strategy: :reverse).materialize_holdings+ end+ travel_to(Time.zone.local(2026, 12, 18, 15)) do+ sync_positions!([], total: 1000)+ row = @account.holdings.find_by!(security: securities(:aapl), date: Date.current)+ assert row.cost_basis_locked+ assert_equal 42, row.cost_basis+ end+ end++ test "an empty list from a holdings_unavailable account is not logged" do+ travel_to(Date.new(2026, 12, 17)) { sync_positions!([ stock_position ]) }+ Rails.logger.stubs(:warn)+ Rails.logger.expects(:warn).with(regexp_matches(/kept positions/)).never+ travel_to(Date.new(2026, 12, 18)) do+ sync_positions!([], institution_metadata: { "sync_status" => { "holdings" => { "holdings_unavailable" => true } } })+ end+ end++ test "clearing a remapped position leaves another provider's row on the user's security" do+ travel_to(1.day.ago) do+ sync_positions!([ stock_position ])+ @account.holdings.find_by!(security: securities(:aapl)).remap_security!(securities(:msft))+ end+ plaid = AccountProvider.create!(account: @account, provider: plaid_accounts(:one))+ other = @account.holdings.create!(security: securities(:msft), date: Date.current, currency: "USD", qty: 5, price: 1, amount: 5,+ account_provider_id: plaid.id)++ assert_nothing_raised { sync_positions!([]) }+ assert_equal 5, other.reload.qty+ end+# === ActivitiesProcessor Tests ===test "activities processor maps BUY type to Buy label" do@@ -791,4 +954,20 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCaseassert_equal 0.0, entry.amount.to_fassert_equal 0.0, entry.entryable.price.to_fend++ private++ def sync_positions!(positions, activities = [], total: 1000, **attrs)+ @snaptrade_account.update!(currency: "USD", cash_balance: 1000, current_balance: total, last_holdings_sync: Time.current,+ raw_holdings_payload: positions, raw_activities_payload: activities, **attrs)+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process+ end++ def current_tickers+ @account.reload.current_holdings.map { |h| h.security.ticker }.sort+ end++ def stock_position(ticker = securities(:aapl).ticker, units: "10")+ { "instrument" => { "kind" => "stock", "symbol" => ticker }, "units" => units, "price" => "150.00", "currency" => "USD" }+ endend