Skip to content

Commit

Permalink
ADD basic transfer matching algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
jhoogstraat committed Apr 13, 2022
1 parent 539fd5b commit 081c395
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
50 changes: 50 additions & 0 deletions src/book.py
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,56 @@ def detect_exchange(self, file_path: Path) -> Optional[str]:

return None

def resolve_deposits(self) -> None:
"""Matches withdrawals and deposits by referencing the related
withdrawal on the deposit.
A match is found when:
A. The coin is the same
B. The deposit amount is between 0.99 and 1 times the withdrawal amount.
Returns:
None
"""
sorted_ops = tr.sort_operations(self.operations, ["utc_time"])

def is_match(withdrawal: tr.Withdrawal, deposit: tr.Deposit) -> bool:
return (
withdrawal.coin == deposit.coin
and withdrawal.change * decimal.Decimal(0.99)
<= deposit.change
<= withdrawal.change
)

withdrawal_queue: list[tr.Withdrawal] = []

for op in sorted_ops:
# log.debug(op.utc_time)
if isinstance(op, tr.Withdrawal):
if not misc.is_fiat(op.change):
withdrawal_queue.append(op)
elif isinstance(op, tr.Deposit):
if not misc.is_fiat(op.coin):
try:
match = next(w for w in withdrawal_queue if is_match(w, op))
op.link = match
withdrawal_queue.remove(match)
log.info(
"Linking transfer: "
f"{match.change} {match.coin} "
f"({match.platform}, {match.utc_time}) "
f"-> {op.change} {op.coin} "
f"({op.platform}, {op.utc_time})"
)
except StopIteration:
log.warning(
"No matching withdrawal operation found for deposit of "
f"{match.change} {match.coin} "
f"({match.platform}, {match.utc_time})"
)

log.info("Finished matching")

def get_price_from_csv(self) -> None:
"""Calculate coin prices from buy/sell operations in CSV files.
Expand Down
1 change: 1 addition & 0 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def main() -> None:
# (as long as there are only one buy/sell pair per time,
# might be problematic otherwhise).
book.merge_identical_operations()
book.resolve_deposits()
book.get_price_from_csv()
book.match_fees_with_operations()

Expand Down
2 changes: 1 addition & 1 deletion src/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ class Commission(Transaction):


class Deposit(Transaction):
pass
link: typing.Optional[Withdrawal] = None


class Withdrawal(Transaction):
Expand Down

0 comments on commit 081c395

Please sign in to comment.