QuantConnect / Lean

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)
https://lean.io
Apache License 2.0
9.56k stars 3.23k forks source link

Review Accounting After a Cash Sync #8010

Closed AlexCatarino closed 2 months ago

AlexCatarino commented 4 months ago

Expected Behavior

After a cash sync, the cashbook shouldn't change a lot.

Actual Behavior

The live deployment to Kraken starts with:

CashBook Total Value:                ₿0.24
2024-04-05T00:00:49.7808038Z TRACE:: Total margin information: TotalMarginUsed: 0.18, MarginRemaining: 0.06

Then we have a cash sync where the margin information jumps:

2024-04-05T11:45:00.0572082Z TRACE:: Brokerage.PerformCashSync(): Sync cash balance
2024-04-05T11:45:10.4329261Z TRACE:: Total margin information: TotalMarginUsed: 0.13, MarginRemaining: 0.32

Potential Solution

N/A

Checklist

Martin-Molinero commented 4 months ago

5 is pretty big in BTC which is what the user is using, so it should be relative to the TPV I think

image

kraken, sounds like it accounting for the holdings again on each cash sync but should be the first only really

image

Marinovsky commented 3 months ago

After doing some research about this bug I found the following things:

  1. I found that the Margin Remaining value changes even without applying the balances values obtained from Kraken API each time the method KrakenBrokerage.GetCashBalance() is called. To find that I ran the algo BasicTemplateCryptoAlgorithm using live-kraken environment and USD as account currency, and commented the following line (531) so that the new balance cash amount wasn't applied to the algorithm's Cashbook: image image image

  2. Martin and I thought that the MarginReamining value could have been changing since Kraken was taking into account the profit/loss of an open position so that KrakenBrokerage.GetCashBalance() was always adjusting to the current price, profit/loss included, but LEAN wasn't. In order to see if our hypothesis was right we took 2 snapshots (with a difference of 10 minutes between them) of the state of the LEAN Holdings, Cashbook and TPV as well as the Holdings and Cash balances from Kraken API responses. After comparing those snapshots we found that the responses from the Kraken API changed just in two fields (value and net) but those weren't used when computing the cash balances for LEAN. Below is a screenshot of the difference between the Kraken resposes as well as the file with the two snapshots: image KrakenCashBalanceBugLogs.txt

Martin-Molinero commented 2 months ago

Shipping fix at https://github.com/QuantConnect/Lean.Brokerages.Kraken/pull/48, starting from version 16546