-
Notifications
You must be signed in to change notification settings - Fork 22
/
bitcoin_gains.py
executable file
·1811 lines (1623 loc) · 72.4 KB
/
bitcoin_gains.py
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
#!/usr/bin/env python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Authors: Robert Bradshaw <[email protected]>
"""
import abc
import argparse
from collections import defaultdict
import csv
import decimal
import hashlib
import heapq
import json
import re
import os
import pprint
import sys
import time
import urllib.request, urllib.error, urllib.parse
import urllib.parse
try:
import readline
except ImportError:
pass
parser = argparse.ArgumentParser(description='Compute capital gains/losses.')
parser.add_argument('histories', metavar='FILE', nargs='+',
help='a csv or json file')
parser.add_argument('--ignore_old_coinbase', default='auto',
help='Ignore old coinbase files (in favor of api-downloaded ones).')
parser.add_argument('--fmv_url', dest='fmv_urls',
action='append',
default=[
'https://api.blockchain.info/charts/market-price?timespan=all&daysAverageString=1&format=csv',
],
help='fair market value prices urls')
parser.add_argument('--data', dest='data', default='data.json',
help='external transaction info')
parser.add_argument('--transfer_window_hours', default=24)
parser.add_argument('--method', default='fifo', help='used to select which lot to sell; one of fifo, lifo, oldest, newest')
parser.add_argument("-y", "--non_interactive", help="don't prompt the user to confirm external transfer details",
action="store_true")
parser.add_argument("--consolidate_bitcoind", help="treat bitcoind accounts as one", action="store_true")
parser.add_argument("--consolidate_coinbase", help="treat coinbase accounts as one", action="store_true")
parser.add_argument("--external_transactions_file", default="external_transactions.json")
parser.add_argument("--flat_transactions_file", default="all_transactions.csv")
parser.add_argument("--nowash", default=False, action="store_true")
parser.add_argument("--buy_in_sell_month", default=False, action="store_true")
parser.add_argument("--cost_basis", default=False, action="store_true")
parser.add_argument("--end_date", metavar="YYYY-MM-DD")
parser.add_argument("--list_purchases", default=False, action="store_true")
parser.add_argument("--list_gifts", default=False, action="store_true")
class TransactionParser(object):
counter = 0
def can_parse(self, filename):
# returns bool
raise NotImplementedError
def parse_file(self, filename):
# returns list[Transaction]
raise NotImplementedError
def merge(self, transactions):
# returns Transaction
assert len(transactions) == 1
return transactions[0]
def merge_some(self, transactions):
# returns list[Transaction]
return [self.merge(transactions)]
def default_account(self):
return self.__class__.__name__.replace('Parser', '').rstrip('0123456789')
def check_complete(self):
pass
def reset(self):
pass
def unique(self, timestamp):
self.counter += 1
return "%s:%s:%s" % (self.default_account(), timestamp, self.counter)
class BitcoindParser(TransactionParser):
def can_parse(self, filename):
# TODO: This is way to loose...
start = re.sub(r'\s+', '', open(filename).read(100))
# Old Bitcoin Core versions begin with "account" key; newer versions
# begin with "address" key instead.
return start.startswith('[{"account":') or start.startswith('[{"address":')
def parse_file(self, filename):
for item in json.load(open(filename)):
timestamp = time.localtime(item['time'])
item['amount'] = decimal.Decimal(item['amount']).quantize(decimal.Decimal('1e-8'))
item['fee'] = decimal.Decimal(item.get('fee', 0)).quantize(decimal.Decimal('1e-8'))
# Include the vout so that atomic payments don't get dropped.
item['txid'] = item['txid'] + ":" + str(item['vout'])
info = ' '.join([item.get('to', ''), item.get('comment', ''), item.get('label', ''), item.get('address', '')])
if not parsed_args.consolidate_bitcoind:
account = ('bitcoind-%s' % item['account']).strip('-')
else:
account = 'bitcoind'
confirmations = item['confirmations']
# Negative confirmations indicate a conflicted transaction.
if confirmations < 0:
continue
if item['category'] == 'receive':
yield Transaction(timestamp, 'deposit', item['amount'], 0, 0, id=item['txid'], info=info, account=account)
elif item['category'] == 'generate':
yield Transaction(timestamp, 'deposit', item['amount'], 0, 0, id=item['txid'], info=info, account=account)
elif item['category'] == 'send':
yield Transaction(timestamp, 'withdraw', item['amount'], 0, 0, fee_btc=item.get('fee', 0), id=item['txid'], info=info, account=account)
elif item['category'] == 'move' and item['amount'] < 0 and not parsed_args.consolidate_bitcoind:
t = Transaction(timestamp, 'transfer', item['amount'], 0, 0, info=info, account=account)
t.dest_account = ('bitcoind-%s' % item['otheraccount']).strip('-')
yield t
def merge_some(self, transactions):
# don't double-count the fee
for t in transactions[1:]:
t.fee_btc = 0
return transactions
class RawBitcoinInfoParser(TransactionParser):
@staticmethod
def fee(txn):
return (sum(input['prev_out']['value'] for input in txn['inputs'])
- sum(output['value'] for output in txn['out'])) / satoshi_to_btc
@staticmethod
def is_withdrawal(txn, addresses):
if any(input['prev_out']['addr'] in addresses for input in txn['inputs']):
if not all(input['prev_out']['addr'] in addresses for input in txn['inputs']):
raise NotImplementedError("Sends from mixed controlled and not controlled addresses %s" % txn)
return True
else:
return False
class AddressListParser(RawBitcoinInfoParser):
"""Treat a set of public addresses as a single acount.
Parses a simple text file with one public address per line, downloading the
transaction history from blockchain.info.
This is useful for any public wallet where you can enumerate addresses
used but otherwise can't export transactions. This includes many
lightweight, mobile, and hardware wallets.
"""
def can_parse(self, filename):
for line in open(filename):
line = line.strip()
if not line or line.startswith('#'):
continue
elif re.match('^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$', line):
return True
else:
return False
def parse_file(self, filename):
addresses = []
for line in open(filename):
line = line.strip()
if not line or line.startswith('#'):
continue
else:
addresses.append(line)
txns = {}
for address in addresses:
for txn in json.load(
open_cached('https://blockchain.info/address/%s?format=json' % address))['txs']:
if txn['hash'] not in txns:
txns[txn['hash']] = txn
for txn in txns.values():
timestamp = time.localtime(txn['time'])
if self.is_withdrawal(txn, addresses):
fee = self.fee(txn)
for ix, output in enumerate(txn['out']):
if output['addr'] not in addresses:
yield Transaction(timestamp, 'withdraw', -decimal.Decimal(output['value']) / satoshi_to_btc, 0, id="withdraw:%s:%s" % (txn['hash'], ix), account=filename, fee_btc=fee, txid=txn['hash'])
fee = 0
else:
for ix, output in enumerate(txn['out']):
if output['addr'] in addresses:
yield Transaction(timestamp, 'deposit', decimal.Decimal(output['value']) / satoshi_to_btc, 0, id="deposit:%s:%s" % (txn['hash'], ix), account=filename, txid=txn['hash'])
def merge_some(self, transactions):
return transactions
class BitcoinInfoParser(RawBitcoinInfoParser):
# https://blockchain.info/address/ADDRESS?format=json
def can_parse(self, filename):
# TODO: This is way to loose...
head = open(filename).read(200)
return head[0] == '{' and '"n_tx":' in head and '"address":' in head
def parse_file(self, filename):
all = json.load(open(filename))
address = all['address']
for txn in all['txs']:
timestamp = time.localtime(txn['time'])
if self.is_withdrawal(txn, [address]):
fee = self.fee(txn)
for ix, output in enumerate(txn['out']):
yield Transaction(timestamp, 'withdraw', -decimal.Decimal(output['value']) / satoshi_to_btc, 0, id="withdraw:%s:%s" % (txn['hash'], ix), account=address, fee_btc=fee, txid=txn['hash'])
fee = 0
else:
for ix, output in enumerate(txn['out']):
if output['addr'] == address:
yield Transaction(timestamp, 'deposit', decimal.Decimal(output['value']) / satoshi_to_btc, 0, id="%s-%s:%s" % (address, txn['hash'], ix), account=address, txid=txn['hash'])
def merge_some(self, transactions):
return transactions
class CsvParser(TransactionParser):
expected_header = None
def can_parse(self, filename):
return re.match(self.expected_header, open(filename).readline().strip())
def parse_row(self, row):
raise NotImplementedError
def parse_file(self, filename):
self.filename = filename
self.start()
first = True
for ix, row in enumerate(csv.reader(open(filename))):
if not row or first:
first = False
self.header = row
continue
elif row[0].startswith('#'):
continue
else:
try:
transaction = self.parse_row(row)
if transaction is not None:
yield transaction
except Exception:
print(ix, row)
raise
for transaction in self.finish():
yield transaction
def start(self):
pass
def finish(self):
return ()
class BitstampParser(CsvParser):
expected_header = 'Type,Datetime,BTC,USD,BTC Price,FEE,Sub Type'
def parse_row(self, row):
type, timestamp, btc, usd, price, fee, _, _ = row
timestamp = time.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
if type == '0':
return Transaction(timestamp, 'deposit', btc, 0, 0)
elif type == '1':
return Transaction(timestamp, 'withdraw', btc, 0, 0)
elif type == '2':
return Transaction(timestamp, 'trade', btc, usd, price, fee)
else:
raise ValueError(type)
class BitstampParser2(CsvParser):
expected_header = 'Type,Datetime,Account,Amount,Value,Rate,Fee,Sub Type'
@staticmethod
def _trim(s, suffix):
if not s:
return None
else:
assert s.endswith(suffix), (s, suffix)
return s[:-len(suffix)]
_last_timestamp = None
def add_secs(self, timestamp):
# Add seconds to preserve order in file, as granularity is only minutes.
if timestamp == self._last_timestamp:
self._secs += 1
return time.localtime(time.mktime(timestamp) + self._secs)
else:
self._last_timestamp = timestamp
self._secs = 0
return timestamp
def parse_row(self, row):
type, timestamp, _, btc, usd, price, fee, buy_sell = row
timestamp = self.add_secs(time.strptime(timestamp, '%b. %d, %Y, %I:%M %p'))
btc = self._trim(btc, ' BTC')
usd = self._trim(usd, ' USD')
price = self._trim(price, ' USD')
fee = self._trim(fee, ' USD') or 0
if type == 'Deposit':
return Transaction(timestamp, 'deposit', btc, 0, 0)
elif type == 'Withdrawal':
return Transaction(timestamp, 'withdraw', '-' + btc, 0, 0)
else:
if buy_sell == 'Sell':
btc = '-' + btc
else:
usd = '-' + usd
return Transaction(timestamp, 'trade', btc, usd, price, fee)
class TransactionParser(CsvParser):
expected_header = 'timestamp,account,type,btc,usd,fee_btc,fee_usd,info'
def parse_row(self, row):
if not row[0] or row[0][0] == '#':
return None
timestamp,account,type,btc,usd,fee_btc,fee_usd,info = row
timestamp = time.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
return Transaction(timestamp, type, btc, usd, fee_btc=fee_btc, fee_usd=fee_usd, account=account, info=info)
class ElectrumParser(CsvParser):
# expected_header = 'transaction_hash,label,confirmations,value,fee,balance,timestamp'
electrum_version = 0
def can_parse(self, filename):
first_line = open(filename).readline().strip()
if re.match ('transaction_hash,label,confirmations,value,timestamp', first_line): # Electrum 2.5.4
self.electrum_version = 2
elif re.match ('transaction_hash,label,confirmations,value,fiat_value,fee,fiat_fee,timestamp', first_line): # Electrum 3.x
self.electrum_version = 3
else:
return False
return True
def parse_row(self, row):
if self.electrum_version == 2:
transaction_hash,label,confirmations,value,timestamp = row
fee = tx_fee(transaction_hash)
# TODO: Why isn't this exported anymore?
timestamp = time.strptime(timestamp, '%Y-%m-%d %H:%M')
elif self.electrum_version == 3:
transaction_hash,label,confirmations,value,fiat_value,fee,fiat_fee,timestamp = row
fee = fee[:-4] #Remove the " BTC"
timestamp = time.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
value = value[:-4] #Remove the " BTC" at the end
if value[-1] == ".":
value = value[:-1] #remove decimal point if nothing follows it. Not doing so confuses python.
if value[0] != "-": #So it's a positive... add a "+" to make it like the electrum 2 string
value = "+" + value
else:
raise ValueError("Electrum parser: Unknown format")
timestamp = time.localtime(time.mktime(timestamp) + 7*60*60)
if not label:
label = 'unknown'
elif label[0] == '<' and label[-1] != '>':
label = label[1:]
common = dict(usd=None, info=label, id=transaction_hash, txid=transaction_hash)
if value[0] == '+':
return Transaction(timestamp, 'deposit', value[1:], **common)
else:
assert value[0] == '-'
true_value = decimal.Decimal(value) + decimal.Decimal(fee)
if true_value == 0:
return Transaction(timestamp, 'fee', fee, **common)
else:
return Transaction(timestamp, 'withdraw', true_value, fee_btc=fee, **common)
def merge_some(self, transactions):
return transactions
class NewCoinbaseParser(CsvParser):
def can_parse(self, filename):
first_line = open(filename).readline().strip()
if 'You can use this transaction report to inform your likely tax obligations' in first_line and 'Coinbase' in first_line:
if not parsed_args.consolidate_coinbase:
raise RuntimeError(
'New-style coinbase transaction are missing wallet designations; '
'please use download-coinbase.py '
'or pass --consolidate_coinbase to treat all Coinbase wallets as one.'
'WARNING: This report is lacks all transfers to/from Coinbase Pro, '
'and will give incorrect results if there are any such transctions.')
else:
return True
def reset(self):
self.started = False
def parse_row(self, row):
if not self.started:
if row[0] == 'Timestamp':
self.header = row
self.started = True
return None
data = dict(zip(self.header, row))
if data['Asset'] != 'BTC':
return None
timestamp = time.strptime(data['Timestamp'], '%Y-%m-%dT%H:%M:%SZ')
type = data['Transaction Type'].lower()
if type in ('paid for an order', 'send'):
type = 'withdraw'
elif type in ('receive',):
type = 'deposit'
elif type not in ('buy', 'sell'):
raise ValueError('Unknown type of transaction: %s' % type)
btc = data['Quantity Transacted']
usd = data['USD Subtotal'] or 0
if not usd:
usd = decimal.Decimal(data['USD Spot Price at Transaction']) * decimal.Decimal(btc)
if type in ('buy',):
usd = '-%s' % usd
if type in ('sell', 'withdraw'):
btc = '-%s' % btc
if type in ('buy', 'sell'):
type = 'trade'
info = data.get('Notes')
if type == 'withdraw':
if data['Transaction Type'] != 'Paid for an order':
print('Warning: bitcoin fees not specified for Coinbase %s, may not match external transaction.' % info)
fee_btc = 0
else:
fee_btc = 0
fee_usd = data['USD Fees'] or 0
account = 'Coinbase:consolidated'
return Transaction(timestamp, type, btc, usd, fee_btc=fee_btc, fee_usd=fee_usd, account=account, info=info)
class DownloadedCoinbaseParser(TransactionParser):
expected_header = '# Coinbase downloaded transactions .*'
def can_parse(self, filename):
return re.match(self.expected_header, open(filename).readline().strip())
def parse_file(self, filename):
with open(filename) as fin:
fin.readline()
data = json.load(fin)
if parsed_args.consolidate_coinbase:
account = 'Coinbase:consolidated'
else:
account = 'Coinbase:%s:%s' % (data['account']['name'], data['account']['id'])
for transaction in data['transactions'].values():
date, hour = transaction['created_at'].split('Z')[0].split('T')
timestamp = time.strptime(date + " " + hour, '%Y-%m-%d %H:%M:%S')
assert transaction['amount']['currency'] == 'BTC'
btc = transaction['amount']['amount']
if 'native_amount' in transaction and transaction['native_amount']['currency'] == 'USD':
usd = transaction['native_amount']['amount']
if 'network' in transaction:
txid = transaction['network'].get('hash')
fee_btc = transaction['network'].get('transaction_fee')
else:
txid = None
fee_btc = None
if transaction['type'] == 'buy':
type = 'trade'
usd = '-' + usd
elif transaction['type'] == 'sell':
type = 'trade'
usd = '-' + usd
elif transaction['type'] in ('send', 'pro_deposit', 'pro_withdrawal', 'vault_deposit', 'vault_withdrawal', 'order', 'exchange_deposit', 'exchange_withdrawal', 'transfer'):
if btc[0] == '-':
type = 'withdraw'
else:
type = 'deposit'
else:
raise ValueError('Unknown type: %s' % transaction['type'])
yield Transaction(
id=transaction['id'],
account=account,
timestamp=timestamp,
btc=btc,
usd=usd,
type=type,
info=transaction['details']['title'] + ' ' + transaction['details']['subtitle'],
txid=txid)
class CoinbaseParser(CsvParser):
expected_header = r'(User,.*,[0-9a-f]+)|(^Transactions$)'
started = False
def reset(self):
self.account = None
self.started = False
def parse_file(self, filename):
if parsed_args.ignore_old_coinbase == 'auto':
# Actually reset the argument and fall through to do it just once.
new_coinbase_parser = DownloadedCoinbaseParser()
for path in parsed_args.histories:
if new_coinbase_parser.can_parse(path):
parsed_args.ignore_old_coinbase = 'true'
break
else:
parsed_args.ignore_old_coinbase = 'false'
if parsed_args.ignore_old_coinbase.lower() in ('true', 'yes'):
ignore_old_coinbase = True
elif parsed_args.ignore_old_coinbase.lower() in ('false', 'no'):
ignore_old_coinbase = True
else:
raise ValueError('Unknown value for ignore_old_coinbase: %s' % parsed_args.ignore_old_coinbase)
if not ignore_old_coinbase:
yield from super(CoinbaseParser, self).parse_file(filename)
def parse_row(self, row):
if not self.started:
if row[0] == 'Account':
self.account = 'Coinbase:%s:%s' % (row[1], row[2])
raw_row = ",".join(row)
if (raw_row.startswith('Timestamp,Balance,')
or raw_row.startswith('User,')
or raw_row.startswith('Account,')):
# Coinbase has multiple header lines.
return None
self.started = True
timestamp, _, btc, _, to, note, _, total, total_currency = row[:9]
date, hour, zone = timestamp.split()
timestamp = time.strptime(date + " " + hour, '%Y-%m-%d %H:%M:%S')
offset = int(zone[:-2]) * 3600 + int(zone[-2:]) * 60
timestamp = time.localtime(time.mktime(timestamp) - offset)
if 'will arrive in your bank account' in note:
note = '$' + note
if '$' in note:
# It's a buy/sell
if total:
assert total_currency == 'USD'
usd = total
else:
prices = re.findall(r'\$\d+\.\d+', note)
if len(prices) != 1:
raise ValueError("Ambiguous or missing price: %s" % note)
usd = prices[0][1:]
type = 'trade'
if 'Paid for' in note or 'Bought' in note:
usd = '-' + usd
else:
usd = 0
type = 'deposit' if float(btc) > 0 else 'withdraw'
info = " ".join([note, to])
if parsed_args.consolidate_coinbase:
account = 'Coinbase:consolidated'
elif True:
account = self.account or self.filename
else:
account = None
if re.match('[0-9a-f]{60,64}', row[-1]):
txid = row[-1]
else:
txid = None
return Transaction(timestamp, type, btc, usd, info=info, account=account, txid=txid)
# AKA Coinbase Pro
class GdaxParser(CsvParser):
def parse_time(self, stime):
return time.strptime(stime.replace('Z', '000'), '%Y-%m-%dT%H:%M:%S.%f')
def default_account(self):
return 'CoinbasePro'
class GdaxFillsParser(GdaxParser):
expected_header = '(portfolio,)?trade id,product,side,created at,size,size unit,price,fee,total,price/fee/total unit'
def parse_row(self, row):
if self.header[0] == 'portfolio':
account = row.pop(0)
if account == 'default':
account = self.default_account()
else:
account = self.default_account()
trade, product, buy_sell, stime, btc, unit, price, fee_usd, total, pft_unit = row
if product != 'BTC-USD':
return None
assert unit == 'BTC' and pft_unit == 'USD'
timestamp = self.parse_time(stime)
usd = decimal.Decimal(total) + decimal.Decimal(fee_usd)
if buy_sell == 'BUY':
return Transaction(timestamp, 'trade', btc, usd, fee_usd=fee_usd, account=account)
elif buy_sell == 'SELL':
return Transaction(timestamp, 'trade', '-' + btc, usd, fee_usd=fee_usd, account=account)
else:
raise ValueError("Unknown transactiont type: %s" % buy_sell)
class GdaxAccountParser(GdaxParser):
expected_header = '(portfolio,)?type,time,amount,balance,amount/balance unit,transfer id,trade id,order id'
def parse_row(self, row):
if self.header[0] == 'portfolio':
account = row.pop(0)
if account == 'default':
account = self.default_account()
else:
account = self.default_account()
type, stime, amount, _, unit, tid, _, _ = row
if unit != 'BTC':
# Ignore non-BTC withdrawals and deposits.
return None
timestamp = self.parse_time(stime)
if type == 'match':
return None # handled in fills
elif type == 'deposit':
return Transaction(timestamp, 'deposit', amount, 0, id=tid, account=account)
elif type == 'withdrawal':
return Transaction(timestamp, 'withdraw', amount, 0, id=tid, account=account)
else:
raise ValueError("Unknown transactiont type: %s" % type)
class KrakenParser(CsvParser):
def start(self):
self._trades = defaultdict(dict)
def can_parse(self, filename):
first_line = open(filename).readline().strip()
if first_line.endswith('"ledgers"'):
raise ValueError("Use ledger, not trade, export for Kraken.")
elif first_line == '"txid","refid","time","type","aclass","asset","amount","fee","balance"':
# Old style.
return True
elif first_line == '"txid","refid","time","type","subtype","aclass","asset","amount","fee","balance"':
# New style.
return True
def parse_row(self, row):
if len(row) == 10:
txid, refid, ktimestamp, ktype, _, _, asset, amount, fee, _ = row
else:
txid, refid, ktimestamp, ktype, _, asset, amount, fee, _ = row
timestamp = time.strptime(ktimestamp, '%Y-%m-%d %H:%M:%S')
if ktype == 'trade':
info = self._trades[refid]
assert asset not in info
info[asset] = row
if len(info) >= 3 and 'XXBT' in info:
btc = info['XXBT'][6]
if 'ZUSD' in info:
usd = info['ZUSD'][6]
type = 'trade'
else:
usd = 0
type = 'deposit' if float(btc) > 0 else 'withdraw'
del self._trades[refid]
return Transaction(timestamp, type, btc, usd)
else:
return
elif asset != 'XXBT':
return None
if ktype == 'deposit':
return Transaction(timestamp, ktype, amount, 0)
elif ktype == 'withdrawal':
return Transaction(timestamp, 'withdraw', amount, 0, fee_btc=fee)
else:
raise NotImplementedError(ktype + ': ' + ','.join(row))
def finish(self):
if self._trades:
unfinished = [(refid, info) for refid, info in self._trades
if len(info) < (2 + 'KFEE' in info)]
if unfinished:
pprint.pprint(dict(unfinished))
raise ValueError('Unfinished trades.')
return ()
class MtGoxParser(CsvParser):
expected_header = 'Index,Date,Type,Info,Value,Balance'
def __init__(self):
self.seen_file_count = [0, 0]
self.seen_transactions = [set(), set()]
def parse_file(self, filename):
basename = os.path.basename(filename).upper()
if 'BTC' in basename:
self.is_btc = True
elif 'USD' in basename:
self.is_btc = False
else:
raise ValueError("mtgox must contain BTC or USD")
self.seen_file_count[self.is_btc] += 1
for t in CsvParser.parse_file(self, filename):
yield t
def parse_row(self, row):
ix, timestamp, type, info, value, balance = row
ix = int(ix)
if ix in self.seen_transactions[self.is_btc]:
raise ValueError("Duplicate tranaction: %s" % ix)
else:
self.seen_transactions[self.is_btc].add(ix)
timestamp = time.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
value = decimal.Decimal(value)
m = re.search(r'tid:\d+', info)
if m:
id = "MtGox:%s" % m.group(0)
else:
id = "MtGox[%s]:%s" % (('UDSD', 'BTC')[self.is_btc], ix)
if type == 'out':
return Transaction(timestamp, 'trade', -value, 0, 0, 0, info=info, id=id)
elif type == 'in':
return Transaction(timestamp, 'trade', value, 0, 0, 0, info=info, id=id)
elif type == 'earned':
return Transaction(timestamp, 'trade', 0, value, 0, 0, info=info, id=id)
elif type == 'spent':
return Transaction(timestamp, 'trade', 0, -value, 0, 0, info=info, id=id)
elif type == 'fee':
if self.is_btc:
return Transaction(timestamp, 'fee', 0, 0, 0, fee_btc=value, info=info, id=id)
else:
return Transaction(timestamp, 'fee', 0, 0, 0, fee_usd=value, info=info, id=id)
elif type == 'withdraw' and self.is_btc:
return Transaction(timestamp, 'withdraw', -value, 0, 0, 0, info=info, id=id)
elif type == 'deposit' and self.is_btc:
return Transaction(timestamp, 'deposit', value, 0, 0, 0, info=info, id=id)
else:
raise ValueError(type)
def merge(self, transactions):
if len(transactions) == 1:
return transactions[0]
types = set(t.type for t in transactions)
if 'fee' in types:
types.remove('fee')
merged = Transaction(transactions[0].timestamp, list(types)[0], None, None, None, id=transactions[0].id)
merged.parser = transactions[0].parser
for t in transactions:
for attr in ('account', 'btc', 'usd', 'fee_usd', 'fee_btc', 'price'):
if getattr(t, attr):
setattr(merged, attr, getattr(t, attr))
try:
if not merged.price and transactions[0].type == 'trade':
merged.price = merged.usd / merged.btc
if not merged.fee_usd and merged.fee_btc:
if merged.price:
merged.fee_usd = roundd(merged.price * merged.fee_btc, 4)
else:
merged.btc += merged.fee_btc
except Exception:
print(len(transactions))
for t in transactions:
print(t, t.line)
print(merged.__dict__)
raise
return merged
def check_complete(self):
if self.seen_file_count[0] != self.seen_file_count[1]:
raise ValueError("Missmatched number of BTC and USD files (%s vs %s)." % tuple(seen_file_count))
if self.seen_file_count[0] == self.seen_file_count[1] == 0:
return
usd_or_btc = ['USD', 'BTC']
for is_btc in (True, False):
transactions = self.seen_transactions[is_btc]
if len(transactions) == 0:
pass
elif len(transactions) != max(transactions):
for gap_start in range(1, len(transactions)):
if gap_start not in transactions:
break
for gap_end in range(gap_start, max(transactions)):
if gap_end in transactions:
break
raise ValueError("Missing transactions in mtgox %s history (%s to %s)." % (usd_or_btc[is_btc], gap_start, gap_end-1))
class DbDumpParser(TransactionParser):
# python bitcointools/dbdump.py --wallet-tx
# NOTE: by default dbdump.py only prints 5 digits, fix to print the last satoshi
# TODO(robertwb): Figure out how to extract the individual accounts.
def can_parse(self, filename):
return filename.endswith('.walletdump')
def parse_file(self, filename):
def parse_pseudo_dict(line):
d = {}
for item in line.replace(': ', ':').split():
if ':' in item:
key, value = item.split(':', 1)
if key == 'value':
value = decimal.Decimal(value)
d[key] = value
return d
partial = False
for line in open(filename):
line = line.strip()
if line.startswith('==WalletTransaction=='):
assert not partial
tx_id = line.split('=')[-1].strip()
partial = True
in_tx = []
out_tx = []
from_me = None
elif line.startswith('TxIn:'):
d = parse_pseudo_dict(line[5:])
in_tx.append(d)
elif line.startswith('TxOut:'):
d = parse_pseudo_dict(line[6:])
out_tx.append(d)
elif line.startswith('mapValue:'):
map_value = parse_pseudo_dict(line[10:-1].replace("'", "").replace(',', ' '))
elif 'fromMe' in line:
# from_me = 'fromMe:True' in line
from_me = 'pubkey' not in in_tx[0]
partial = False
info = ' '.join(s for s in [map_value.get('to'), map_value.get('comment')] if s)
timestamp = time.localtime(int(map_value['timesmart']))
if from_me:
total_in = sum(tx['value'] for tx in in_tx)
total_out = sum(tx['value'] for tx in out_tx)
fee = total_in - total_out
for ix, tx in enumerate(out_tx):
if tx['Own'] == 'False':
yield Transaction(timestamp, 'withdraw', -tx['value'], 0, id="%s:%s" % (tx_id, ix), fee_btc=fee, info=info + ' ' + tx['pubkey'], account='wallet.dat')
fee = zero # only count the fee once
if fee:
yield Transaction(timestamp, 'fee', -fee, 0, id="%s:fee" % tx_id, info=info + ' fee', account='wallet.dat')
else:
for ix, tx in enumerate(out_tx):
if tx['Own'] == 'True':
yield Transaction(timestamp, 'deposit', tx['value'], 0, id="%s:%s" % (tx_id, ix), info=info + ' ' + tx['pubkey'], account='wallet.dat')
assert not partial
def merge_some(self, transactions):
return transactions
zero = decimal.Decimal('0', decimal.Context(8))
tenth = decimal.Decimal('0.1')
satoshi_to_btc = decimal.Decimal('1e8')
def roundd(x, digits):
return x.quantize(tenth**digits)
def decimal_or_none(o):
if isinstance(o, str) and o.startswith('--'):
# Double negative.
o = o[2:]
return None if o is None else decimal.Decimal(o)
def strip_or_none(o):
return o.strip() if o else o
class Transaction(object):
def __init__(self, timestamp, type, btc, usd, price=None, fee_usd=0, fee_btc=0, info=None, id=None, account=None, parser=None, txid=None):
self.timestamp = timestamp
self.type = type
self.btc = decimal_or_none(btc)
self.usd = decimal_or_none(usd)
self.price = decimal_or_none(price)
self.fee_usd = decimal_or_none(fee_usd)
self.fee_btc = decimal_or_none(fee_btc)
self.info = strip_or_none(info)
if self.btc and self.usd and self.price is None:
self.price = self.usd / self.btc
self.id = id
self.account = account
if parser:
self.parser = parser
self.txid = txid
def __eq__(left, right):
return left.timestamp == right.timestamp and left.btc == right.btc and left.id == right.id
def __lt__(left, right):
if left.timestamp == right.timestamp:
# Prioritize transferring in to avoid negative balance.
if left.type == 'transfer' and left.dest_account == right.account:
return left.btc < 0
elif right.type == 'transfer' and right.dest_account == left.account:
return right.btc > 0
else:
return (right.btc, str(left.id)) < (left.btc, str(right.id))
else:
return left.timestamp < right.timestamp
# return (left.timestamp, right.btc, str(left.id)) < (right.timestamp, left.btc, str(right.id))
def __str__(self):
if self.fee_btc:
fee_str = ", fee=%s BTC" % self.fee_btc
elif self.fee_usd:
fee_str = ", fee=%s USD" % self.fee_usd
else:
fee_str = ""
if self.type == 'transfer':
dest_str = ', dest=%s' % self.dest_account
else:
dest_str = ""
if self.txid:
txid_str = ', txid=%s...' % self.txid[:6]
else:
txid_str = ''
return "%s(%s, %s, %s, %s%s%s%s)" % (self.type, time.strftime('%Y-%m-%d %H:%M:%S', self.timestamp), self.usd, self.btc, self.account, fee_str, dest_str, txid_str)
__repr__ = __str__
@classmethod
def csv_cols(cls):
return ('time', 'type', 'usd', 'btc', 'price', 'fee_usd', 'fee_btc', 'account', 'id', 'info')
@classmethod
def csv_header(cls, sep=','):
return sep.join(cls.csv_cols())
def csv(self, sep=','):
cols = []
for col_name in self.csv_cols():
if col_name == 'time':
value = time.strftime('%Y-%m-%d %H:%M:%S', self.timestamp)
else:
value = str(getattr(self, col_name))
cols.append(value)
return sep.join(cols).replace('\n', ' ')
class Lot:
def __init__(self, timestamp, btc, usd, transaction, dissallowed_loss=0):
self.timestamp = timestamp
self.btc = btc
self.usd = usd
self.price = usd / btc
self.transaction = transaction
self.dissallowed_loss = dissallowed_loss
def split(self, btc):
"""
Splits this lot into two, with the first consisting of at most btc bitcoins.
"""
if btc <= 0:
return None, self
elif btc < self.btc:
usd = roundd(self.price * btc, 2)
dissallowed_loss = roundd(self.dissallowed_loss * btc / self.btc, 2)
return (Lot(self.timestamp, btc, usd, self.transaction, dissallowed_loss),
Lot(self.timestamp, self.btc - btc, self.usd - usd, self.transaction, self.dissallowed_loss - dissallowed_loss))
else:
return self, None
def __eq__(left, right):
return left.timestamp == right.timestamp and left.transaction == right.transaction
def __lt__(left, right):
if parsed_args.method in ('fifo', 'oldest'):
return (left.timestamp, left.transaction) < (right.timestamp, right.transaction)
elif parsed_args.method in ('lifo', 'newest'):
return (right.timestamp, left.transaction) < (left.timestamp, right.transaction)
def __str__(self):
dissallowed_loss = ", dissallowed_loss=%s" % self.dissallowed_loss if self.dissallowed_loss else ""
return "Lot(%s, %s, %s%s)" % (time.strftime('%Y-%m-%d', self.timestamp), self.btc, self.price, dissallowed_loss)
__repr__ = __str__
# Why is this not a class?
class Heap:
def __init__(self, data=[]):
self.data = list(data)
def push(self, item):
heapq.heappush(self.data, item)
def pop(self):
return heapq.heappop(self.data)
def __len__(self):
return len(self.data)
class LotSelector(object, metaclass=abc.ABCMeta):
def __init__(self, data=[]):
self._data = list(data)
@abc.abstractmethod
def push(self, lot):
pass
@abc.abstractmethod
def pop(self):
pass