fix(kraken): take a trade's quantity and cash from the ledger
Problem
Kraken's TradesHistory reports a fill as vol and cost, and neither is what moved through the account.
- Quantity. Kraken charges a trade's fee in whichever currency the order specifies, sometimes the base asset: buy BTC and the fee comes out of the BTC.
TradesHistoryreportsvolgross and converts the fee to the quote currency, with no fee-currency field, so nothing in that response says the fee was ever bitcoin. Recordingvolcredits units that were never received. They are never disposed of either, so the position stays permanently high, and every reversed historical quantity is off by the same amount. - Cash.
costis what the fill was worth, not what left the cash balance. A fee charged in the quote currency is deducted on top of it: a 1,000.00 buy with a 2.00 fee takes 1,002.00 out, and Sure recorded 1,000.00. That is a fraction of a percent per trade, butBalance::ReverseCalculatorwalks backwards from today's cash, so the shortfall accumulates across every trade and lands in the opening boundary adjustment as one lump.
Fix
The ledger already has the answer. Each ledger row carries the trade's txid in refid, one row per asset moved, and Kraken applies balance = previous + amount - fee there, so each asset's row is netted correctly whichever currency the fee was taken in. Take the quantity from the base asset's row and the cash movement from the quote row, through one shared ledger_row_for. A fee paid in the base asset leaves the quote row equal to cost, which is correct, because the coins absorbed it.
When no ledger row is found, fall back to vol and cost, so an account synced before the ledger permission was granted behaves as it does today. Once its rows do arrive, the next sync corrects the trade from them rather than skipping it as already imported: the quantity, amount and name are updated where the ledger answers and differs. An unchanged entry is not rewritten, and one the user edited or locked is left alone.
Tests
Five cases in ProcessorTest: a fee charged in the base asset, a fee charged in the quote currency, a trade with no ledger rows, which still falls back to what TradesHistory reported, a fallback trade corrected once its rows arrive (and not rewritten on the sync after), and an edited trade left alone.
bin/rails test test/models: 6,926 runs, 0 failures. Rubocop clean.
Summary by CodeRabbit
- Bug Fixes
- Kraken trades now reflect ledger-reported quantities and cash movements, including fees, when ledger data is available. If ledger data is unavailable, new trades continue to use reported trade values.
- Previously imported, unedited trades are corrected when ledger values differ. User-edited or sync-protected trades remain unchanged, and repeated syncs avoid unnecessary updates.