Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Import open SnapTrade option positions at contract value (#5028)

arnaurodondev41e23fd69332
diff --git a/app/models/provider/snaptrade.rb b/app/models/provider/snaptrade.rb
index 94d804acb7..b3542eb4b1 100644
--- a/app/models/provider/snaptrade.rb
+++ b/app/models/provider/snaptrade.rb
@@ -61,11 +61,11 @@ class Provider::Snaptrade
TOKEN_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
+ # units are per-contract, which neither SnaptradeAccount::HoldingsProcessor
+ # nor the units * price sum in SnaptradeAccount::Processor#calculate_holdings_value
+ # models (options are, via contract_multiplier). A denylist, so equity-like
+ # kinds added later still import rather than being dropped.
+ UNSUPPORTED_INSTRUMENT_KINDS = %w[future future_option cfd].freeze
# GET /accounts/{id}/activities returns at most 1000 rows per request.
ACTIVITIES_PAGE_SIZE = 1000
diff --git a/app/models/snaptrade_account.rb b/app/models/snaptrade_account.rb
index fc75de9e1a..0f671ca8b2 100644
--- a/app/models/snaptrade_account.rb
+++ b/app/models/snaptrade_account.rb
@@ -215,7 +215,9 @@ class SnaptradeAccount < ApplicationRecord
units = parse_decimal(data[:units]) || BigDecimal("0")
price = parse_decimal(data[:price]) || BigDecimal("0")
- units * price
+ # Valued as the holding is (Processor#calculate_holdings_value), so a
+ # flagged option cancels at contract value.
+ units * price * contract_multiplier(extract_symbol_data(data))
end
end
diff --git a/app/models/snaptrade_account/data_helpers.rb b/app/models/snaptrade_account/data_helpers.rb
index 981dc7cba0..4e4e02d6eb 100644
--- a/app/models/snaptrade_account/data_helpers.rb
+++ b/app/models/snaptrade_account/data_helpers.rb
@@ -247,12 +247,12 @@ module SnaptradeAccount::DataHelpers
end
def extract_underlying_data(symbol_data)
- raw = symbol_data[:underlying_symbol] || symbol_data["underlying_symbol"]
+ raw = symbol_data[:underlying_symbol] || symbol_data["underlying_symbol"] || symbol_data[:underlying] || symbol_data["underlying"]
raw.is_a?(Hash) ? raw.with_indifferent_access : nil
end
def extract_underlying_ticker(symbol_data)
- raw = symbol_data[:underlying_symbol] || symbol_data["underlying_symbol"]
+ raw = symbol_data[:underlying_symbol] || symbol_data["underlying_symbol"] || symbol_data[:underlying] || symbol_data["underlying"]
if raw.is_a?(Hash)
data = raw.with_indifferent_access
data[:symbol] || data[:raw_symbol]
@@ -291,17 +291,22 @@ module SnaptradeAccount::DataHelpers
# SnapTrade reports option `units` in contracts while quoting `price` per
# underlying share. Standard options represent 100 underlying shares per
- # contract; mini options (`is_mini_option: true`) represent 10.
+ # contract; mini options (`is_mini_option: true`) represent 10. Positions
+ # carry the contract's own `multiplier`.
def contract_multiplier(symbol_data, option_data = nil)
data = option_data.presence || symbol_data
return 1 unless data.is_a?(Hash)
data = data.with_indifferent_access
is_option = option_data.present? ||
+ data[:kind].to_s.casecmp?("option") ||
data[:option_type].present? ||
!data[:is_mini_option].nil?
return 1 unless is_option
+ multiplier = parse_decimal(data[:multiplier])
+ return multiplier if multiplier&.positive?
+
ActiveModel::Type::Boolean.new.cast(data[:is_mini_option]) ? 10 : 100
end
end
diff --git a/app/models/snaptrade_account/holdings_processor.rb b/app/models/snaptrade_account/holdings_processor.rb
index b47256b54e..ec75522e3d 100644
--- a/app/models/snaptrade_account/holdings_processor.rb
+++ b/app/models/snaptrade_account/holdings_processor.rb
@@ -164,6 +164,10 @@ class SnaptradeAccount::HoldingsProcessor
price = parse_decimal(data["price"] || data[:price])
return if price.nil?
+ # Per-contract, as for option trades (ActivitiesProcessor#process_trade).
+ multiplier = contract_multiplier(symbol_data)
+ price *= multiplier
+
# Calculate amount
amount = quantity * price
@@ -196,7 +200,7 @@ class SnaptradeAccount::HoldingsProcessor
avg_price = data["average_purchase_price"] || data[:average_purchase_price] ||
data["cost_basis"] || data[:cost_basis]
if avg_price.present?
- update_holding_cost_basis(holding&.security || security, avg_price)
+ update_holding_cost_basis(holding&.security || security, parse_decimal(avg_price)&.*(multiplier))
end
true
end
diff --git a/app/models/snaptrade_account/processor.rb b/app/models/snaptrade_account/processor.rb
index 8c9c84ae7b..f9bddc31db 100644
--- a/app/models/snaptrade_account/processor.rb
+++ b/app/models/snaptrade_account/processor.rb
@@ -80,8 +80,11 @@ class SnaptradeAccount::Processor
calculated_total = holdings_value + cash_value
- # Use calculated total if we have holdings, otherwise trust API value
- if holdings_value > 0
+ # Use calculated total if we have holdings, otherwise trust API value.
+ # Net short positions (a short option on its own) make it negative; then
+ # only when nothing is missing from it: a long without units or a price
+ # counts as 0 and would leave just the short.
+ if holdings_value.positive? || (holdings_value.negative? && net_short_total_complete?)
Rails.logger.debug "SnaptradeAccount::Processor - Using calculated total: holdings=#{holdings_value} + cash=#{cash_value} = #{calculated_total}"
calculated_total
elsif snaptrade_account.current_balance.present?
@@ -151,10 +154,22 @@ class SnaptradeAccount::Processor
data = holding.is_a?(Hash) ? holding.with_indifferent_access : {}
units = parse_decimal(data[:units]) || 0
price = parse_decimal(data[:price]) || 0
- units * price
+ units * price * contract_multiplier(extract_symbol_data(data))
end
end
+ # Every position has units and a price, and there is no cash in another
+ # currency: that cash is imported as a holding, so it is in the API total
+ # but not in holdings plus cash.
+ def net_short_total_complete?
+ positions_complete = Array(snaptrade_account.raw_holdings_payload).all? do |holding|
+ data = holding.is_a?(Hash) ? holding.with_indifferent_access : {}
+ parse_decimal(data[:units]).present? && parse_decimal(data[:price]).present?
+ end
+
+ positions_complete && snaptrade_account.non_primary_cash_entries.none? { |entry| parse_decimal(entry[:amount])&.nonzero? }
+ end
+
def use_api_total_balance?
return false unless snaptrade_account.current_balance.present?
diff --git a/test/models/provider/snaptrade_oauth_test.rb b/test/models/provider/snaptrade_oauth_test.rb
index 65394d5298..de57fbec83 100644
--- a/test/models/provider/snaptrade_oauth_test.rb
+++ b/test/models/provider/snaptrade_oauth_test.rb
@@ -411,8 +411,10 @@ class Provider::SnaptradeOauthTest < ActiveSupport::TestCase
body = {
results: [
{ instrument: { kind: "stock", symbol: "AAPL" }, units: "10", price: "1.5" },
- { instrument: { kind: "option", symbol: "AAPL 240119C00150000" }, units: "2", price: "5.1" },
+ # Kept past expiry (in any zone) until the broker's book settles it
+ { instrument: { kind: "option", symbol: "OPT", expiration_date: Date.yesterday.iso8601 }, units: "2", price: "5.1" },
{ instrument: { kind: "future", symbol: "ESZ4" }, units: "1", price: "10" },
+ { instrument: { kind: "future_option", symbol: "./ESZ4 EW4X4 241115C5800" }, units: "1", price: "10" },
{ instrument: { kind: "cfd", symbol: "CFD1" }, units: "1", price: "10" },
{ instrument: { kind: "somethingnew", symbol: "NEW" }, units: "3", price: "2" }
]
@@ -425,7 +427,7 @@ class Provider::SnaptradeOauthTest < ActiveSupport::TestCase
positions = provider.get_positions(account_id: "acct-1")
- assert_equal %w[AAPL NEW], positions.map { |p| p.dig("instrument", "symbol") }
+ assert_equal %w[AAPL OPT NEW], positions.map { |p| p.dig("instrument", "symbol") }
end
test "expired token is refreshed before the data call and rotation persisted" do
diff --git a/test/models/snaptrade_account_processor_test.rb b/test/models/snaptrade_account_processor_test.rb
index 7449b45036..8520bbb978 100644
--- a/test/models/snaptrade_account_processor_test.rb
+++ b/test/models/snaptrade_account_processor_test.rb
@@ -234,8 +234,163 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCase
assert_equal BigDecimal("100"), @snaptrade_account.cash_equivalent_position_value("USD")
end
+ test "option positions are valued per contract, short ones as a liability" do
+ security = securities(:aapl)
+
+ @snaptrade_account.update!(
+ currency: "USD",
+ current_balance: BigDecimal("9999.00"),
+ cash_balance: BigDecimal("1000.00"),
+ raw_holdings_payload: [
+ { "instrument" => { "kind" => "stock", "symbol" => security.ticker }, "units" => "10", "price" => "150.00", "currency" => "USD" },
+ option_position("AAPL 261218C00240000", "CALL", units: "2", price: "5.10", cost_basis: "4.00"),
+ option_position("AAPL 261218P00200000", "PUT", units: "-1", price: "2.00")
+ ]
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account).process
+
+ # 1500 stock + 2 x 510 long call - 1 x 200 short put + 1000 cash
+ assert_equal BigDecimal("3320"), @account.reload.balance
+
+ call = @account.holdings.joins(:security).find_by(securities: { ticker: "AAPL 261218C00240000" })
+ assert_equal [ BigDecimal("2"), BigDecimal("510"), BigDecimal("1020"), BigDecimal("400") ],
+ [ call.qty, call.price, call.amount, call.cost_basis ]
+ # Holdings cannot be negative, so the short leg only counts in the total
+ assert_nil @account.holdings.joins(:security).find_by(securities: { ticker: "AAPL 261218P00200000" })
+ assert_nil Security.find_by(ticker: "AAPL 261218P00200000")
+ end
+
+ test "a short option on its own reduces the total below a stale cash-only API total" do
+ @snaptrade_account.update!(
+ currency: "USD",
+ current_balance: BigDecimal("1000.00"),
+ cash_balance: BigDecimal("1000.00"),
+ raw_holdings_payload: [ option_position("AAPL 261218P00200000", "PUT", units: "-1", price: "2.00") ]
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account).process
+
+ # 1000 cash - 1 x 200 short put
+ assert_equal BigDecimal("800"), @account.reload.balance
+ end
+
+ test "a short option next to an unpriced long keeps the API total" do
+ @snaptrade_account.update!(
+ currency: "USD",
+ current_balance: BigDecimal("20900.00"),
+ cash_balance: BigDecimal("1000.00"),
+ raw_holdings_payload: [
+ { "instrument" => { "kind" => "stock", "symbol" => securities(:aapl).ticker }, "units" => "100", "price" => nil, "currency" => "USD" },
+ option_position("AAPL 261218C00240000", "CALL", units: "-1", price: "1.00")
+ ]
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account).process
+
+ assert_equal BigDecimal("20900"), @account.reload.balance
+ end
+
+ test "a short option next to a long without units keeps the API total" do
+ @snaptrade_account.update!(
+ currency: "USD",
+ current_balance: BigDecimal("20900.00"),
+ cash_balance: BigDecimal("1000.00"),
+ raw_holdings_payload: [
+ { "instrument" => { "kind" => "stock", "symbol" => securities(:aapl).ticker }, "units" => nil, "price" => "200.00", "currency" => "USD" },
+ option_position("AAPL 261218C00240000", "CALL", units: "-1", price: "1.00")
+ ]
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account).process
+
+ assert_equal BigDecimal("20900"), @account.reload.balance
+ end
+
+ test "a short option next to cash in another currency keeps the API total" do
+ @snaptrade_account.update!(
+ currency: "USD",
+ current_balance: BigDecimal("1680.00"),
+ cash_balance: BigDecimal("1000.00"),
+ raw_balances_payload: [
+ { "currency" => { "code" => "USD" }, "cash" => "1000.00" },
+ { "currency" => { "code" => "EUR" }, "cash" => "800.00" }
+ ],
+ raw_holdings_payload: [ option_position("AAPL 261218P00200000", "PUT", units: "-1", price: "2.00") ]
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account).process
+
+ # The EUR cash is imported as a holding, not counted in 1000 - 200.
+ assert_equal BigDecimal("1680"), @account.reload.balance
+ end
+
+ test "a cash-equivalent option is subtracted from cash at contract value" do
+ @snaptrade_account.update!(
+ raw_holdings_payload: [ option_position("AAPL 261218C00240000", "CALL", units: "2", price: "5.00").merge("cash_equivalent" => true) ]
+ )
+
+ assert_equal BigDecimal("1000"), @snaptrade_account.cash_equivalent_position_value("USD")
+ end
+
+ test "option positions use the contract multiplier and position currency" do
+ @snaptrade_account.update!(
+ raw_holdings_payload: [ option_position("XYZ 261218C00050000", "CALL", units: "3", price: "1.50", multiplier: "10", currency: "CAD") ]
+ )
+
+ SnaptradeAccount::HoldingsProcessor.new(@snaptrade_account).process
+
+ holding = @account.holdings.joins(:security).find_by!(securities: { ticker: "XYZ 261218C00050000" })
+ assert_equal [ BigDecimal("15"), BigDecimal("45"), "CAD" ], [ holding.price, holding.amount, holding.currency ]
+ end
+
+ test "an option position without option_type still uses its contract multiplier" do
+ @snaptrade_account.update!(raw_holdings_payload: [ option_position("XYZ 261218C00050000", nil, units: "3", price: "1.50") ])
+
+ SnaptradeAccount::HoldingsProcessor.new(@snaptrade_account).process
+
+ holding = @account.holdings.joins(:security).find_by!(securities: { ticker: "XYZ 261218C00050000" })
+ assert_equal BigDecimal("450"), holding.amount
+ end
+
+ test "position-created option security gets the trade importer's name and exchange" do
+ occ = "AAPL 261218C00240000"
+ @snaptrade_account.update!(
+ currency: "USD",
+ raw_holdings_payload: [ option_position(occ, "CALL", units: "2", price: "5.10") ],
+ raw_activities_payload: [ {
+ "id" => "b1", "type" => "BUY", "units" => 2, "price" => 4, "amount" => -800,
+ "settlement_date" => 3.days.ago.to_date.to_s, "currency" => { "code" => "USD" },
+ "option_symbol" => {
+ "ticker" => occ, "option_type" => "CALL", "strike_price" => 240, "expiration_date" => "2026-12-18",
+ "underlying_symbol" => { "symbol" => "AAPL", "exchange" => { "mic_code" => "XNAS" } }
+ }
+ } ]
+ )
+
+ # Holdings run before activities, so the position creates the security
+ SnaptradeAccount::Processor.new(@snaptrade_account).process
+
+ security = Security.find_by!(ticker: occ)
+ assert_equal 1, Security.where(ticker: occ).count
+ assert_equal [ "AAPL $240 CALL (2026-12-18)", "XNAS" ], [ security.name, security.exchange_mic ]
+ end
+
+ test "an expired contract is not carried through the reverse history walk" do
+ buy = option_trade("b1", "BUY", units: 2, price: 4, amount: -800, date: "2026-12-01")
+ expiry = option_trade("x1", "OPTIONEXPIRATION", units: -2, price: 0, amount: 0, date: "2026-12-21")
+ travel_to(Date.new(2026, 12, 18)) { sync_positions!([ option_position(OCC, "CALL", units: "2", price: "5.10") ], [ buy ]) }
+
+ travel_to(Date.new(2026, 12, 28)) do
+ sync_positions!([], [ buy, expiry ])
+ Holding::Materializer.new(@account.reload, strategy: :reverse).materialize_holdings
+
+ assert_equal BigDecimal("2"), @account.holdings.find_by!(date: Date.new(2026, 12, 10)).qty
+ end
+ 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, 18)) { sync_positions!([ stock_position, option_position(OCC, "CALL", units: "2", price: "5.10") ]) }
travel_to(Date.new(2026, 12, 28)) { sync_positions!([]) }
assert_empty current_tickers
@@ -957,6 +1112,8 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCase
private
+ OCC = "AAPL 261218C00240000".freeze
+
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)
@@ -970,4 +1127,23 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCase
def stock_position(ticker = securities(:aapl).ticker, units: "10")
{ "instrument" => { "kind" => "stock", "symbol" => ticker }, "units" => units, "price" => "150.00", "currency" => "USD" }
end
+
+ def option_trade(id, type, units:, price:, amount:, date:)
+ { "id" => id, "type" => type, "units" => units, "price" => price, "amount" => amount, "trade_date" => date,
+ "settlement_date" => date, "currency" => { "code" => "USD" },
+ "option_symbol" => { "ticker" => OCC, "option_type" => "CALL", "strike_price" => 240, "expiration_date" => "2026-12-18",
+ "underlying_symbol" => { "symbol" => "AAPL", "exchange" => { "mic_code" => "XNAS" } } } }
+ end
+
+ # Shaped like a SnapTrade /positions/all OptionInstrument position
+ def option_position(symbol, option_type, units:, price:, cost_basis: nil, multiplier: "100", currency: "USD")
+ {
+ "instrument" => {
+ "kind" => "option", "symbol" => symbol, "option_type" => option_type,
+ "strike_price" => "240", "expiration_date" => "2026-12-18", "multiplier" => multiplier,
+ "underlying" => { "kind" => "stock", "symbol" => symbol.split.first, "exchange" => "XNAS", "currency" => currency }
+ },
+ "units" => units, "price" => price, "cost_basis" => cost_basis, "currency" => currency
+ }
+ end
end