The personal finance app for everyone (by everyone)
Ruby
Fix SnapTrade holdings by using the /positions/all endpoint (#3043)
Scott Hughes5bba880e6653
diff --git a/app/models/provider/snaptrade.rb b/app/models/provider/snaptrade.rbindex 39b59d0693..5cf4e598a7 100644--- a/app/models/provider/snaptrade.rb+++ b/app/models/provider/snaptrade.rb@@ -32,6 +32,13 @@ class Provider::SnaptradeDASHBOARD_URL = "https://dashboard.snaptrade.com".freezeTOKEN_EXPIRY_LEEWAY = 60 # seconds; refresh this long before actual expiry+ # Filtered out of get_positions so they never reach raw_holdings_payload:+ # units are per-contract and symbols OCC-style, which neither+ # SnaptradeAccount::HoldingsProcessor nor the units * price sum in+ # SnaptradeAccount::Processor#calculate_holdings_value models. A denylist, so+ # equity-like kinds added later still import rather than being dropped.+ UNSUPPORTED_INSTRUMENT_KINDS = %w[option future cfd].freeze+class << selfdef oauth_configured?oauth_client_id.present? && oauth_client_secret.present?@@ -207,7 +214,20 @@ class Provider::Snaptrade# Returns Array<Hash> of positionsdef get_positions(account_id:)- get_json("/api/v1/accounts/#{account_id}/positions")+ response = get_json("/api/v1/accounts/#{account_id}/positions/all")+ results = response["results"] if response.is_a?(Hash)++ # An empty `results` is a legitimately empty account, but a missing one is+ # a partial or schema-changed response. Raising leaves the previous+ # snapshot in place rather than overwriting it with nothing.+ unless results.is_a?(Array)+ raise ApiError.new(+ "SnapTrade positions response has no results array " \+ "(keys: #{response.is_a?(Hash) ? response.keys.inspect : response.class})"+ )+ end++ results.reject { |position| unsupported_instrument?(position) }end# Returns raw JSON: paginated form is {"data" => [...]}, may also be a plain Array@@ -248,6 +268,15 @@ class Provider::Snaptradeprivate+ def unsupported_instrument?(position)+ return false unless position.is_a?(Hash)++ instrument = position["instrument"]+ return false unless instrument.is_a?(Hash)++ UNSUPPORTED_INSTRUMENT_KINDS.include?(instrument["kind"].to_s.downcase)+ end+def get_json(path, params = {})request_json(:get, path, params: params)enddiff --git a/app/models/snaptrade_account/data_helpers.rb b/app/models/snaptrade_account/data_helpers.rbindex c542e53083..f5e52b8479 100644--- a/app/models/snaptrade_account/data_helpers.rb+++ b/app/models/snaptrade_account/data_helpers.rb@@ -105,6 +105,7 @@ module SnaptradeAccount::DataHelpersdef extract_exchange(symbol_data)exchange = symbol_data[:exchange] || symbol_data["exchange"]+ return exchange.presence if exchange.is_a?(String)return nil unless exchange.is_a?(Hash)exchange.with_indifferent_access[:mic_code] || exchange.with_indifferent_access[:id]@@ -129,8 +130,13 @@ module SnaptradeAccount::DataHelpersendend- # SnapTrade positions nest the security data as holding.symbol.symbol+ # Security metadata sits under `instrument`, or under `symbol.symbol` in+ # payloads persisted to raw_holdings_payload before the /positions/all+ # migration, which are re-read until the next sync overwrites them.def extract_symbol_data(data)+ instrument = data[:instrument] || data["instrument"]+ return instrument.with_indifferent_access if instrument.is_a?(Hash)+symbol_wrapper = data[:symbol].is_a?(Hash) ? data[:symbol].with_indifferent_access : {}raw_symbol_data = symbol_wrapper[:symbol]diff --git a/app/models/snaptrade_account/holdings_processor.rb b/app/models/snaptrade_account/holdings_processor.rbindex f036a20073..f38b5b3b5e 100644--- a/app/models/snaptrade_account/holdings_processor.rb+++ b/app/models/snaptrade_account/holdings_processor.rb@@ -84,18 +84,7 @@ class SnaptradeAccount::HoldingsProcessorenddef process_holding(data)- # Extract security info from the holding- # SnapTrade has DEEPLY NESTED structure:- # holding.symbol.symbol.symbol = ticker (e.g., "TSLA")- # holding.symbol.symbol.description = name (e.g., "Tesla Inc")- raw_symbol_wrapper = data["symbol"] || data[:symbol] || {}- symbol_wrapper = raw_symbol_wrapper.is_a?(Hash) ? raw_symbol_wrapper.with_indifferent_access : {}-- # The actual security data is nested inside symbol.symbol- raw_symbol_data = symbol_wrapper["symbol"] || symbol_wrapper[:symbol] || {}- symbol_data = raw_symbol_data.is_a?(Hash) ? raw_symbol_data.with_indifferent_access : {}-- # Get the ticker - it's at symbol.symbol.symbol+ symbol_data = extract_symbol_data(data)ticker = symbol_data["symbol"] || symbol_data[:symbol]# If that's still a hash, we need to go deeper or use raw_symbol@@ -122,15 +111,9 @@ class SnaptradeAccount::HoldingsProcessor# Get the holding date (use current date if not provided)holding_date = Date.current- # Extract currency - it can be at the holding level or in symbol_data- currency_data = data["currency"] || data[:currency] || symbol_data["currency"] || symbol_data[:currency]- currency = if currency_data.is_a?(Hash)- currency_data.with_indifferent_access["code"]- elsif currency_data.is_a?(String)- currency_data- else- account.currency- end+ # Must resolve to the same bucket as cash_equivalent_position_value, or+ # cash-equivalent positions stop cancelling out (#2729).+ currency = extract_currency(data, symbol_data, account.currency)Rails.logger.info "SnaptradeAccount::HoldingsProcessor - Importing holding: #{ticker} qty=#{quantity} price=#{price} currency=#{currency}"@@ -147,8 +130,11 @@ class SnaptradeAccount::HoldingsProcessordelete_future_holdings: false)- # Store cost basis if available- avg_price = data["average_purchase_price"] || data[:average_purchase_price]+ # Store cost basis if available. Both fields are per-share, which is+ # what update_holding_cost_basis expects — unlike the identically named+ # tax_lots[].cost_basis, which SnapTrade documents as a whole-lot total.+ avg_price = data["average_purchase_price"] || data[:average_purchase_price] ||+ data["cost_basis"] || data[:cost_basis]if avg_price.present?update_holding_cost_basis(security, avg_price)enddiff --git a/test/models/provider/snaptrade_oauth_test.rb b/test/models/provider/snaptrade_oauth_test.rbindex 7c65889faf..d3c5bf64fb 100644--- a/test/models/provider/snaptrade_oauth_test.rb+++ b/test/models/provider/snaptrade_oauth_test.rb@@ -128,6 +128,79 @@ class Provider::SnaptradeOauthTest < ActiveSupport::TestCaseassert_equal [ { "id" => "acct-1" } ], accountsend+ test "get_positions calls /positions/all and unwraps results" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ request = OpenStruct.new(headers: {}, params: {})+ body = {+ results: [ { instrument: { kind: "stock", symbol: "AAPL" }, units: "10", price: "1.5" } ],+ data_freshness: { as_of: "2026-08-14T18:12:18Z" }+ }.to_json++ connection = mock("faraday")+ connection.expects(:get)+ .with("#{Provider::Snaptrade::API_BASE_URL}/api/v1/accounts/acct-1/positions/all")+ .yields(request).returns(faraday_response(status: 200, body: body))+ provider.stubs(:api_connection).returns(connection)++ positions = provider.get_positions(account_id: "acct-1")++ assert_equal 1, positions.size+ assert_equal "AAPL", positions.first.dig("instrument", "symbol")+ end++ test "get_positions returns an empty array for an account holding nothing" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ connection = mock("faraday")+ connection.expects(:get).yields(OpenStruct.new(headers: {}, params: {}))+ .returns(faraday_response(status: 200, body: { results: [] }.to_json))+ provider.stubs(:api_connection).returns(connection)++ assert_equal [], provider.get_positions(account_id: "acct-1")+ end++ test "get_positions raises rather than reporting no positions when results are absent" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ connection = mock("faraday")+ connection.expects(:get).yields(OpenStruct.new(headers: {}, params: {}))+ .returns(faraday_response(status: 200, body: { data_freshness: {} }.to_json))+ provider.stubs(:api_connection).returns(connection)++ error = assert_raises(Provider::Snaptrade::ApiError) do+ provider.get_positions(account_id: "acct-1")+ end+ assert_match "no results array", error.message+ end++ test "get_positions filters out instrument kinds the holdings pipeline cannot model" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ body = {+ results: [+ { instrument: { kind: "stock", symbol: "AAPL" }, units: "10", price: "1.5" },+ { instrument: { kind: "option", symbol: "AAPL 240119C00150000" }, units: "2", price: "5.1" },+ { instrument: { kind: "future", symbol: "ESZ4" }, units: "1", price: "10" },+ { instrument: { kind: "cfd", symbol: "CFD1" }, units: "1", price: "10" },+ { instrument: { kind: "somethingnew", symbol: "NEW" }, units: "3", price: "2" }+ ]+ }.to_json++ connection = mock("faraday")+ connection.expects(:get).yields(OpenStruct.new(headers: {}, params: {}))+ .returns(faraday_response(status: 200, body: body))+ provider.stubs(:api_connection).returns(connection)++ positions = provider.get_positions(account_id: "acct-1")++ assert_equal %w[AAPL NEW], positions.map { |p| p.dig("instrument", "symbol") }+ end+test "expired token is refreshed before the data call and rotation persisted" doconfigure_oauth!item = fake_item(expires_at: 1.minute.ago)diff --git a/test/models/snaptrade_account_processor_test.rb b/test/models/snaptrade_account_processor_test.rbindex 820d6d54e0..b87cb781af 100644--- a/test/models/snaptrade_account_processor_test.rb+++ b/test/models/snaptrade_account_processor_test.rb@@ -159,6 +159,81 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCaseassert_equal "CHF", @account.currencyend+ # === /positions/all payload shape ===++ test "holdings processor creates holdings from a positions/all payload" do+ security = securities(:aapl)++ @snaptrade_account.update!(+ raw_holdings_payload: [+ {+ "instrument" => {+ "kind" => "stock",+ "symbol" => security.ticker,+ "raw_symbol" => security.ticker,+ "description" => security.name,+ "currency" => "USD",+ "exchange" => "XNAS"+ },+ "units" => "10",+ "price" => "77.885",+ "cost_basis" => "30",+ "currency" => "USD"+ }+ ]+ )++ SnaptradeAccount::HoldingsProcessor.new(@snaptrade_account).process++ holding = @account.holdings.find_by(security: security)+ assert_not_nil holding+ assert_equal BigDecimal("10"), holding.qty+ assert_equal BigDecimal("77.885"), holding.price+ end++ test "holdings processor reads cost_basis as a per-share value" do+ security = securities(:aapl)++ @snaptrade_account.update!(+ raw_holdings_payload: [+ {+ "instrument" => { "kind" => "stock", "symbol" => security.ticker, "currency" => "USD" },+ "units" => "10",+ "price" => "77.885",+ "cost_basis" => "30",+ "currency" => "USD"+ }+ ]+ )++ SnaptradeAccount::HoldingsProcessor.new(@snaptrade_account).process++ holding = @account.holdings.find_by(security: security)+ assert_not_nil holding+ assert_equal BigDecimal("30"), holding.cost_basis+ assert_equal "provider", holding.cost_basis_source+ end++ test "cash-equivalent positions are recognised in a positions/all payload" do+ security = securities(:aapl)++ @snaptrade_account.update!(+ currency: "USD",+ cash_balance: BigDecimal("1000.00"),+ raw_holdings_payload: [+ {+ "instrument" => { "kind" => "mutualfund", "symbol" => security.ticker, "currency" => "USD" },+ "units" => "100",+ "price" => "1.00",+ "currency" => "USD",+ "cash_equivalent" => true+ }+ ]+ )++ assert_equal BigDecimal("100"), @snaptrade_account.cash_equivalent_position_value("USD")+ end+# === ActivitiesProcessor Tests ===test "activities processor maps BUY type to Buy label" do