-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathbook.py
More file actions
1926 lines (1744 loc) · 75.2 KB
/
book.py
File metadata and controls
1926 lines (1744 loc) · 75.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# CoinTaxman
# Copyright (C) 2021 Carsten Docktor <https://github.com/provinzio>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import collections
import csv
import datetime
import decimal
import re
from collections import defaultdict
from pathlib import Path
from typing import Any, Optional
import config
import log_config
import misc
import transaction as tr
from core import kraken_asset_map
from database import set_price_db
from price_data import PriceData
log = log_config.getLogger(__name__)
class Book:
# Need to track state of duplicate deposit/withdrawal entries
# All deposits/withdrawals are held back until they occur a second time
# Initialize non-existing fields with None once they're called
kraken_held_ops: defaultdict[str, defaultdict[str, Any]] = defaultdict(
lambda: defaultdict(lambda: None)
)
def __init__(self, price_data: PriceData) -> None:
self.price_data = price_data
self.operations: list[tr.Operation] = []
def __bool__(self) -> bool:
return bool(self.operations)
def create_operation(
self,
operation: str,
utc_time: datetime.datetime,
platform: str,
change: decimal.Decimal,
coin: str,
row: int,
file_path: Path,
remark: Optional[str] = None,
) -> tr.Operation:
try:
Op = getattr(tr, operation)
except AttributeError:
log.error(
f"Could not recognize {operation=} from {platform=} in "
f"{file_path=} {row=}. "
"The operation type might have been removed or renamed. "
"Please open an issue or PR."
)
raise RuntimeError
kwargs = {}
if remark:
kwargs["remarks"] = [remark]
op = Op(utc_time, platform, change, coin, [row], file_path, **kwargs)
assert isinstance(op, tr.Operation)
return op
def _append_operation(
self,
op: tr.Operation,
) -> None:
# Discard operations after the `TAX_YEAR`.
# Ignore operations which make no change.
if op.utc_time.year <= config.TAX_YEAR and op.change != 0:
self.operations.append(op)
def append_operation(
self,
operation: str,
utc_time: datetime.datetime,
platform: str,
change: decimal.Decimal,
coin: str,
row: int,
file_path: Path,
remark: Optional[str] = None,
) -> None:
# Discard operations after the `TAX_YEAR`.
# Ignore operations which make no change.
if utc_time.year <= config.TAX_YEAR and change != 0:
op = self.create_operation(
operation,
utc_time,
platform,
change,
coin,
row,
file_path,
remark=remark,
)
self._append_operation(op)
def _read_binance(self, file_path: Path, version: int = 1) -> None:
platform = "binance"
operation_mapping = {
"Distribution": "Airdrop",
"Cash Voucher distribution": "Airdrop",
"Cashback Voucher": "Airdrop",
"Rewards Distribution": "Airdrop",
"Simple Earn Flexible Airdrop": "Airdrop",
"Airdrop Assets": "Airdrop",
"Crypto Box": "Airdrop",
"Launchpool Airdrop": "Airdrop",
"Megadrop Rewards": "Airdrop",
#
"Savings Interest": "CoinLendInterest",
"Savings purchase": "CoinLend",
"Savings Principal redemption": "CoinLendEnd",
"Savings distribution": "CoinLendInterest",
"Simple Earn Flexible Subscription": "CoinLend",
"Simple Earn Flexible Redemption": "CoinLendEnd",
"Simple Earn Flexible Interest": "CoinLendInterest",
"Simple Earn Locked Subscription": "CoinLend",
"Simple Earn Locked Redemption": "CoinLendEnd",
"Simple Earn Locked Rewards": "CoinLendInterest",
"Savings Distribution": "CoinLendInterest",
#
"BNB Vault Rewards": "CoinLendInterest",
"Launchpool Earnings Withdrawal": "CoinLendInterest",
#
"Commission History": "Commission",
"Commission Fee Shared With You": "Commission",
"Referrer rebates": "Commission",
"Referral Kickback": "Commission",
"Commission Rebate": "Commission",
# DeFi yield farming
"Liquid Swap add": "CoinLend",
"Liquid Swap remove": "CoinLendEnd",
"Liquid Swap rewards": "CoinLendInterest",
"Launchpool Interest": "CoinLendInterest",
#
"Super BNB Mining": "StakingInterest",
"POS savings interest": "StakingInterest",
"POS savings purchase": "Staking",
"POS savings redemption": "StakingEnd",
"ETH 2.0 Staking Rewards": "StakingInterest",
"Staking Purchase": "Staking",
"Staking Rewards": "StakingInterest",
"Staking Redemption": "StakingEnd",
#
"Fiat Deposit": "Deposit",
"Withdraw": "Withdrawal",
#
"Transaction Buy": "Buy",
"Transaction Spend": "Sell",
"Transaction Revenue": "Buy",
"Transaction Sold": "Sell",
"Transaction Fee": "Fee",
"Asset Recovery": "Sell",
}
with open(file_path, encoding="utf8") as f:
reader = csv.reader(f)
# Skip header.
next(reader)
for rowlist in reader:
if version == 1:
_utc_time, account, operation, coin, _change, remark = rowlist
elif version == 2:
(
_,
_utc_time,
account,
operation,
coin,
_change,
remark,
) = rowlist
else:
log.error("File version not Supported " + str(file_path))
raise NotImplementedError
row = reader.line_num
# Parse data.
utc_time = datetime.datetime.strptime(_utc_time, "%Y-%m-%d %H:%M:%S")
utc_time = utc_time.replace(tzinfo=datetime.timezone.utc)
change = misc.force_decimal(_change)
operation = operation_mapping.get(operation, operation)
if operation in (
"The Easiest Way to Trade",
"Small assets exchange BNB",
"Small Assets Exchange BNB",
"Transaction Related",
"Large OTC trading",
"Sell",
"Buy",
"Binance Convert",
):
operation = "Sell" if change < 0 else "Buy"
if operation == "Liquid Swap add/sell":
operation = "CoinLendEnd" if change < 0 else "CoinLend"
if operation == "Commission" and account != "Spot":
# All comissions will be handled the same way.
# As of now, only Spot Binance Operations are supported,
# so we have to change the account type to Spot.
account = "Spot"
if (
account in ("Spot", "P2P")
and operation
in (
"transfer_in",
"transfer_out",
)
or (
account in ("Spot", "Funding")
and operation == "Transfer Between Main and Funding Wallet"
)
):
# Ignore transfers
continue
change = abs(change)
# Validate data.
supported_account_types = ("Spot", "Savings", "Earn", "Funding")
assert account in supported_account_types, (
f"Other types than {supported_account_types} are currently "
f"not supported. Given account type is `{account}`. "
"Please create an Issue or PR."
)
assert operation
assert coin
assert change
if remark:
# Ignore default remarks
if remark in (
"Withdraw fee is included",
"Binance Earn",
"Binance Pay",
"Binance Launchpool",
) or remark.endswith(" to BNB"):
remark = None
# Do not warn for specific remarks
elif remark.startswith("Korrekturbuchung."):
pass
# Warn on other binance remarks, becuase all remarks should be some
# unnecessary default text which we'd like to ignore
else:
log.warning(
"I may have missed a remark in %s:%i: `%s`.",
file_path,
row,
remark,
)
self.append_operation(
operation, utc_time, platform, change, coin, row, file_path, remark
)
def _read_binance_v2(self, file_path: Path) -> None:
self._read_binance(file_path=file_path, version=2)
def _read_coinbase(self, file_path: Path) -> None:
platform = "coinbase"
operation_mapping = {
"Receive": "Deposit",
"Send": "Withdrawal",
"Coinbase Earn": "Buy",
"Learning Reward": "Buy",
"Rewards Income": "Staking",
}
with open(file_path, encoding="utf8") as f:
reader = csv.reader(f)
# Skip header.
try:
assert next(reader) # header line
assert next(reader) == []
assert next(reader) == []
assert next(reader) == []
assert next(reader) == ["Transactions"]
assert next(reader) # user row
assert next(reader) == []
fields = next(reader)
num_columns = len(fields)
# Coinbase export format from late 2021 and ongoing
if num_columns == 10:
assert fields == [
"Timestamp",
"Transaction Type",
"Asset",
"Quantity Transacted",
"Spot Price Currency",
"Spot Price at Transaction",
"Subtotal",
"Total (inclusive of fees)",
"Fees",
"Notes",
] or fields == [
"Timestamp",
"Transaction Type",
"Asset",
"Quantity Transacted",
"Spot Price Currency",
"Spot Price at Transaction",
"Subtotal",
"Total (inclusive of fees and/or spread)",
"Fees and/or Spread",
"Notes",
]
# Coinbase export format from mid 2021 and before
elif num_columns == 9:
assert fields == [
"Timestamp",
"Transaction Type",
"Asset",
"Quantity Transacted",
"EUR Spot Price at Transaction",
"EUR Subtotal",
"EUR Total (inclusive of fees)",
"EUR Fees",
"Notes",
]
else:
raise RuntimeError(
"Unknown Coinbase format: "
"Number of rows do not match known versions: "
f"{file_path}."
)
except AssertionError as e:
msg = (
"Unable to read coinbase file: Malformed header. "
f"Skipping {file_path}."
)
e.args += (msg,)
log.exception(e)
return
for columns in reader:
# Coinbase export format from late 2021 and ongoing
if num_columns == 10:
(
_utc_time,
operation,
coin,
_change,
_currency_spot,
_eur_spot,
_eur_subtotal,
_eur_total,
_eur_fee,
remark,
) = columns
# Coinbase export format from mid 2021 and before
elif num_columns == 9:
(
_utc_time,
operation,
coin,
_change,
_eur_spot, # Rounded price from CSV, unused
_eur_subtotal, # Cost without fees
_eur_total,
_eur_fee,
remark,
) = columns
_currency_spot = "EUR"
row = reader.line_num
# Parse data.
utc_time = datetime.datetime.strptime(_utc_time, "%Y-%m-%dT%H:%M:%SZ")
utc_time = utc_time.replace(tzinfo=datetime.timezone.utc)
operation = operation_mapping.get(operation, operation)
change = misc.force_decimal(_change)
# `eur_subtotal` and `eur_fee` are None for withdrawals.
eur_subtotal = misc.xdecimal(_eur_subtotal)
if eur_subtotal is None:
# Cost without fees from CSV is missing. This can happen for
# old transactions (<2018), event though something was bought.
# Calculate the `eur_subtotal` from `eur_spot`.
if eur_spot := misc.xdecimal(_eur_spot):
eur_subtotal = eur_spot * change
eur_fee = misc.xdecimal(_eur_fee)
# Validate data.
assert operation
assert coin
assert change
assert _currency_spot == "EUR"
# Calculated price
if eur_subtotal:
assert isinstance(eur_subtotal, decimal.Decimal)
price_calc = eur_subtotal / change
# Save price in our local database for later.
set_price_db(platform, coin, "EUR", utc_time, price_calc)
if operation == "Convert":
# Parse change + coin from remark, which is
# in format "Converted 0,123 ETH to 0,456 BTC".
match = re.match(
r"^Converted [0-9,\.]+ [A-Z]+ to "
r"(?P<change>[0-9,\.]+) (?P<coin>[A-Z]+)$",
remark,
)
assert match
_convert_change = match.group("change").replace(",", ".")
convert_change = misc.force_decimal(_convert_change)
convert_coin = match.group("coin")
eur_total = misc.force_decimal(_eur_total)
convert_eur_spot = eur_total / convert_change
self.append_operation(
"Sell", utc_time, platform, change, coin, row, file_path
)
self.append_operation(
"Buy",
utc_time,
platform,
convert_change,
convert_coin,
row,
file_path,
)
# Save convert price in local database, too.
set_price_db(
platform, convert_coin, "EUR", utc_time, convert_eur_spot
)
else:
# Add operation normally to the list.
self.append_operation(
operation, utc_time, platform, change, coin, row, file_path
)
# If it's a sell, add the corresponding buy to complement
# the trading pair.
if operation == "Sell":
assert isinstance(eur_subtotal, decimal.Decimal)
self.append_operation(
"Buy",
utc_time,
platform,
eur_subtotal,
"EUR",
row,
file_path,
)
# If it's a buy, add the corresponding sell to complement
# the trading pair.
elif operation == "Buy":
assert isinstance(eur_subtotal, decimal.Decimal)
self.append_operation(
"Sell",
utc_time,
platform,
eur_subtotal,
"EUR",
row,
file_path,
)
# Add paid fees to the list.
if eur_fee:
assert isinstance(eur_fee, decimal.Decimal)
self.append_operation(
"Fee", utc_time, platform, eur_fee, "EUR", row, file_path
)
def _read_coinbase_v2(self, file_path: Path) -> None:
self._read_coinbase(file_path=file_path)
def _read_coinbase_v3(self, file_path: Path) -> None:
self._read_coinbase(file_path=file_path)
def _read_coinbase_pro(self, file_path: Path) -> None:
platform = "coinbase_pro"
operation_mapping = {
"BUY": "Buy",
"SELL": "Sell",
}
with open(file_path, encoding="utf8") as f:
reader = csv.reader(f)
# Skip header.
next(reader)
for (
portfolio,
trade_id,
product,
operation,
_utc_time,
_size,
size_unit,
_price,
_fee,
total,
price_fee_total_unit,
) in reader:
row = reader.line_num
# Parse data.
utc_time = datetime.datetime.strptime(
_utc_time, "%Y-%m-%dT%H:%M:%S.%fZ"
)
utc_time = utc_time.replace(tzinfo=datetime.timezone.utc)
operation = operation_mapping.get(operation, operation)
size = misc.force_decimal(_size)
price = misc.force_decimal(_price)
fee = misc.xdecimal(_fee)
total_price = size * price
# Unused variables.
del portfolio
del trade_id
del product
del total
# Validate data.
assert operation
assert size
assert size_unit
assert price_fee_total_unit
self.append_operation(
operation, utc_time, platform, size, size_unit, row, file_path
)
if operation == "Sell":
self.append_operation(
"Buy",
utc_time,
platform,
total_price,
price_fee_total_unit,
row,
file_path,
)
elif operation == "Buy":
self.append_operation(
"Sell",
utc_time,
platform,
total_price,
price_fee_total_unit,
row,
file_path,
)
if fee:
self.append_operation(
"Fee",
utc_time,
platform,
fee,
price_fee_total_unit,
row,
file_path,
)
def _read_kraken_trades(self, file_path: Path) -> None:
log.error(
f"{file_path.name}: "
"Looks like this is a Kraken 'Trades' history, "
"but we need the 'Ledgers' history. "
"(See: Wiki - Exchange Kraken)"
)
def _read_kraken_ledgers(self, file_path: Path) -> None:
fee_sign_of_file: Optional[bool] = None
platform = "kraken"
operation_mapping = {
"spend": "Sell", # Sell ordered via 'Buy Crypto' or 'Dust Sweeping'
"receive": "Buy", # Buy ordered via 'Buy Crypto' or 'Dust Sweeping'
"reward": "StakingInterest",
"staking": "StakingInterest",
"deposit": "Deposit",
"withdrawal": "Withdrawal",
"rollover": "MarginFee",
}
with open(file_path, encoding="utf8") as f:
reader = csv.reader(f)
# Skip header.
next(reader)
for columns in reader:
num_columns = len(columns)
# Kraken ledgers export format from 2025 and ongoing
if num_columns == 11:
(
txid,
refid,
_utc_time,
_type,
subtype,
aclass,
_asset,
_wallet,
_amount,
_fee,
balance,
) = columns
# Kraken ledgers export format from October 2020 until 2025
elif num_columns == 10:
(
txid,
refid,
_utc_time,
_type,
subtype,
aclass,
_asset,
_amount,
_fee,
balance,
) = columns
# Kraken ledgers export format from September 2020 and before
elif num_columns == 9:
(
txid,
refid,
_utc_time,
_type,
aclass,
_asset,
_amount,
_fee,
balance,
) = columns
else:
log.error(
f"{file_path}: Unknown Kraken ledgers format: "
"Number of rows do not match known versions."
)
raise RuntimeError
row = reader.line_num
# Parse data.
utc_time = datetime.datetime.strptime(_utc_time, "%Y-%m-%d %H:%M:%S")
utc_time = utc_time.replace(tzinfo=datetime.timezone.utc)
change = misc.force_decimal(_amount)
# remove the appended .S for staked assets
_asset = _asset.removesuffix(".S")
coin = kraken_asset_map.get(_asset, _asset)
fee = misc.force_decimal(_fee)
# An older implementation expected always positive fees
# It seems that newer ledger files can have negative fee
# values instead.
if fee != 0:
# As soon as the first fee!=0 appears, check whether the
# fees are positive or negative. All fees in the file
# should have the same sign.
if fee_sign_of_file is None:
fee_sign_of_file = fee < 0
# Adjust the fee sign so that fees are always positive.
if fee_sign_of_file is True:
fee *= -1
if fee < 0:
log.error(
f"{file_path} row {row}: Unexpected fee sign. "
"All fees should have the same sign. "
"Please create an Issue or PR."
)
raise RuntimeError
operation = operation_mapping.get(_type)
if operation is None:
if _type == "trade":
operation = "Sell" if change < 0 else "Buy"
elif _type == "margin":
# Margin positions for Kraken always fall under income from
# capital, as the user can decide until the end if it is closed
# or settled. "rollover" entries contain margin fees between
# start and end. The start of a margin position is denoted with
# a "margin" entry with zero change. For closed positions, the
# end is marked with a "margin" entry containing the net
# gain/loss of the position.
# If the change is zero, consider only the fees.
if change == 0:
operation = "MarginFee"
elif change > 0:
operation = "MarginGain"
else:
operation = "MarginLoss"
elif _type == "settled":
# "settled" entries mark the end of settled positions.
operation = "MarginGain" if change > 0 else "MarginLoss"
elif _type == "transfer":
if num_columns == 9:
# for backwards compatibility assume Airdrop for staking
log.warning(
f"{file_path} row {row}: Staking is not supported for"
"old Kraken ledger formats. "
"Please create an Issue or PR."
)
operation = "Airdrop"
elif subtype == "stakingfromspot":
operation = "Staking"
elif subtype == "stakingtospot":
operation = "StakingEnd"
elif subtype in ["spottostaking", "spotfromstaking"]:
# duplicate entries for staking actions
continue
elif subtype in ["spottofutures", "spotfromfutures"]:
# transfer between spot and futures
continue
else:
log.error(
f"{file_path} row {row}: Order subtype '{subtype}' is "
"currently not supported. Please create an Issue or PR."
)
raise RuntimeError
elif _type == "earn":
if subtype == "reward":
operation = "StakingInterest"
elif subtype == "migration":
# Migration of "x.S" legacy staking balance to new staking
# infrastructure in "earn / bonded" wallet
continue
elif subtype == "allocation":
if change > 0:
operation = "Staking"
else:
# duplicate entries for staking actions
continue
elif subtype == "deallocation":
if change > 0:
operation = "StakingEnd"
else:
# duplicate entries for staking actions
continue
else:
log.error(
f"{file_path} row {row}: Order subtype '{subtype}' is "
"currently not supported. Please create an Issue or PR."
)
raise RuntimeError
else:
log.error(
f"{file_path} row {row}: Other order type '{_type}' is "
"currently not supported. Please create an Issue or PR."
)
raise RuntimeError
change = abs(change)
# Validate data.
assert operation
assert coin
# Margin trading: Add operations and fees to list.
if operation in ["MarginFee", "MarginGain", "MarginLoss"]:
if operation == "MarginFee":
assert (
change == 0
), "Margin fee operation should only contain fee."
if change:
# Add margin gain/losses to operation list.
self.append_operation(
operation, utc_time, platform, change, coin, row, file_path
)
if fee:
self.append_operation(
"MarginFee", utc_time, platform, fee, coin, row, file_path
)
# Skip duplicate entries for deposits / withdrawals and additional
# deposit / withdrawal lines for staking / unstaking / staking reward
# actions.
# The second deposit and the first withdrawal need to be considered,
# since these are the points in time where the user actually has the
# assets at their disposal. The first deposit and second withdrawal are
# in the public trade history and are skipped.
# For staking / unstaking / staking reward actions, deposits /
# withdrawals only occur once and will be ignored.
# The "appended" flag stores if an operation for a given refid has
# already been appended to the operations list:
# == None: Initial value (first occurrence)
# == False: No operation has been appended (second occurrence)
# == True: Operation has already been appended, this should not happen
elif operation in ["Deposit", "Withdrawal"]:
assert change
# First, create the operations
op = self.create_operation(
operation, utc_time, platform, change, coin, row, file_path
)
op_fee = None
if fee != 0:
op_fee = self.create_operation(
"Fee", utc_time, platform, fee, coin, row, file_path
)
# If this is the first occurrence, set the "appended" flag to false
# and don't append the operation to the list. Instead, store the
# data for verifying or appending it later.
if self.kraken_held_ops[refid]["appended"] is None:
self.kraken_held_ops[refid]["appended"] = False
self.kraken_held_ops[refid]["operation"] = op
self.kraken_held_ops[refid]["operation_fee"] = op_fee
# If this is the second occurrence, append a new operation, set the
# "appended" flag to True and assert that the data of this operation
# agrees with the data of the first occurrence.
elif self.kraken_held_ops[refid]["appended"] is False:
self.kraken_held_ops[refid]["appended"] = True
try:
# Make sure, that the found operations with the
# same refid have the same operation type, amount
# of change and same coin.
assert isinstance(
op, type(self.kraken_held_ops[refid]["operation"])
), (
"operation "
f"({op.type_name} != "
f'{self.kraken_held_ops[refid]["operation"].type_name})'
)
assert (
op.change
== self.kraken_held_ops[refid]["operation"].change
), (
"change "
f"({op.change} != "
f'{self.kraken_held_ops[refid]["operation"].change})'
)
assert (
op.coin == self.kraken_held_ops[refid]["operation"].coin
), (
"coin "
f"({op.coin} != "
f'{self.kraken_held_ops[refid]["operation"].coin})'
)
except AssertionError as e:
# Row is internally saved as list[int].
first_row = self.kraken_held_ops[refid]["operation"].line[0]
log.error(
"Two internal kraken operations matched by the "
f"same {refid=} don't have the same {e}.\n"
"CoinTaxman expects, that these two operations "
"have the same type of operation, amount of "
"change and the same coin.\n"
f"See {file_path} in row {first_row} and "
f"{row}.\n"
"Please create an Issue or PR."
)
raise RuntimeError
# For deposits, this is all we need to do before appending the
# operation. For withdrawals, we need to append the first
# withdrawal as soon as the second withdrawal occurs. Therefore,
# overwrite the operation with the stored first withdrawal.
if operation == "Withdrawal":
op = self.kraken_held_ops[refid]["operation"]
op_fee = self.kraken_held_ops[refid]["operation_fee"]
# Finally, append the operations and delete the stored
# operations to reduce memory consumption
self._append_operation(op)
if op_fee:
self._append_operation(op_fee)
del self.kraken_held_ops[refid]["operation"]
del self.kraken_held_ops[refid]["operation_fee"]
# If an operation with the same refid has been already appended,
# this is the third occurrence. Throw an error if this happens.
elif self.kraken_held_ops[refid]["appended"] is True:
log.error(
f"{file_path} row {row}: More than two entries with refid "
f"{refid} should not exist ({operation}). "
"Please create an Issue or PR."
)
raise RuntimeError
# This should never happen
else:
log.error(
f"{file_path} row {row}: Unknown value for appended "
f"operation flag {self.kraken_held_ops[refid]['appended']}."
"Please create an Issue or PR."
)
raise TypeError
# for all other operation types
else:
assert change
self.append_operation(
operation, utc_time, platform, change, coin, row, file_path
)
if fee != 0:
self.append_operation(
"Fee", utc_time, platform, fee, coin, row, file_path
)
if operation == "StakingInterest":
# For Kraken, the rewarded coins are added to the staked
# portfolio. TODO (for MULTI_DEPOT only): Directly add the
# rewarded coins to the staking depot (not like here with the
# detour of adding it to spot and then staking the same amount)
self.append_operation(
"Staking", utc_time, platform, change, coin, row, file_path
)
def _read_kraken_ledgers_old(self, file_path: Path) -> None:
self._read_kraken_ledgers(file_path)
def _read_kraken_ledgers_v2(self, file_path: Path) -> None:
self._read_kraken_ledgers(file_path)
def _read_bitpanda_pro_trades(self, file_path: Path) -> None:
"""Reads a trade statement from Bitpanda Pro.
Args:
file_path (Path): Path to Bitpanda trade history.
"""
platform = "bitpanda_pro"
with open(file_path, encoding="utf8") as f:
reader = csv.reader(f)
# skip header
next(reader)
line = next(reader)
transaction_file_warn = (
f"{file_path} looks like a Bitpanda transaction file."
" Skipping. Please download the trade history instead."
)
# for transactions, it's currently written "id" (small)
if line[0].startswith("Account id :"):
log.warning(transaction_file_warn)
return
assert line[0].startswith("Account ID:")
line = next(reader)
# empty line - still keep this check in case Bitpanda changes the
# transaction file to match the trade header (casing)
if not line:
log.warning(transaction_file_warn)
return
elif line[0] != "Bitpanda Pro trade history":
log.warning(
f"{file_path} doesn't look like a Bitpanda trade file. Skipping."
)
return
line = next(reader)
assert line in [
[
"Order ID",
"Trade ID",
"Type",
"Market",
"Amount",
"Amount Currency",
"Price",
"Price Currency",
"Fee",
"Fee Currency",
"Time (UTC)",
],
[
"Order ID",
"Trade ID",
"Type",
"Market",
"Amount",