Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(kraken): take a trade's quantity and cash from the ledger (#4086)

Daniel Garcia Sardina303580ab98e7
diff --git a/app/models/kraken_account/processor.rb b/app/models/kraken_account/processor.rb
index 943eeed8ac..4c7c7f9012 100644
--- a/app/models/kraken_account/processor.rb
+++ b/app/models/kraken_account/processor.rb
@@ -42,6 +42,10 @@ class KrakenAccount::Processor
end
def process_trades
+ # Built per pass: one made before an earlier pass's inserts would miss
+ # them, and import those trades twice.
+ @existing_trade_entries = nil
+
raw_trades.each do |txid, trade|
process_trade(txid, trade)
end
@@ -58,7 +62,7 @@ class KrakenAccount::Processor
return unless account
external_id = "kraken_trade_#{txid}"
- return if account.entries.exists?(external_id: external_id, source: "kraken")
+ existing = existing_trade_entries[external_id]
type = trade["type"].to_s.downcase
return unless %w[buy sell].include?(type)
@@ -67,8 +71,19 @@ class KrakenAccount::Processor
base_symbol, quote_symbol = infer_pair_symbols(pair, trade)
return if base_symbol.blank?
- qty = trade["vol"].to_d
- return if qty.zero?
+ ledger_qty, ledger_cash = ledger_values_for(txid, base_symbol, quote_symbol)
+
+ return reconcile_with_ledger(existing, txid, ledger_qty, ledger_cash, type, base_symbol, quote_symbol) if existing
+
+ # `vol` is gross. When the fee is taken in the base asset -- an order-level
+ # choice Kraken makes per fill -- the units that actually moved are fewer,
+ # and TradesHistory gives no way to tell: it reports every fee converted to
+ # the quote currency, with no fee-currency field. The ledger is where the
+ # truth is, so prefer it and fall back to `vol`. A ledger net of zero is
+ # an answer -- a small fill whose units all went on the fee -- and is
+ # recorded, since its cash still moved.
+ qty = ledger_qty || trade["vol"].to_d
+ return if ledger_qty.nil? && qty.zero?
price = trade["price"].to_d
cost = trade["cost"].presence&.to_d
@@ -84,8 +99,13 @@ class KrakenAccount::Processor
# `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 : -cost
+ # Same reasoning as the quantity: `cost` is what the fill was worth, not
+ # what left the account. A fee charged in the quote currency comes out on
+ # top of it, and the ledger's quote row nets the two already -- whichever
+ # currency the fee was actually taken in.
+ entry_amount = ledger_cash || (type == "buy" ? cost : -cost)
label = type == "buy" ? "Buy" : "Sell"
+ capture_partial_ledger(txid, ledger_qty, ledger_cash, base_symbol, quote_symbol)
account.entries.create!(
date: date,
@@ -108,6 +128,125 @@ class KrakenAccount::Processor
Rails.logger.error "KrakenAccount::Processor - failed to process trade #{txid}: #{e.message}"
end
+ # A trade imported before its ledger rows were available -- before the API
+ # key was granted "Query ledger entries", or before the ledger backfill
+ # reached it -- holds TradesHistory's gross `vol` and `cost`. Once the rows
+ # arrive, correct it from them, as a fresh import would have. Only what the
+ # ledger answers is touched, an unchanged entry is not rewritten, and one the
+ # user edited or locked is left alone.
+ #
+ # Each value is corrected on its own: a fee taken in the base asset leaves the
+ # quote row equal to `cost`, and one taken in the quote leaves the base row
+ # equal to `vol`, so a trade whose second row has not arrived yet is not made
+ # any less right by taking the first.
+ def reconcile_with_ledger(entry, txid, qty, cash, type, base_symbol, quote_symbol)
+ # Checked before the entryable is touched, so a sync with no ledger rows
+ # costs no query per trade.
+ return if qty.nil? && cash.nil?
+ return if entry.protected_from_sync?
+
+ trade = entry.entryable
+ return unless trade.is_a?(Trade)
+
+ signed_qty = qty && (type == "buy" ? qty : -qty)
+
+ qty_changed = signed_qty && signed_qty != trade.qty
+ cash_changed = cash && cash != entry.amount
+ return unless qty_changed || cash_changed
+
+ capture_partial_ledger(txid, qty, cash, base_symbol, quote_symbol)
+
+ label = type == "buy" ? "Buy" : "Sell"
+ # Entry.transaction, not entry.transaction: delegated_type makes the
+ # instance method the Transaction entryable accessor.
+ Entry.transaction do
+ trade.update!(qty: signed_qty) if qty_changed
+ entry.update!(
+ amount: cash_changed ? cash : entry.amount,
+ name: qty_changed ? "#{label} #{qty.round(8)} #{base_symbol}" : entry.name
+ )
+ end
+ end
+
+ # Every existing trade entry for this payload, with its Trade, in one query
+ # rather than two per fill.
+ def existing_trade_entries
+ @existing_trade_entries ||= begin
+ external_ids = raw_trades.keys.map { |txid| "kraken_trade_#{txid}" }
+ kraken_account.current_account.entries
+ .where(source: "kraken", external_id: external_ids)
+ .includes(:entryable)
+ .index_by(&:external_id)
+ end
+ end
+
+ # The ledger's quantity and cash for a trade, nil where it has no row.
+ def ledger_values_for(txid, base_symbol, quote_symbol)
+ [ ledger_qty_for(txid, base_symbol), ledger_cash_for(txid, quote_symbol) ]
+ end
+
+ # A trade moves two assets, so a ledger holding only one of its rows -- a
+ # partial response, or the backfill's page cap falling between them --
+ # leaves the trade half ledger, half TradesHistory. Recorded for support when
+ # the trade is written, not on every sync that finds it unchanged.
+ def capture_partial_ledger(txid, qty, cash, base_symbol, quote_symbol)
+ return if qty.nil? == cash.nil?
+
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "Kraken ledger has only the #{qty.nil? ? quote_symbol : base_symbol} row of trade #{txid}",
+ source: self.class.name,
+ provider_key: "kraken",
+ family: kraken_account.kraken_item&.family,
+ metadata: { txid: txid.to_s, base: base_symbol, quote: quote_symbol, account_id: kraken_account.current_account&.id }
+ )
+ end
+
+ # A trade's ledger rows carry its txid in `refid`, one row per asset moved.
+ # The row for the base asset holds what was really received or given up:
+ # Kraken applies `balance = previous + amount - fee`, so a fee charged in the
+ # base asset is already netted out there and nowhere else.
+ def ledger_qty_for(txid, base_symbol)
+ row = ledger_row_for(txid, base_symbol)
+ return nil if row.nil?
+
+ (row["amount"].to_d - row["fee"].to_d).abs
+ end
+
+ # The quote-currency side of the same trade: what actually moved in or out of
+ # the cash balance. Sure's sign convention is the ledger's inverted -- there a
+ # buy shows the quote asset leaving as a negative amount; here money out is
+ # positive.
+ #
+ # Rounded to what `entries.amount` stores: a crypto-quoted pair's ledger
+ # carries more decimals than the column, and unrounded it would never equal
+ # the stored figure, sending every unchanged trade down the update path on
+ # every sync.
+ def ledger_cash_for(txid, quote_symbol)
+ return nil if quote_symbol.blank?
+
+ row = ledger_row_for(txid, quote_symbol)
+ return nil if row.nil?
+
+ (-(row["amount"].to_d - row["fee"].to_d)).round(Entry.columns_hash["amount"].scale)
+ end
+
+ def ledger_row_for(txid, symbol)
+ rows = ledgers_by_refid[txid.to_s]
+ return nil if rows.blank?
+
+ wanted = KrakenAccount::SecurityResolver.canonical_asset(symbol)
+ rows.find { |ledger| KrakenAccount::SecurityResolver.canonical_asset(ledger["asset"]) == wanted }
+ end
+
+ def ledgers_by_refid
+ @ledgers_by_refid ||= begin
+ ledgers = kraken_account.raw_transactions_payload&.dig("ledgers") || {}
+ ledgers.values.group_by { |ledger| ledger["refid"].to_s }
+ end
+ end
+
def infer_pair_symbols(pair, trade)
pair_metadata = kraken_account.raw_payload&.dig("pair_metadata") || {}
metadata = pair_metadata[pair] || pair_metadata.values.find { |candidate| candidate["altname"].to_s == pair }
diff --git a/test/models/kraken_account/processor_test.rb b/test/models/kraken_account/processor_test.rb
index 2b38526d5f..1e055d42b3 100644
--- a/test/models/kraken_account/processor_test.rb
+++ b/test/models/kraken_account/processor_test.rb
@@ -86,6 +86,163 @@ class KrakenAccount::ProcessorTest < ActiveSupport::TestCase
end
end
+ # ---------------------------------------------------------------------------
+ # the ledger is the source of truth for what actually moved
+ # ---------------------------------------------------------------------------
+
+ # `vol` is gross. When Kraken takes the fee in the base asset -- an order-level
+ # choice it makes per fill -- fewer units arrive, and TradesHistory cannot say
+ # so: it reports every fee converted to the quote currency, with no
+ # fee-currency field. The ledger nets it, because Kraken applies
+ # `balance = previous + amount - fee` there.
+ test "takes a buy's quantity from the ledger, net of a base-asset fee" do
+ set_ledgers(
+ "l1" => ledger_row("buy_tx", "XXBT", amount: "0.00100000", fee: "0.00000200"),
+ "l2" => ledger_row("buy_tx", "ZUSD", amount: "-50.00", fee: "0.00")
+ )
+
+ KrakenAccount::Processor.new(@kraken_account).process
+
+ buy = @account.entries.find_by!(external_id: "kraken_trade_buy_tx", source: "kraken")
+ assert_equal 0.000998.to_d, buy.trade.qty
+ end
+
+ # `cost` is what the fill was worth, not what left the account: a fee charged
+ # in the quote currency comes out on top of it.
+ test "takes a sell's cash movement from the ledger, net of a quote-currency fee" do
+ set_ledgers(
+ "l3" => ledger_row("sell_tx", "XXBT", amount: "-0.00200000", fee: "0.00000000"),
+ "l4" => ledger_row("sell_tx", "ZUSD", amount: "120.00", fee: "0.20")
+ )
+
+ KrakenAccount::Processor.new(@kraken_account).process
+
+ sell = @account.entries.find_by!(external_id: "kraken_trade_sell_tx", source: "kraken")
+ assert_equal(-119.80.to_d, sell.amount)
+ end
+
+ test "falls back to the reported volume and cost when the trade has no ledger rows" do
+ KrakenAccount::Processor.new(@kraken_account).process
+
+ buy = @account.entries.find_by!(external_id: "kraken_trade_buy_tx", source: "kraken")
+ assert_equal 0.001.to_d, buy.trade.qty
+ assert_equal 50.to_d, buy.amount
+ end
+
+ # A trade imported before the ledger permission was granted holds the gross
+ # `vol` and `cost`. When its rows arrive, the next sync corrects it rather
+ # than skipping it as already imported.
+ test "corrects a trade imported without ledger rows once they arrive" do
+ KrakenAccount::Processor.new(@kraken_account).process
+ buy = @account.entries.find_by!(external_id: "kraken_trade_buy_tx", source: "kraken")
+ assert_equal 0.001.to_d, buy.trade.qty
+
+ set_ledgers(
+ "l1" => ledger_row("buy_tx", "XXBT", amount: "0.00100000", fee: "0.00000200"),
+ "l2" => ledger_row("buy_tx", "ZUSD", amount: "-50.00", fee: "0.10")
+ )
+ KrakenAccount::Processor.new(@kraken_account).process
+
+ buy.reload
+ assert_equal 0.000998.to_d, buy.trade.reload.qty
+ assert_equal 50.10.to_d, buy.amount
+
+ assert_no_changes -> { buy.reload.updated_at } do
+ KrakenAccount::Processor.new(@kraken_account).process
+ end
+ end
+
+ test "leaves a trade the user edited alone when its ledger rows arrive" do
+ KrakenAccount::Processor.new(@kraken_account).process
+ buy = @account.entries.find_by!(external_id: "kraken_trade_buy_tx", source: "kraken")
+ buy.update!(user_modified: true)
+
+ set_ledgers(
+ "l1" => ledger_row("buy_tx", "XXBT", amount: "0.00100000", fee: "0.00000200"),
+ "l2" => ledger_row("buy_tx", "ZUSD", amount: "-50.00", fee: "0.10")
+ )
+ KrakenAccount::Processor.new(@kraken_account).process
+
+ assert_equal 0.001.to_d, buy.trade.reload.qty
+ assert_equal 50.to_d, buy.reload.amount
+ end
+
+ # A fill whose units all went on its fee nets to zero in the ledger. That is
+ # the ledger's answer, not a missing row: the cash still left the account.
+ test "records a buy whose whole quantity went on the fee" do
+ set_ledgers(
+ "l1" => ledger_row("buy_tx", "XXBT", amount: "0.00100000", fee: "0.00100000"),
+ "l2" => ledger_row("buy_tx", "ZUSD", amount: "-50.00", fee: "0.00")
+ )
+
+ KrakenAccount::Processor.new(@kraken_account).process
+
+ buy = @account.entries.find_by!(external_id: "kraken_trade_buy_tx", source: "kraken")
+ assert_equal 0.to_d, buy.trade.qty
+ assert_equal 50.to_d, buy.amount
+ end
+
+ # `entries.amount` keeps four decimals and a ledger can carry eight. Compared
+ # unrounded, the stored figure would never match, and every sync would take
+ # the update path for a trade that has not changed.
+ test "rounds ledger cash to the stored precision and leaves it alone afterwards" do
+ set_ledgers(
+ "l1" => ledger_row("buy_tx", "XXBT", amount: "0.00100000", fee: "0.00000000"),
+ "l2" => ledger_row("buy_tx", "ZUSD", amount: "-50.00123456", fee: "0.00000000")
+ )
+ KrakenAccount::Processor.new(@kraken_account).process
+
+ buy = @account.entries.find_by!(external_id: "kraken_trade_buy_tx", source: "kraken")
+ assert_equal 50.0012.to_d, buy.amount
+
+ Entry.any_instance.expects(:update!).never
+ KrakenAccount::Processor.new(@kraken_account).process
+ end
+
+ # Each row is right on its own: a fee taken in the base asset leaves the quote
+ # row equal to `cost`, so taking the quantity before the cash row arrives
+ # makes the trade no less correct. The half-ledger trade is logged for support,
+ # once, when it is written.
+ test "corrects the quantity from a base row alone and logs the missing quote row" do
+ KrakenAccount::Processor.new(@kraken_account).process
+ buy = @account.entries.find_by!(external_id: "kraken_trade_buy_tx", source: "kraken")
+
+ set_ledgers("l1" => ledger_row("buy_tx", "XXBT", amount: "0.00100000", fee: "0.00000200"))
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "kraken").count }, 1 do
+ KrakenAccount::Processor.new(@kraken_account).process
+ end
+ assert_equal 0.000998.to_d, buy.trade.reload.qty
+ assert_equal 50.to_d, buy.reload.amount
+
+ assert_no_difference -> { DebugLogEntry.where(provider_key: "kraken").count } do
+ KrakenAccount::Processor.new(@kraken_account).process
+ end
+ end
+
+ # A repeat sync can carry thousands of fills. Their entries and trades load
+ # in one go rather than in two queries per fill.
+ test "loads the existing trades once, not once per fill" do
+ KrakenAccount::Processor.new(@kraken_account).process
+
+ queries = capture_sql_queries { KrakenAccount::Processor.new(@kraken_account).send(:process_trades) }
+
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "entries"') }
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "trades"') }
+ end
+
+ # The entry uniqueness check would stop a duplicate, but each trade would then
+ # fail its insert and log an error on every pass after the first.
+ test "a second pass of the same processor sees the trades the first one imported" do
+ processor = KrakenAccount::Processor.new(@kraken_account)
+ processor.send(:process_trades)
+
+ Rails.logger.expects(:error).never
+ assert_no_difference -> { @account.entries.where(source: "kraken").count } do
+ processor.send(:process_trades)
+ end
+ end
+
test "trade import is idempotent by txid" do
assert_difference -> { @account.entries.where(source: "kraken").count }, 2 do
KrakenAccount::Processor.new(@kraken_account).process
@@ -179,6 +336,21 @@ class KrakenAccount::ProcessorTest < ActiveSupport::TestCase
private
+ def set_ledgers(ledgers)
+ @kraken_account.update!(
+ raw_transactions_payload: @kraken_account.raw_transactions_payload.merge("ledgers" => ledgers)
+ )
+ end
+
+ # A trade's ledger rows carry its txid in `refid`, one row per asset moved.
+ def ledger_row(refid, asset, amount:, fee:)
+ {
+ "refid" => refid, "time" => Time.current.to_f, "type" => "trade",
+ "subtype" => "", "aclass" => "currency", "asset" => asset,
+ "amount" => amount, "fee" => fee, "balance" => "0.00000000"
+ }
+ end
+
def trade_payload(type, volume, cost, fee)
price = volume.to_d.zero? ? 0.to_d : cost.to_d / volume.to_d