Repository navigation
fix(fx): stop an overdraft leaving phantom dollars when the IBKR Cash Report proves the loan - #456
Merged
Merged
Conversation
…sh Report proves it A buy that spent more dollars than the account held took the missing part as untracked, and a later day's sale re-added it to the pool as if it existed. A conversion then spent dollars that were owed, not held: the issue's repro gave -175 in both methods on an economic -145, with 200 phantom dollars left. Now, for a currency whose cash an IBKR CashReport proves (one account, a known non-negative startingCash, every period reconciled with the movements the engine sees, no skipped AFx rows), the shortfall opens a loan at the day's ECB rate. Later inflows repay it oldest first and book x * (r_loan - cost) in 1633/1637; debit interest while negative adds to the debt; the 7-day late cover runs first; a same-day round trip keeps the #447 rule. Every other currency and every fixture keeps the untracked path (byte-identical, only the untracked note's text now names an overdraft or margin loan). The new report note gives the debt's own change, which STS 71/2021 puts in the base general (0304/0305) and DGT V2414-12 in the base del ahorro. Refs #449
… balance counts as a loan casillas.md and traza-fx.md now say when DeclaRenta treats a balance below zero as a loan (the IBKR Cash Report must reconcile), how each repayment is booked and traced, and where the Supreme Court and the DGT put the debt's part. CLAUDE.md gets the #449 Hard Trace and drops the open known gap. Refs #449
…engine reads The loan gate proved each period's net only: starting cash plus the flows the FX engine sees had to equal the ending cash. Movements the engine does not see that cancel inside a period passed, so the loan model invented a loan on an account that never went below zero. A USD deposit and an equal withdrawal in one year booked 70 EUR of loan repayments in «Tradicional con divisa» and 30 EUR in the default, on an economic 0. A second IBKR account with no Cash Report, merged with one that has it, passed too, because the per-event check compared only the broker. The gate now also reads the raw rows of the currency: every trade must be a currency pair or a stock, fund or bond trade of the Cash Report's account and broker (no option, future, short cover, or commission in the currency on a trade in another one), every cash row must be income, withholding, interest or fees (no deposit, withdrawal or transfer), and no corporate action may carry cash. A short sale's own inflow stays unseen and breaks the reconciliation. The gate also gave different answers per method: it summed each method's own stock-sale events, and the default drops a sale with proceeds of 0 or less. A worthless sale whose commission exceeded its proceeds turned the loan on in «Tradicional con divisa» only. The gate now always reads the sales the way «Tradicional con divisa» does. No fixture changes: none passes the gate.
…y the loan In the default, a loan repaid the day it opened booked nothing, to keep the #447 loss-sale rule. That also dropped repayments with no loss. When a buy borrowed dollars and a sale of part of the shares the same day returned the account's own dollars, those dollars repaid the loan, and the borrowed slice stayed parked in the remaining shares at the loan's rate. Its cost difference was lost: 500 USD at 0.90, a buy of 1000 at 0.95, half sold for 510 that day and the rest later gave -27 on an economic -2. The same upload without a Cash Report, and f9926b6, give -2. An independent generator missed on 47 of 1500 no-loss seeds, all with same-day trades. Now, in the default, a same-day repayment first covers the borrowed slices still parked in the shares: they take the paying dollars' cost and date, as the same-day cover does for a buy with no dollars of its own. Only the borrowed principal a losing sale did not return keeps the loss-sale rule, so IRT-LOSS stays at -190 / -30. «Tradicional con divisa» is unchanged. The issue's generator gets a same-day mode (part or all of the position sold on the day of an overdrawing buy, at no loss): 200 seeds match in both methods with a Cash Report. With the cover turned off, MIN1 and the same-day seeds fail. No fixture changes: none passes the gate.
…tell the user the same The loan note summed the debt part only over repayment rows that reached 1633/1637. In the default, the loan's own shares repay it at the loan's rate, a zero row, because the default's stock line (sale-rate cost) already holds that change. So the default gave no note, or a fraction of the figure, for a loan the mode reported in full: 0 against 50 EUR on the same loan. The engine now records every repayment's debt part, x × (r_loan − r_day), also for zero rows, and the note fires from that figure. Both methods give the same number. The hint told a user who follows the Supreme Court to put the amount in 0304 or 0305, but not to take it out of 1633/1637, so the amount could be declared twice. It also passed a signed number for box 0305. The note now gives the gain and the loss apart, both as positive amounts, and says to lower 1633 by the gain and raise it by the loss. The untracked-currency note told every broker's users to upload the IBKR Cash Report, also users who had already uploaded it. It now has three forms: the generic one (no word of IBKR), one for an IBKR currency with no Cash Report that passes the gate (it says what the gate needs), and one inside the gate that calls those dollars the Cash Report's opening balance. The loan note now shows in the open «Cómo se ha calculado» box with the other method notes. All new text is in the 5 locales. Fixtures: the numbers do not change. The untracked note on the IBKR fixtures (ibkr-sample, ibkr-multicurrency, ibkr-options, ibkr-434-afx-2025 with AFx skipped) now has the id report.fx_traditional_uncovered_ibkr; the other brokers keep report.fx_traditional_uncovered with the f9926b6 hint.
… debt part The docs said a deposit or an option premium breaks the loan gate's reconciliation. That was false when the movements cancel inside a period. They now list the rows the gate rejects outright (deposits, withdrawals, transfers, options, short covers, a second account) and say that both methods reach the same decision. They describe how the default handles a loan repaid the day it opened, the debt part from every repayment with gains and losses apart, and how to move that part to 0304/0305 out of 1633/1637. CLAUDE.md records the three traps the review found and the new controls.
Contributor
|
Caution Review failedThe pull request is closed.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #456 +/- ##
==========================================
+ Coverage 93.82% 93.90% +0.08%
==========================================
Files 63 64 +1
Lines 7819 8103 +284
Branches 2678 2791 +113
==========================================
+ Hits 7336 7609 +273
- Misses 398 405 +7
- Partials 85 89 +4
🚀 New features to boost your workflow:
|
GeiserX
added a commit
that referenced
this pull request
Nov 18, 2026
…d repaying in the wrong order (#460) * fix(fx): stop the broker-loan model trusting rows it cannot prove and repaying loans in the wrong order Follow-up to the late review of #456 (issue #449). The gate now fails closed. It turned the loan model on for a CashReport row with dates like "2025-00-01" .. "2025-99-31" (they held every date of 2025), for rows with no account id (blank matched blank), for a row with no endingCash (the parser's "0" reconciled REPRO, whose dollars end at 0), for the same row stamped by two brokers (deduplicated to one before the one-broker check), and when an opening short sale's inflow cancelled an orphan withholding's debit (the FX engine sees neither). The parser still gives Modelo 720 "0" for a missing endingCash and flags it. The ledger spends and repays in the account's order: - the CashReport's opening balance is the oldest currency, so it goes before later tracked lots (a conversion of 1000 on 1000 of opening and a newer 0.80 lot booked 100 in 2025 instead of 0, and 50 in 2026); - opening balance a same-day sale returns repays that day's loan first (500 of opening, a buy of 1000, a sale of 400: the account owes 100, not 500, and a later inflow of 500 repays 100); - a same-day payback repays only what the loan still owes (in «Tradicional con divisa», two same-day sales after a repayment threw 500 USD away and left the pool at 60 instead of 560); - in a loan currency the default now sees a sale with proceeds of 0 or less, as the gate counted it (a worthless sale's 5 USD commission stayed in the default's pool). The report gives one untracked note per currency and kind (an IBKR note no longer covers another broker's dollars), and when part of the debt's change is outside 1633/1637 (the default's stock line), the new report.fx_loan_repayment_manual note gives the part in 1633/1637 and asks to reconcile the rest by hand, in the 5 locales. No fixture changes in any FX method (38 fixtures, 7 option sets, JSON identical): none passes the gate. A merged IBKR + Degiro upload now gets two untracked notes (76.31 IBKR, 452.75 other) instead of one IBKR note of 529.07; its numbers do not change. * docs(fx): say what the loan gate rejects and when the debt adjustment needs a manual check traza-fx.md, casillas.md and the CLAUDE.md #449 Hard Trace now say that the opening balance goes before later lots, that only the shortfall after the available cash and an accepted late cover becomes a loan, which rows the gate rejects (invalid dates, blank accounts, no endingCash, the same row from two brokers, an opening short sale, an orphan withholding), how a same-day sale repays a loan that day, that a LOAN row's gain is the debit's commission share, and when the report asks to reconcile the debt part by hand. The review's traps and controls are recorded. * fix(fx): stop opening cash lost in a same-day loss sale from becoming a phantom broker loan In a loan currency every untracked parked slice is the Cash Report's opening balance, which the account really held. When a same-day loss sale did not return all of it, repayBorrowed still pushed the lost part as a #447 same-day debt. A later round trip that day paid it with real dollars, and the final conversion opened a loan nothing repaid (D2: 80 on a true 50; Z1: 160 on 145; both methods). The lost part is now discarded at once with the row closeDebts writes, counted in fx_traditional_opening. Untracked currencies outside the gate keep the #447 rule. New generator mode `loss` with 1500 of opening balance pins it: no LOAN row on the final conversion, pool 0. * fix(fx): give the plain loan note when the paying dollars cost the loan's rate by coincidence The _manual loan note fired for every repayment row that netted to 0. Shares bought with dollars funded at the loan's rate on the loan's day repaid it with a zero row. The note then said the debt's change sat in the sale of shares bought with the loan, which repaid nothing. Lowering 1633 by the debt part was right there, as it was for the same loan with funding at another rate. A zero row now counts as in 1633/1637. The exception is the default repaying with the loan's own borrowed principal that the shares' sale re-added at the loan's rate: there the stock line holds the change. «Tradicional con divisa» had the same mirror case (a shifted cost equal to the loan's rate) and now gets the plain note too.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When a buy spends more dollars than the account holds, the balance goes below zero and IBKR lends the difference. DeclaRenta treated those missing dollars as "untracked", as if they were an opening balance it could not see. When a later day's sale paid the debt, the engine put those dollars back in the pool, and a later conversion then spent dollars that were owed, not held.
The example in #449 gave −175 € in both FX methods. The real result is −145 €, and 200 phantom dollars stayed in the pool. Over 200 generated overdraft cycles, 151 missed in «Tradicional con divisa» and 129 in the default.
Fix
DeclaRenta now treats a balance below zero as a loan from the broker. It does this only when the IBKR Cash Report proves the account's cash:
The order of use is: the opening balance first, then the existing 7-day late cover, then a loan at that day's ECB rate for what is still missing. Later inflows repay the oldest loan first. Each repayment books
x × (loan rate − cost of the paying dollars)in 1633/1637. Interest charged while the balance is negative adds to the debt. A same-day round trip keeps the #447 rule. Monodivisa does not change.A new note gives the debt's own gain and loss. It says that STS 71/2021 puts that change in the base general (0304/0305) while the DGT (V2414-12) puts it in the base del ahorro, and how to move it out of 1633/1637 if you follow the Supreme Court. The FX trace shows each loan and each repayment.
Every other upload keeps today's path. The «Tradicional con divisa» untracked note now names an overdraft or margin loan as a possible cause. IBKR files get their own version (
report.fx_traditional_uncovered_ibkr) that says what a Cash Report needs to pass the gate.What users see
Limits
accountIdon its trades turns the gate off.Checks
tests/integration/fx-overdraft-loan.test.ts: 53 tests, 18 of them red on the pre-fix code.Closes #449