Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(kraken): one security per asset, not one per trading pair (#4023)

Daniel Garcia Sardinae090ce540d5d
diff --git a/app/models/kraken_account/holdings_processor.rb b/app/models/kraken_account/holdings_processor.rb
index d0a589ca49..5520b872f5 100644
--- a/app/models/kraken_account/holdings_processor.rb
+++ b/app/models/kraken_account/holdings_processor.rb
@@ -41,6 +41,13 @@ class KrakenAccount::HoldingsProcessor
return if symbol.blank? || total.zero? || price_usd.blank?
+ # Fiat at the exchange is cash, not a position. Held as a holding it is
+ # valued twice -- once here and once as the cash the ledger already moved --
+ # and it can never be reversed into history, because no trade ever moves it.
+ return if KrakenAccount::FIAT_CURRENCIES.include?(
+ KrakenAccount::SecurityResolver.canonical_asset(symbol)
+ )
+
security = resolve_security(symbol)
return unless security
@@ -72,8 +79,7 @@ class KrakenAccount::HoldingsProcessor
end
def resolve_security(symbol)
- ticker = symbol.to_s.include?(":") ? symbol.to_s : "CRYPTO:#{symbol}"
- KrakenAccount::SecurityResolver.resolve(ticker, symbol)
+ KrakenAccount::SecurityResolver.resolve(symbol)
end
def log_stale_rate(symbol, field, rate_date)
diff --git a/app/models/kraken_account/ledger_processor.rb b/app/models/kraken_account/ledger_processor.rb
index 21de29136a..f97869b8d9 100644
--- a/app/models/kraken_account/ledger_processor.rb
+++ b/app/models/kraken_account/ledger_processor.rb
@@ -350,7 +350,7 @@ class KrakenAccount::LedgerProcessor
end
def fiat?(base_symbol)
- KrakenAccount::FIAT_CURRENCIES.include?(base_symbol.to_s.upcase)
+ KrakenAccount::FIAT_CURRENCIES.include?(KrakenAccount::SecurityResolver.canonical_asset(base_symbol))
end
# One bulk request per asset for the span the ledger covers, the same call
@@ -380,7 +380,7 @@ class KrakenAccount::LedgerProcessor
end
def resolve_security(base_symbol)
- KrakenAccount::SecurityResolver.resolve("CRYPTO:#{base_symbol}", base_symbol)
+ KrakenAccount::SecurityResolver.resolve(base_symbol)
end
# The price on the day the units moved, not the price today. Falls back to
diff --git a/app/models/kraken_account/processor.rb b/app/models/kraken_account/processor.rb
index fd8382a205..943eeed8ac 100644
--- a/app/models/kraken_account/processor.rb
+++ b/app/models/kraken_account/processor.rb
@@ -76,7 +76,7 @@ class KrakenAccount::Processor
fee = trade["fee"].presence&.to_d || 0
currency = quote_symbol.presence || "USD"
date = Time.zone.at(trade["time"].to_d).to_date
- security = KrakenAccount::SecurityResolver.resolve("CRYPTO:#{base_symbol}", base_symbol)
+ security = KrakenAccount::SecurityResolver.resolve(base_symbol)
return unless security
# Sure's convention is positive = money out, so a buy is +cost and a sell
diff --git a/app/models/kraken_account/security_resolver.rb b/app/models/kraken_account/security_resolver.rb
index 036f9f9866..bcbe57c131 100644
--- a/app/models/kraken_account/security_resolver.rb
+++ b/app/models/kraken_account/security_resolver.rb
@@ -1,16 +1,98 @@
# frozen_string_literal: true
+# Resolves a Kraken asset to the security that represents it.
+#
+# One security per *asset*, never per trading pair. A position in BTC is one
+# position whether it was bought with EUR, sold for USD or is sitting in an Earn
+# wallet, so all of those must land on the same security or the holding is split
+# across several, each looking a fraction of its real size.
+#
+# That rules out the generic resolver's provider search for this path: asked to
+# resolve "CRYPTO:BTC" it answers with whatever pair its price provider ranks
+# first -- BTCBRL, BTC-EUR, BTCUSD -- which is a different security each time the
+# ranking moves, and never the one already in the database, because the ticker it
+# returns is not the ticker that was asked for.
+#
+# The ticker is instead bound straight to the crypto price provider, exactly as
+# Onchain::SecurityResolver does, and for the same reason. That also keeps one
+# asset in one record across integrations: the CRYPTO: prefix is shared, so a
+# coin held both on Kraken and on-chain is a single security rather than two.
class KrakenAccount::SecurityResolver
- EXCHANGE_MIC = "XKRA"
-
- def self.resolve(ticker, symbol)
- Security::Resolver.new(ticker).resolve
- rescue StandardError => e
- Rails.logger.warn "KrakenAccount::SecurityResolver - resolver failed for #{ticker}: #{e.message}"
- Security.find_or_initialize_by(ticker: ticker, exchange_operating_mic: EXCHANGE_MIC).tap do |security|
- security.name = symbol if security.name.blank?
- security.offline = true unless security.offline
- security.save! if security.changed?
+ TICKER_PREFIX = "CRYPTO:"
+
+ # The only securities provider that prices bare crypto symbols.
+ PRICE_PROVIDER = Onchain::SecurityResolver::PRICE_PROVIDER
+ EXCHANGE_MIC = Onchain::SecurityResolver::EXCHANGE_MIC
+
+ # Kraken suffixes a staked or bonded balance onto the asset code -- XBT.M,
+ # ETH2.S, DOT28.S -- and those are the same asset in a different wallet. The
+ # suffix can repeat: a balance payload reports bonded DOT as DOT28.S.S, so the
+ # group is matched one-or-more times rather than once, or DOT28.S.S resolves to
+ # a different security than the DOT28.S the ledger reports.
+ #
+ # The digits are only consumed ahead of a dot: LUNA2 stays LUNA2. Kraken has
+ # no staked variant of an asset whose name ends in a digit today; if it ever
+ # does, LUNA2.S would collapse to LUNA and this needs a table instead.
+ STAKING_SUFFIX = /(?:\d*\.[A-Z]+)+\z/
+
+ # Kraken's own legacy codes for the same asset: XBT and XXBT are BTC, XETH is
+ # ETH, ZEUR is EUR. Shared with AssetNormalizer so a symbol canonicalised here
+ # and one canonicalised there cannot disagree -- which is how BTC ended up
+ # split across CRYPTO:BTC and CRYPTO:XBT.
+ FIAT_PREFIXES = KrakenAccount::AssetNormalizer::FIAT_PREFIXES
+ SYMBOL_FALLBACKS = KrakenAccount::AssetNormalizer::SYMBOL_FALLBACKS
+
+ class << self
+ def resolve(asset_symbol)
+ asset = canonical_asset(asset_symbol)
+ return nil if asset.blank?
+
+ ticker = "#{TICKER_PREFIX}#{asset}"
+
+ existing_security(ticker) || create_security(ticker, asset)
end
+
+ # "XBT.M" -> "BTC", "DOT28.S" -> "DOT", "CRYPTO:ETH" -> "ETH"
+ def canonical_asset(symbol)
+ value = symbol.to_s.strip.upcase
+ value = value.split(":", 2).last.to_s if value.include?(":")
+ value = value.sub(STAKING_SUFFIX, "")
+ value = FIAT_PREFIXES[value] || value
+ SYMBOL_FALLBACKS[value] || value
+ end
+
+ private
+
+ # Does not require exchange_operating_mic to match: a Security for this
+ # ticker may already exist because another integration created it first,
+ # and reusing it keeps one asset in one record. The uniqueness index is on
+ # (ticker, mic), so there can be more than one -- the previous Kraken code
+ # created these at XKRA -- and the one at the crypto venue is preferred,
+ # then the oldest, so the choice is stable across syncs.
+ #
+ # A security with no provider cannot be priced, so it is bound to the one
+ # that quotes bare coin symbols and brought online. One with a provider
+ # someone else chose, or one deliberately kept offline under a provider,
+ # is left alone.
+ def existing_security(ticker)
+ security = Security.find_by(ticker: ticker, exchange_operating_mic: EXCHANGE_MIC) ||
+ Security.where(ticker: ticker).order(:created_at).first
+ return nil if security.nil?
+
+ security.update!(price_provider: PRICE_PROVIDER, offline: false) if security.price_provider.blank?
+ security
+ end
+
+ def create_security(ticker, asset)
+ Security.create!(
+ ticker: ticker,
+ name: asset,
+ exchange_operating_mic: EXCHANGE_MIC,
+ price_provider: PRICE_PROVIDER
+ )
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
+ Rails.logger.warn "KrakenAccount::SecurityResolver - could not create #{ticker}: #{e.message}"
+ Security.find_by(ticker: ticker)
+ end
end
end
diff --git a/app/models/kraken_item/importer.rb b/app/models/kraken_item/importer.rb
index fe03a82cbe..ec9d036a3f 100644
--- a/app/models/kraken_item/importer.rb
+++ b/app/models/kraken_item/importer.rb
@@ -63,7 +63,13 @@ class KrakenItem::Importer
next if balance.zero? && hold_trade.zero?
- price_usd, price_status = price_for(parsed[:price_symbol])
+ # Price the underlying asset, not the wallet variant: there is no
+ # DOT28.S ticker, and staked DOT is worth what DOT is worth. Without
+ # this the variant prices as "missing" and the holding is dropped
+ # entirely, so a staked position vanishes from the snapshot.
+ price_usd, price_status = price_for(
+ KrakenAccount::SecurityResolver.canonical_asset(parsed[:price_symbol])
+ )
amount_usd = price_usd ? (balance * price_usd).round(2) : 0.to_d
parsed.merge(
diff --git a/test/models/kraken_account/holdings_processor_test.rb b/test/models/kraken_account/holdings_processor_test.rb
index 171e332bf0..19eeaf70db 100644
--- a/test/models/kraken_account/holdings_processor_test.rb
+++ b/test/models/kraken_account/holdings_processor_test.rb
@@ -55,6 +55,21 @@ class KrakenAccount::HoldingsProcessorTest < ActiveSupport::TestCase
KrakenAccount::HoldingsProcessor.new(@kraken_account).process
end
+ # Fiat at the exchange is cash the ledger already moved. Held as a holding
+ # too it is valued twice, and it can never be reversed into history because
+ # no trade ever moves it.
+ test "does not import a fiat balance as a holding" do
+ @kraken_account.update!(raw_payload: { "assets" => [
+ { "symbol" => "EUR", "price_symbol" => "EUR", "balance" => "500", "price_usd" => "1.1", "source" => "spot" },
+ { "symbol" => "ZUSD", "price_symbol" => "USD", "balance" => "50", "price_usd" => "1.0", "source" => "spot" }
+ ] })
+ import_adapter = mock
+ import_adapter.expects(:import_holding).never
+ Account::ProviderImportAdapter.stubs(:new).returns(import_adapter)
+
+ KrakenAccount::HoldingsProcessor.new(@kraken_account).process
+ end
+
test "does not overwrite a different provider holding with the same security/date/currency" do
binance_item = BinanceItem.create!(family: @family, name: "Binance", api_key: "b", api_secret: "s")
binance_account = binance_item.binance_accounts.create!(name: "Binance", account_type: "combined", currency: "USD")
diff --git a/test/models/kraken_account/security_resolver_test.rb b/test/models/kraken_account/security_resolver_test.rb
new file mode 100644
index 0000000000..ebcf262897
--- /dev/null
+++ b/test/models/kraken_account/security_resolver_test.rb
@@ -0,0 +1,109 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class KrakenAccount::SecurityResolverTest < ActiveSupport::TestCase
+ # ---------------------------------------------------------------------------
+ # canonical_asset
+ # ---------------------------------------------------------------------------
+
+ test "canonicalises Kraken's legacy codes" do
+ assert_equal "BTC", canonical("XXBT")
+ assert_equal "BTC", canonical("XBT")
+ assert_equal "ETH", canonical("XETH")
+ assert_equal "EUR", canonical("ZEUR")
+ end
+
+ # A staked or bonded balance is the same asset in a different wallet. Left
+ # in, "DOT28.S" resolves to a security of its own and the position is split.
+ test "strips a staking or bonding suffix" do
+ assert_equal "BTC", canonical("XBT.M")
+ assert_equal "ETH", canonical("ETH2.S")
+ assert_equal "DOT", canonical("DOT28.S")
+ end
+
+ # The balance payload reports bonded DOT with the suffix twice.
+ test "strips a repeated suffix" do
+ assert_equal "DOT", canonical("DOT28.S.S")
+ assert_equal canonical("DOT28.S"), canonical("DOT28.S.S")
+ end
+
+ # A trailing digit is only a suffix when a dot follows it. LUNA2 is its own
+ # asset, not a wallet variant of LUNA.
+ test "leaves an asset whose name ends in a digit alone" do
+ assert_equal "LUNA2", canonical("LUNA2")
+ end
+
+ test "accepts a symbol that already carries the ticker prefix" do
+ assert_equal "ETH", canonical("CRYPTO:ETH")
+ end
+
+ # ---------------------------------------------------------------------------
+ # resolve
+ # ---------------------------------------------------------------------------
+
+ test "one security per asset, whatever wallet it sits in" do
+ spot = KrakenAccount::SecurityResolver.resolve("XXBT")
+ staked = KrakenAccount::SecurityResolver.resolve("XBT.M")
+
+ assert_equal spot.id, staked.id
+ assert_equal "CRYPTO:BTC", spot.ticker
+ end
+
+ test "binds a new security to the provider that can price a bare coin symbol" do
+ security = KrakenAccount::SecurityResolver.resolve("XXBT")
+
+ assert_equal KrakenAccount::SecurityResolver::PRICE_PROVIDER, security.price_provider
+ assert_equal KrakenAccount::SecurityResolver::EXCHANGE_MIC, security.exchange_operating_mic
+ assert_not security.offline?
+ end
+
+ # Another integration may have created the record first. Reusing it keeps one
+ # asset in one security rather than one per integration.
+ test "adopts an existing security instead of creating a second one" do
+ existing = Security.create!(ticker: "CRYPTO:BTC", name: "BTC", offline: true)
+
+ resolved = assert_no_difference -> { Security.count } do
+ KrakenAccount::SecurityResolver.resolve("XXBT")
+ end
+
+ assert_equal existing.id, resolved.id
+ assert_equal KrakenAccount::SecurityResolver::PRICE_PROVIDER, resolved.reload.price_provider
+ assert_not resolved.offline?
+ end
+
+ # A provider another integration chose deliberately is left alone, and so is
+ # an offline flag set under it.
+ test "does not overwrite a price provider someone else set" do
+ Security.create!(ticker: "CRYPTO:BTC", name: "BTC", price_provider: "yahoo_finance", offline: true)
+
+ resolved = KrakenAccount::SecurityResolver.resolve("XXBT")
+
+ assert_equal "yahoo_finance", resolved.price_provider
+ assert resolved.offline?
+ end
+
+ # The uniqueness index is on (ticker, mic), so the same ticker can exist at
+ # more than one venue -- the previous Kraken code created these at XKRA. The
+ # one at the crypto venue wins; failing that the oldest, so the choice does
+ # not move between syncs.
+ test "prefers the security at the crypto venue when the ticker exists at several" do
+ Security.create!(ticker: "CRYPTO:BTC", name: "BTC", exchange_operating_mic: "XKRA", offline: true)
+ venue = Security.create!(ticker: "CRYPTO:BTC", name: "BTC", exchange_operating_mic: KrakenAccount::SecurityResolver::EXCHANGE_MIC)
+
+ assert_equal venue.id, KrakenAccount::SecurityResolver.resolve("XXBT").id
+ end
+
+ test "falls back to the oldest security for the ticker" do
+ oldest = Security.create!(ticker: "CRYPTO:BTC", name: "BTC", exchange_operating_mic: "XKRA", created_at: 2.days.ago)
+ Security.create!(ticker: "CRYPTO:BTC", name: "BTC", exchange_operating_mic: "XNAS", created_at: 1.day.ago)
+
+ assert_equal oldest.id, KrakenAccount::SecurityResolver.resolve("XXBT").id
+ end
+
+ private
+
+ def canonical(symbol)
+ KrakenAccount::SecurityResolver.canonical_asset(symbol)
+ end
+end
diff --git a/test/models/kraken_item/importer_test.rb b/test/models/kraken_item/importer_test.rb
index 880fbb13d1..65c69b9418 100644
--- a/test/models/kraken_item/importer_test.rb
+++ b/test/models/kraken_item/importer_test.rb
@@ -59,6 +59,25 @@ class KrakenItem::ImporterTest < ActiveSupport::TestCase
assert_includes account.extra.dig("kraken", "missing_prices"), "ETH.F"
end
+ # There is no DOT28.S ticker: a bonded balance has to be priced as the asset
+ # underneath it. Priced as the wallet variant it comes back "missing" and the
+ # holding is dropped, so a staked position vanishes from the snapshot.
+ test "prices a bonded balance as its underlying asset" do
+ @provider.stubs(:get_asset_info).returns("DOT28.S" => { "altname" => "DOT28.S" })
+ @provider.stubs(:get_extended_balance).returns(
+ "DOT28.S" => { "balance" => "10.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }
+ )
+ @provider.stubs(:get_ticker).with("DOTUSD").returns("DOTUSD" => { "c" => [ "4.00" ] })
+
+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import
+
+ account = @item.kraken_accounts.first
+ dot = account.raw_payload["assets"].first
+ assert_equal "exact", dot["price_status"]
+ assert_in_delta 4.0, dot["price_usd"].to_d, 0.001
+ assert_in_delta 40.0, account.current_balance, 0.01
+ end
+
test "paginates TradesHistory in 50 fill pages" do
@provider.stubs(:get_asset_info).returns({})
@provider.stubs(:get_extended_balance).returns({})