The personal finance app for everyone (by everyone)
Ruby
fix(kraken): a buy is money out and a sell is money in, not the reverse (#3757)
Daniel Garcia Sardina7b0bbbd3f71a
diff --git a/app/models/kraken_account/processor.rb b/app/models/kraken_account/processor.rbindex c85ab61954..2e3c5bd81b 100644--- a/app/models/kraken_account/processor.rb+++ b/app/models/kraken_account/processor.rb@@ -75,8 +75,12 @@ class KrakenAccount::Processorsecurity = KrakenAccount::SecurityResolver.resolve("CRYPTO:#{base_symbol}", base_symbol)return unless security- entry_amount = type == "buy" ? -cost : cost+ # Sure's convention is positive = money out, so a buy is +cost and a sell+ # -cost: the sign of the quantity, with Kraken's `cost` as the magnitude.+ # `cost` is the fill's actual cash figure and can differ from `vol * price`+ # by rounding, so it is kept rather than recomputed.trade_qty = type == "buy" ? qty : -qty+ entry_amount = type == "buy" ? cost : -costlabel = type == "buy" ? "Buy" : "Sell"account.entries.create!(diff --git a/db/migrate/20260927142423_fix_kraken_trade_entry_signs.rb b/db/migrate/20260927142423_fix_kraken_trade_entry_signs.rbnew file mode 100644index 0000000000..9cc0334c4f--- /dev/null+++ b/db/migrate/20260927142423_fix_kraken_trade_entry_signs.rb@@ -0,0 +1,53 @@+# Every Kraken trade entry was written with its cash flow inverted: a buy as+# money arriving, a sell as money leaving. The processor is fixed, but it+# skips an entry whose external_id it already has, so a resync never revisits+# the rows it wrote before -- and the balance series, derived by walking back+# from today through those flows, stays wrong for every existing account.+#+# The trade's quantity already carried the right sign, so it decides: an entry+# whose amount disagrees with its trade's quantity is flipped. The magnitude is+# kept as stored; `Entry.amount` and the trade's fields are separate values and+# this is not the place to recompute one from the other. A row that already+# agrees is left alone, which makes the migration safe to run more than once.+#+# An entry the user edited is theirs, whatever it says, and is left for them.+#+# The persisted balance series was derived from the wrong flows and is+# rebuilt on the account's next sync, which for a linked account recomputes+# the whole series. Nothing is queued from here: a migration that dispatches+# jobs cannot be retried without repeating the side effect, and a dispatch+# that fails after the update commits leaves accounts nothing can find again.+# Syncing on the next visit is the mechanism the app already has, and it does+# not depend on this migration having run to completion.+class FixKrakenTradeEntrySigns < ActiveRecord::Migration[8.1]+ def up+ flipped = execute(<<~'SQL').to_a+ UPDATE entries+ SET amount = -amount+ WHERE source = 'kraken'+ AND external_id LIKE 'kraken\_trade\_%'+ AND entryable_type = 'Trade'+ AND user_modified = false+ AND amount <> 0+ AND EXISTS (+ SELECT 1 FROM trades+ WHERE trades.id = entries.entryable_id+ AND trades.qty <> 0+ AND SIGN(trades.qty) <> SIGN(entries.amount)+ )+ RETURNING account_id+ SQL++ return say "No inverted Kraken trade entries found" if flipped.empty?++ accounts = flipped.map { |row| row["account_id"] }.uniq+ say "Flipped #{flipped.size} Kraken trade entries across #{accounts.size} accounts; " \+ "their balance series are rebuilt on their next sync"+ end++ # The rows that were flipped cannot be told apart afterwards from rows that+ # were right to begin with, so there is nothing to put back.+ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/test/migrations/fix_kraken_trade_entry_signs_migration_test.rb b/test/migrations/fix_kraken_trade_entry_signs_migration_test.rbnew file mode 100644index 0000000000..405630318d--- /dev/null+++ b/test/migrations/fix_kraken_trade_entry_signs_migration_test.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20260927142423_fix_kraken_trade_entry_signs")++class FixKrakenTradeEntrySignsMigrationTest < ActiveSupport::TestCase+ setup do+ @account = accounts(:investment)+ @security = Security.create!(ticker: "CRYPTO:BTC", name: "BTC", offline: true)+ end++ test "flips an entry whose amount disagrees with its trade's quantity" do+ buy = kraken_trade("buy_tx", qty: 0.001, amount: -50) # a buy written as money in+ sell = kraken_trade("sell_tx", qty: -0.002, amount: 120) # a sell written as money out++ run_migration++ assert_equal 50, buy.reload.amount+ assert_equal(-120, sell.reload.amount)+ end++ # Balances are rebuilt by the account's next sync, not from here: a+ # migration that dispatches jobs cannot be retried without repeating them.+ test "queues nothing itself" do+ kraken_trade("buy_tx", qty: 0.001, amount: -50)++ assert_no_difference -> { @account.syncs.count } do+ run_migration+ end+ end++ test "leaves an entry that already agrees, so it can run twice" do+ buy = kraken_trade("buy_tx", qty: 0.001, amount: 50)++ run_migration+ run_migration++ assert_equal 50, buy.reload.amount+ end++ test "leaves an entry the user edited" do+ buy = kraken_trade("buy_tx", qty: 0.001, amount: -50, user_modified: true)++ run_migration++ assert_equal(-50, buy.reload.amount)+ end++ test "leaves entries from other sources and other Kraken entry kinds" do+ other = kraken_trade("buy_tx", qty: 0.001, amount: -50, source: "binance", external_id: "binance_trade_buy_tx")+ ledger = kraken_trade("dep", qty: 0.001, amount: -50, external_id: "kraken_ledger_dep")++ run_migration++ assert_equal(-50, other.reload.amount)+ assert_equal(-50, ledger.reload.amount)+ end++ private+ def kraken_trade(txid, qty:, amount:, user_modified: false, source: "kraken", external_id: nil)+ @account.entries.create!(+ date: Date.current,+ name: "Trade",+ amount: amount,+ currency: "USD",+ source: source,+ external_id: external_id || "kraken_trade_#{txid}",+ user_modified: user_modified,+ entryable: Trade.new(security: @security, qty: qty, price: 50_000, currency: "USD")+ )+ end++ def run_migration+ ActiveRecord::Migration.suppress_messages do+ FixKrakenTradeEntrySigns.new.up+ end+ end+enddiff --git a/test/models/kraken_account/processor_test.rb b/test/models/kraken_account/processor_test.rbindex 157b654a7a..44fe052597 100644--- a/test/models/kraken_account/processor_test.rb+++ b/test/models/kraken_account/processor_test.rb@@ -42,13 +42,16 @@ class KrakenAccount::ProcessorTest < ActiveSupport::TestCaseKrakenAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)end+ # Sure stores positive = money out. A buy spends cash, so its entry amount is+ # positive; a sell returns cash, so its amount is negative. That is also what+ # `qty * price` yields once qty carries its own sign, which it already did.test "imports buy and sell spot fills as trade entries" doassert_difference -> { @account.entries.where(source: "kraken").count }, 2 doKrakenAccount::Processor.new(@kraken_account).processendbuy = @account.entries.find_by!(external_id: "kraken_trade_buy_tx", source: "kraken")- assert_equal(-50.to_d, buy.amount)+ assert_equal 50.to_d, buy.amountassert_equal "USD", buy.currencyassert_equal 0.001.to_d, buy.trade.qtyassert_equal 50_000.to_d, buy.trade.price@@ -56,12 +59,33 @@ class KrakenAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal "Buy", buy.trade.investment_activity_labelsell = @account.entries.find_by!(external_id: "kraken_trade_sell_tx", source: "kraken")- assert_equal 120.to_d, sell.amount+ assert_equal(-120.to_d, sell.amount)assert_equal(-0.002.to_d, sell.trade.qty)assert_equal 0.20.to_d, sell.trade.feeassert_equal "Sell", sell.trade.investment_activity_labelend+ # The bug this guards against: the entry amount agreed with neither the trade+ # direction nor `qty * price`, so a buy read as an inflow and a sell as an+ # outflow. Balances are derived by walking back from today, so the error did+ # not cancel out -- it accumulated across the whole history.+ #+ # The magnitude is Kraken's `cost`, the fill's actual cash figure, which can+ # differ from `vol * price` by rounding; only the sign is derived.+ test "a trade entry amount carries the sign of its quantity and the magnitude of its cost" do+ KrakenAccount::Processor.new(@kraken_account).process++ @account.entries.where(source: "kraken").each do |entry|+ trade = entry.trade+ txid = entry.external_id.delete_prefix("kraken_trade_")+ cost = @kraken_account.raw_transactions_payload.dig("trades", txid, "cost").to_d++ assert_equal trade.qty.positive?, entry.amount.positive?,+ "#{entry.external_id}: a buy is money out, a sell money in"+ assert_equal cost, entry.amount.abs, "#{entry.external_id}: the magnitude is the reported cost"+ end+ end+test "trade import is idempotent by txid" doassert_difference -> { @account.entries.where(source: "kraken").count }, 2 doKrakenAccount::Processor.new(@kraken_account).process