-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbitprices.php
executable file
·1464 lines (1178 loc) · 55.7 KB
/
bitprices.php
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 php
<?php
require_once dirname(__FILE__) . '/lib/strict_mode.funcs.php';
require_once dirname(__FILE__) . '/lib/mylogger.class.php';
require_once dirname(__FILE__) . '/lib/mysqlutil.class.php';
require_once dirname(__FILE__) . '/lib/httputil.class.php';
require_once dirname(__FILE__) . '/lib/html_table.class.php';
require_once dirname(__FILE__) . '/lib/bitcoin-php/bitcoin.inc';
require_once dirname(__FILE__) . '/lib/validator/AddressValidator.php';
use \LinusU\Bitcoin\AddressValidator;
require_once dirname(__FILE__) . '/lib/blockchain_api.php';
require_once dirname(__FILE__) . '/lib/price_api.php';
define( 'SATOSHI', 100000000 );
// no global scope execution past this point!
exit( main( $argv ) );
/**
* Our main function. It only performs top-level exception handling.
*/
function main( $argv ) {
ini_set('memory_limit', -1 );
$worker = new bitprices();
try {
return $worker->run( $argv );
}
catch( Exception $e ) {
mylogger()->log_exception( $e );
// print validation errors to stderr.
if( $e->getCode() == 2 ) {
fprintf( STDERR, $e->getMessage() . "\n\n" );
}
return $e->getCode() ?: 1;
}
}
/**
* Main App
*/
class bitprices {
// where all the work starts and ends.
public function run( $argv ) {
$params = $this->get_cli_params();
$rc = $this->process_cli_params( $params );
if( $rc != 0 ) {
return $rc;
}
$params = $this->get_params();
$format = $params['format'];
$report_type = $params['report-type'];
date_default_timezone_set("UTC");
$start = microtime( true );
$tx_list = $this->gettxfromuser();
if( !$tx_list ) {
$addrs = $this->get_addresses();
$tx_list = $this->get_matching_transactions( $addrs );
}
$results = $this->process_transactions( $tx_list );
$meta = null;
switch( $report_type ) {
case 'schedule_d': $rows = $this->gen_report_schedule_d( $results, $format ); break;
case 'matrix': $rows = $this->gen_report_matrix( $results, $format ); break;
default: list($rows, $meta) = $this->gen_report_tx( $results, $format ); break;
}
$this->print_results( $rows, $meta, $format );
$end = microtime(true);
$duration = $end - $start;
echo "\nExecution time: $duration seconds\n\n";
}
/**
* returns the CLI params, exactly as entered by user.
*/
protected function get_cli_params() {
$params = getopt( 'g', array( 'date-start:', 'date-end:',
'addresses:', 'addressfile:', 'txfile:',
'direction:', 'currency:',
'cols:', 'outfile:',
'format:', 'logfile:',
'toshi:', 'toshi-fast',
'addr-tx-limit:', 'testnet',
'btcd-rpc-host:', 'btcd-rpc-port:',
'btcd-rpc-user:', 'btcd-rpc-pass:',
'priceapi:',
'api:', 'insight:',
'list-templates', 'list-cols',
'report-type:', 'cost-method:',
'oracle-raw:', 'oracle-json:',
'version',
) );
return $params;
}
/**
* processes and normalizes the CLI params. adds defaults
* and ensure each value is set.
*/
protected function process_cli_params( $params ) {
if( @$params['logfile'] ) {
mylogger()->set_log_file( $params['logfile'] );
mylogger()->echo_log = false;
}
if( !@$params['api'] ) {
$params['api'] = 'insight';
}
if( !@$params['report-type'] ) {
$params['report-type'] = 'tx';
}
if( !@$params['cost-method'] ) {
$params['cost-method'] = 'fifo';
}
if( !@$params['insight'] ) {
$params['insight'] = 'https://insight.bitpay.com/api';
}
$params['toshi-fast'] = isset($params['toshi-fast']);
$params['testnet'] = isset($params['testnet']);
if( !@$params['toshi'] ) {
$params['toshi'] = 'https://bitcoin.toshi.io';
}
if( !@$params['btcd-rpc-host'] ) {
$params['btcd-rpc-host'] = '127.0.0.1'; // use localhost
}
if( !@$params['btcd-rpc-port'] ) {
$params['btcd-rpc-port'] = 8334; // use default port.
}
if( $params['api'] == 'btcd' && (!@$params['btcd-rpc-user'] || !@$params['btcd-rpc-pass']) ) {
echo( "btcd-rpc-user and btcd-rpc-pass must be set when using api=btcd\n" );
return 1;
}
if( !@$params['addr-tx-limit'] ) {
$params['addr-tx-limit'] = 1000;
}
$params['direction'] = @$params['direction'] ?: 'both';
if( !in_array( @$params['direction'], array( 'in', 'out', 'both' ) ) ) {
$params['direction'] = 'both';
}
$params['date-start'] = @$params['date-start'] ? strtotime($params['date-start']) : 0;
$params['date-end'] = @$params['date-end'] ? strtotime($params['date-end']) : time();
$params['currency'] = strtoupper( @$params['currency'] ) ?: 'USD';
$params['priceapi'] = @$params['priceapi'] ?: 'btcaverage';
if($params['priceapi'] == 'bitcoin_com' && $params['currency'] != 'USD') {
throw new Exception("Only USD is supported for bitcoin.com price API");
}
$params['format'] = @$params['format'] ?: 'txt';
$params['oracle-raw'] = @$params['oracle-raw'] ?: null;
$params['oracle-json'] = @$params['oracle-json'] ?: null;
// note: get_cols internally calls get_params and uses params[currency]
$this->params = $params;
$params['cols'] = $this->get_cols( @$params['cols'] ?: 'standard' );
$this->params = $params;
if( isset( $params['version'] ) ) {
$this->print_version();
return 2;
}
if( isset( $params['list-templates'] ) ) {
$this->print_list_templates();
return 2;
}
if( isset( $params['list-cols'] ) ) {
$this->print_list_cols();
return 2;
}
// these three are mutually exclusive.
$cnt = 0;
$cnt += @$params['addresses'] ? 1 : 0;
$cnt += @$params['addressfile'] ? 1 : 0;
$cnt += @$params['txfile'] ? 1 : 0;
if( $cnt != 1 ) {
$this->print_help();
return 1;
}
if( !isset($params['g']) ) {
$this->print_help();
return 1;
}
return 0;
}
/**
* returns the normalized CLI params, after initial processing/sanitization.
*/
protected function get_params() {
return $this->params;
}
/**
* obtains the BTC addresses from user input, either via the
* --addresses arg or the --addressfile arg.
*/
protected function get_addresses() {
// optimize retrieval.
static $addresses = null;
if( $addresses ) {
return $addresses;
}
$params = $this->get_params();
$list = array();
if( @$params['addresses'] ) {
$list = explode( ',', $this->strip_whitespace( $params['addresses'] ) );
}
if( @$params['addressfile'] ) {
$csv = implode( ',', file( @$params['addressfile'] ) );
$list = explode( ',', $this->strip_whitespace( $csv ) );
}
foreach( $list as $idx => $addr ) {
if( !$addr ) {
unset( $list[$idx] );
continue;
}
$version = $params['testnet'] ? AddressValidator::TESTNET : AddressValidator::MAINNET;
if( !AddressValidator::isValid( $addr, $version ) ) {
// code 2 means an input validation exception.
throw new Exception( "Bitcoin address $addr is invalid", 2 );
}
}
if( !count( $list ) ) {
throw new Exception( "No valid addresses to process.", 2 );
}
$addresses = $list;
return $list;
}
/**
* obtains transactions in libratax CSV format when --txfile flag
* is present.
*/
protected function gettxfromuser() {
$params = $this->get_params();
$txfile = @$params['txfile'];
if( !$txfile ) {
return null;
}
$start_time = $params['date-start'];
$end_time = $params['date-end'] + 86400 -1;
$cb = function( $row, $count ) use(&$start_time, &$end_time) {
$txtime = strtotime($row['date']);
$in_period = $txtime >= $start_time && $txtime <= $end_time;
if( !$in_period ) {
return null;
}
// note: libratax does not include an address for all transactions.
return array( 'block_time' => $txtime,
'addr' => $row['dest'],
'amount' => $row['amt'],
'amount_in' => $row['amt'] > 0 ? $row['amt'] : 0,
'amount_out' => $row['amt'] < 0 ? abs($row['amt']) : 0,
'txid' => $count,
'exchange_rate' => $row['spotval'],
'type' => $row['taxtype'],
);
};
return $this->getlibrataxcsv($txfile, $cb);
}
/**
* parses a libratax transaction CSV file.
*/
protected function getlibrataxcsv( $txfile, $row_cb = null ) {
$lines = file( $txfile );
array_shift($lines); // remove header row
$rows = [];
foreach( $lines as $l ) {
list( $date, $dest, $note, $amt, $asset, $spotval, $totalval, $taxtype, $category ) = str_getcsv( $l );
$row = [
'date' => $date,
'dest' => $dest,
'note' => $note,
'amt' => btcutil::btc_to_int($amt),
'asset' => $asset,
'spotval' => ((int)($spotval*1000))/10,
'totalval' => $totalval,
'taxtype' => $taxtype,
'category' => $category
];
$row = $row_cb ? $row_cb( $row, count($rows) + 1 ) : $row;
if( $row ) {
$rows[] = $row;
}
}
return $rows;
}
/**
* returns a key/val array of available column template definitions.
* column templates are simply named lists of columns that should appear
* in the tx report.
*/
protected function get_col_templates() {
$all_cols = implode( ',', array_keys( $this->all_columns() ) );
$map = array(
'standard' => array( 'desc' => "Standard report", 'cols' => 'date,addrshort,btcamount,price,fiatamount,fiatamountnow,fiatgain,type' ),
'balance' => array( 'desc' => "Balance report", 'cols' => 'date,addrshort,btcin,btcout,realizedgain,btcbalance', 'notes' => 'Equivalent to LibraTax: Balance report.' ),
'realizedgain' => array( 'desc' => "Realized Gain", 'cols' => 'date,btcamount,fiatamount,realizedgainshort,realizedgainlong' ),
'realizedgainmethods' => array( 'desc' => "Realized Gain Method Comparison", 'cols' => 'date,btcamount,fiatamount,realizedgainfifo,realizedgainlifo' ),
'thenandnow' => array( 'desc' => "Then and Now", 'cols' => 'date,price,fiatamount,pricenow,fiatamountnow,fiatgain' ),
'inout' => array( 'desc' => "Standard report with Inputs and Outputs", 'cols' => 'date,addrshort,btcin,btcout,price,fiatin,fiatout' ),
'blockchain' => array( 'desc' => "Only columns from blockchain", 'cols' => 'date,time,tx,address,btcin,btcout' ),
'all' => array( 'desc' => "All available columns", 'cols' => $all_cols ),
);
foreach( $map as $k => $info ) {
$map[$k]['cols'] = explode( ',', $info['cols'] );
}
return $map;
}
/**
* parses the --cols argument and returns an array of columns.
* note that the --cols argument accepts either:
* a csv list of columns -- or --
* a template name + csv list of columns.
*
* For the latter case, the template name is expanded to a column list.
*/
protected function get_cols( $arg ) {
$arg = $this->strip_whitespace( $arg );
$templates = $this->get_col_templates();
$allcols = $this->all_columns();
$parts = explode( ',', $arg, 2 );
$report = $parts[0];
$extra = @$parts[1];
if( @$templates[$report] ) {
$arg = implode(',', $templates[$report]['cols']);
if( $extra ) {
$arg .= ',' . $extra;
}
}
$cols = explode( ',', $arg );
foreach( $cols as $c ) {
if( !isset($allcols[$c]) ) {
throw new Exception( "'$c' is not a known column or column template.", 2 );
}
}
return $cols;
}
/**
* removes whitespace from a string
*/
protected function strip_whitespace( $str ) {
return preg_replace('/\s+/', '', $str);
}
/**
* a function to append strings and add newlines+indent as necessary.
* TODO: save elsewhere. no longer used.
*/
public function str_append_indent( $str, $append, $prefix, $maxlinechr = 80 ) {
$lines = explode( "\n", $str );
$lastline = $lines[count($lines)-1];
$exceeds = strlen($lastline) + strlen($append) > $maxlinechr;
$str .= $exceeds ? ("\n" . $prefix . $append) : $append;
return $str;
}
/**
* prints help text for --list-templates
* note: output is pretty JSON for both human and machine readability.
*/
public function print_list_templates() {
$tpl = $this->get_col_templates();
echo json_encode( $tpl, JSON_PRETTY_PRINT ) . "\n\n";
}
/**
* prints help text for --list-cols
* note: output is pretty JSON for both human and machine readability.
*/
public function print_list_cols() {
$map = $this->all_columns();
$colmap = [];
foreach( $map as $k => $v ) {
$colmap[$k] = $v['title'];
}
echo json_encode( $colmap, JSON_PRETTY_PRINT ) . "\n\n";
}
/**
* prints program version text
*/
public function print_version() {
$version = @file_get_contents( __DIR__ . '/VERSION');
echo $version ?: 'version unknown' . "\n";
}
/**
* prints CLI help text
*/
public function print_help() {
$buf = <<< END
bitprices.php
This script generates a report of transactions with the USD value
at the time of each transaction.
Options:
-g go!
--addresses=<csv> comma separated list of bitcoin addresses
--addressfile=<path> file containing bitcoin addresses, one per line.
--txfile=<path> file containing transactions in libratax csv format.
note: addresses, addressfile and txfile are exclusive.
--api=<api> toshi|btcd|insight. default = toshi.
--direction=<dir> transactions in | out | both default = both.
--date-start=<date> Look for transactions since date. default = all.
--date-end=<date> Look for transactions until date. default = now.
--currency=<curr> symbol supported by bitcoinaverage.com. default = USD.
--priceapi=<api> btcaverage|bitcoin_com. default=btcaverage
--report-type=<type> tx | schedule_d | matrix. default=tx
options --direction, --cols, --list-templates,
--list-cols apply to tx report only.
option --cost-method applies to schedule_d and
matrix reports only.
--cost-method=<m> fifo|lifo default = fifo.
--cols=<cols> a report template or list of columns. default=standard.
See --list-cols
--list-templates if present, a list of templates will be printed.
--list-cols if present, a list of columns will be printed.
--outfile=<path> specify output file path.
--format=<format> txt|csv|json|jsonpretty|html|all default=txt
if all is specified then a file will be created
for each format with appropriate extension.
only works when outfile is specified.
--toshi=<url> toshi server. defaults to https://bitcoin.toshi.io
--toshi-fast if set, toshi server supports filtered transactions.
--btcd-rpc-host=<h> btcd rpc host. default = 127.0.0.1
--btcd-rpc-port=<p> btcd rpc port. default = 8334
--btcd-rpc-user=<u> btcd rpc username.
--btcd-rpc-pass=<p> btcd rpc password.
--insight=<url> insight server. defaults to https://insight.bitpay.com/api
use http://localhost:3001/insight-api for local node
--addr-tx-limit=<n> per address transaction limit. default = 1000
--testnet use testnet. only affects addr validation.
--oracle-raw=<p> path to save raw server response, optional.
--oracle-json=<p> path to save formatted server response, optional.
END;
fprintf( STDERR, $buf );
}
/**
* processes transactions and price data for one or more bitcoin addresses.
*/
protected function process_transactions( $trans ) {
$params = $this->get_params();
$currency = $params['currency'];
// make vin and vout maps keyed by txid for fast lookups.
// this will give us the sum of wallet-address inputs and
// sum of wallet-address outputs, per transaction.
$vinlist = [];
$voutlist = [];
foreach( $trans as $tx ) {
if( $tx['amount_out'] ) {
$key = $tx['txid'];
$sum = @$vinlist[$key] ?: 0;
$vinlist[$key] = $sum + $tx['amount_out'];
}
else if( $tx['amount_in'] ) {
$key = $tx['txid'];
$sum = @$voutlist[$key] ?: 0;
$voutlist[$key] = $sum + $tx['amount_in'];
}
}
$results = array();
foreach( $trans as $tx ) {
if( !@$tx['type'] ) { // libratax data already has type set.
// determine transfer type.
$type = '';
if( $tx['amount_in'] ) {
$key = $tx['txid'];
$total_output = @$vinlist[$key];
$type = 'purchase';
}
else if( $tx['amount_out'] ) {
$key = $tx['txid'];
$total_input = @$voutlist[$key];
$type = 'sale';
}
$tx['type'] = $type;
}
$this->add_fields( $tx, $currency );
$results[] = $tx;
}
// important: for LIFO, the movements must be sorted by timestamp
// and purchase type. (buy then sell). If a SELL were to
// precede a BUY for the same timestamp, then the BUY would
// be processed by LIFO as if it occurred AFTER the sell.
usort( $results, function($a, $b) {
// order by block_time asc
if( $a['block_time'] < $b['block_time'] ) {
return -1;
}
else if( $a['block_time'] > $b['block_time'] ) {
return 1;
}
// order by buy, then sell, then transfer.
if( $a['type'] != $b['type'] ) {
$rc = strcmp( $a['type'], $b['type'] );
if( $rc != 0 ) {
return $rc;
}
}
return strcmp( $a['txid'], $b['txid'] );
});
return $results;
}
protected function add_fields( &$tx, $currency ) {
$er = @$tx['exchange_rate'] ?: $this->get_historic_price( $currency, $tx['block_time'] );
$tx['exchange_rate'] = $er;
$tx['exchange_rate_now'] = $ern = $this->get_24_hour_avg_price_cached( $currency );
$tx['fiat_amount_in'] = $er ? btcutil::btcint_to_fiatint( $tx['amount_in'] * $tx['exchange_rate'] ) : null;
$tx['fiat_amount_out'] = $er ? btcutil::btcint_to_fiatint( $tx['amount_out'] * $tx['exchange_rate'] ) : null;
$tx['fiat_amount_in_now'] = $ern ? btcutil::btcint_to_fiatint( $tx['amount_in'] * $tx['exchange_rate_now'] ) : null;
$tx['fiat_amount_out_now'] = $ern ? btcutil::btcint_to_fiatint( $tx['amount_out'] * $tx['exchange_rate_now'] ) : null;
$tx['fiat_currency'] = $currency;
}
/**
* queries a blockchain api provider to obtain historical transactions for
* list of input addresses.
*/
protected function get_matching_transactions( $addrs ) {
$params = $this->get_params();
$api = blockchain_api_factory::instance( $params['api'] );
$tx_list = $api->get_addresses_transactions( $addrs,
$params['date-start'],
$params['date-end'] +3600*24-1,
$params );
return $tx_list;
}
/**
* returns price for currency on UTC date of $timestamp
*/
protected function get_historic_price( $currency, $timestamp ) {
$date = gmdate( 'Y-m-d', $timestamp );
$params = $this->get_params();
$priceapi = $params['priceapi'];
$map = self::get_historic_prices_cached( $priceapi, $currency );
$price = @$map[$date];
return $price;
}
/**
* retrieves the 24 hour avg price from cache if present and not stale.
* stale is defined as 1 hour.
*/
protected function get_24_hour_avg_price_cached( $currency ) {
static $prices = array();
$params = $this->get_params();
$priceapi = $params['priceapi'];
$price = @$prices[$currency];
if( $price ) {
return $price;
}
$fname = dirname(__FILE__) . sprintf( '/price_24/24_hour_avg_price.%s.%s.csv', $priceapi, $currency );
$max_age = 60 * 60; // max 1 hour.
$cache_file_valid = file_exists( $fname ) && time() - filemtime( $fname ) < $max_age;
// use cached price file if file age is less than max_age
if( $cache_file_valid ) {
$price = unserialize( file_get_contents( $fname ) );
$prices[$currency] = $price;
return $price;
}
$dir = dirname( $fname );
file_exists($dir) || mkdir( $dir );
$price = price_api_factory::instance($priceapi)->get_24_hour_avg_price( $currency );
@unlink( $fname );
file_put_contents( $fname, serialize($price) );
$prices[$currency] = $price;
return $price;
}
/**
* retrieves all historic prices for $currency, from cache if present and
* not stale. stale is defined as older than 12 hours.
*/
protected static function get_historic_prices_cached( $priceapi, $currency) {
static $maps = array();
static $downloaded_map = array();
$map = @$maps[$currency];
if( $map ) {
return $map;
}
// if we already downloaded this run, then abort.
$downloaded = @$downloaded_map[$currency];
if( $downloaded ) {
return null;
}
$market = 'BTC' . strtoupper($currency);
$fname = dirname(__FILE__) . sprintf( '/price_history/per_day_all_time_history.%s.%s.csv', $priceapi, $market );
$exists = file_exists( $fname );
if( $exists ) {
$file_age = time() - filemtime( $fname );
}
if( !$exists || $file_age > 60*60*12 ) {
$dir = dirname( $fname );
file_exists($dir) || mkdir( $dir );
$buf = price_api_factory::instance($priceapi)->retrieve_price_history( $currency );
file_put_contents( $fname, $buf );
$downloaded_map[$currency] = true;
}
$fh = fopen( $fname, 'r' );
$map = array();
while( $row = fgetcsv( $fh ) ) {
list( $date, $high, $low, $avg, $volume ) = $row;
if(!is_numeric($avg)) {
continue;
}
$date = date('Y-m-d', strtotime( $date ) );
$map[$date] = (int)($avg * 100);
}
$maps[$currency] = $map;
return $map;
}
/**
* shortens a bitcoin address to abc...xyz form.
*/
protected function shorten_addr( $address ) {
return strlen( $address ) > 8 ? substr( $address, 0, 3 ) . '..' . substr( $address, -3 ) : $address;
}
/**
* generates the tx (transaction) report.
*/
protected function gen_report_tx( $results, $format ) {
$params = $this->get_params();
$direction = $params['direction'];
$btc_balance = 0;
$fiat_balance = 0;
$fiat_balance_now = 0;
$fiat_gain_balance = 0;
$total_btc_in = 0 ; $total_fiat_in = 0; $num_tx_in = 0; // for average cost.
$total_btc_out = 0; $total_fiat_out = 0; $num_tx_out = 0;
$total_btc_in_alltime = 0 ; $total_fiat_in_alltime = 0; $num_tx_in_alltime = 0; // for average cost.
$total_btc_out_alltime = 0; $total_fiat_out_alltime = 0; $num_tx_out_alltime = 0;
$short_term_gain = $long_term_gain = 0;
$exchange_rate = 0;
$fifo_stack = array();
$lifo_stack = array();
$total_fiat_in = $total_btc_in = 0;
$fifo_lot_id = 0;
$lifo_lot_id = 0;
$col_totals = array();
$map = $this->all_columns();
$nr = [];
$metalist = [];
foreach( $results as $r ) {
$realized_gain_fifo_short = $realized_gain_fifo_long = 0;
$realized_gain_lifo_short = $realized_gain_lifo_long = 0;
$btc_amount = $r['amount_in'] - $r['amount_out'];
$fiat_amount = $r['fiat_amount_in'] - $r['fiat_amount_out'];
$fiat_amount_now = $r['fiat_amount_in_now'] - $r['fiat_amount_out_now'];
$fifo_qty = $lifo_qty = $btc_amount;
$fiat_gain = $fiat_amount_now - $fiat_amount;
$btc_balance += $btc_amount;
$fiat_balance += $fiat_amount;
$fiat_balance_now += $fiat_amount_now;
$fiat_gain_balance += $fiat_gain;
if( $r['type'] == 'purchase' ) {
// add to end of fifo stack
$fifo_stack[] = array( 'qty' => $r['amount_in'], 'exchange_rate' => $r['exchange_rate'], 'block_time' => $r['block_time'], 'lot_id' => ++$fifo_lot_id );
$lifo_stack[] = array( 'qty' => $r['amount_in'], 'exchange_rate' => $r['exchange_rate'], 'block_time' => $r['block_time'], 'lot_id' => ++$lifo_lot_id );
}
// calc realized gains if it is an output.
// TODO: avoid if a transfer between our wallet addresses.
if( $r['type'] == 'sale' ) {
// calc fifo totals to date
$this->calc_fifo_stack( $r, $fifo_stack, $is_fifo = true,
function( $data )
use (&$realized_gain_fifo_short, &$realized_gain_fifo_long ) {
$realized_gain_fifo_short += $data['longterm'] ? 0 : $data['realized_gain'];
$realized_gain_fifo_long += $data['longterm'] ? $data['realized_gain'] : 0;
} );
// calc lifo totals to date
$this->calc_fifo_stack( $r, $lifo_stack, $is_fifo = false,
function( $data )
use (&$realized_gain_lifo_short, &$realized_gain_lifo_long ) {
$realized_gain_lifo_short += $data['longterm'] ? 0 : $data['realized_gain'];
$realized_gain_lifo_long += $data['longterm'] ? $data['realized_gain'] : 0;
} );
}
$realized_gain_fifo = $realized_gain_fifo_long + $realized_gain_fifo_short;
$realized_gain_lifo = $realized_gain_lifo_long + $realized_gain_lifo_short;
// calc alltime totals.
if( $r['amount_in'] ) {
$total_fiat_in_alltime += $r['fiat_amount_in'];
$total_btc_in_alltime += $r['amount_in'];
$num_tx_in_alltime ++;
}
if( $r['amount_out'] ) {
$total_fiat_out_alltime += $r['fiat_amount_out'];
$total_btc_out_alltime += $r['amount_out'];
$num_tx_out_alltime ++;
}
// filter out transactions by direction and date params.
if( $direction == 'in' && !$r['amount_in'] ) {
continue;
}
else if( $direction == 'out' && !$r['amount_out'] ) {
continue;
}
else if( $r['block_time'] < $params['date-start'] ) {
continue;
}
else if( $r['block_time'] > $params['date-end'] +3600*24-1 ) {
continue;
}
$exchange_rate = $r['exchange_rate'];
if( $r['amount_in'] ) {
$total_fiat_in += $r['fiat_amount_in'];
$total_btc_in += $r['amount_in'];
$num_tx_in ++;
}
$btc_out_amount = $r['amount_out'] - $r['amount_in'];
$fiat_out_amount = $r['fiat_amount_out'] - $r['fiat_amount_in'];
if( $r['amount_out'] ) {
$total_btc_out += $r['amount_out'];
$total_fiat_out += $r['fiat_amount_out'];
$num_tx_out ++;
}
$fc = strtoupper( $r['fiat_currency'] );
$row = [];
$meta = [];
$meta['addr'] = $r['addr'];
$meta['tx'] = $r['txid'];
$methods = array('fifo', 'lifo');
if( !in_array( $params['cost-method'], $methods ) ) {
throw new Exception( "Invalid cost method: " . $params['cost-method'] );
}
$cm = $params['cost-method'];
$realized_gain = eval("return \$realized_gain_{$cm};");
$realized_gain_long = eval("return \$realized_gain_{$cm}_long;" );
$realized_gain_short = eval("return \$realized_gain_{$cm}_short;" );
foreach( $params['cols'] as $col ) {
$cn = $map[$col]['title']; // column name
switch( $col ) {
case 'date': $row[$cn] = date('Y-m-d', $r['block_time'] ); break;
case 'time': $row[$cn] = date('H:i:s', $r['block_time'] ); break;
case 'addrshort': $row[$cn] = $this->shorten_addr( $r['addr'] ); break;
case 'address': $row[$cn] = $r['addr']; break;
case 'btcin': $row[$cn] = btcutil::btc_display( $r['amount_in'], true ); break;
case 'btcout': $row[$cn] = btcutil::btc_display( $r['amount_out'], true ); break;
case 'btcbalance': $row[$cn] = btcutil::btc_display( $btc_balance ); break;
case 'fiatin': $row[$cn] = btcutil::fiat_display( $r['fiat_amount_in'], true ); break;
case 'fiatout': $row[$cn] = btcutil::fiat_display( $r['fiat_amount_out'], true ); break;
case 'fiatbalance': $row[$cn] = btcutil::fiat_display( $fiat_balance ); break;
case 'fiatinnow': $row[$cn] = btcutil::fiat_display( $r['fiat_amount_in_now'], true ); break;
case 'fiatoutnow': $row[$cn] = btcutil::fiat_display( $r['fiat_amount_out_now'], true ); break;
case 'fiatbalancenow': $row[$cn] = btcutil::fiat_display( $fiat_balance_now ); break;
case 'price': $row[$cn] = btcutil::fiat_display( $r['exchange_rate'] ); break;
case 'pricenow': $row[$cn] = btcutil::fiat_display( $r['exchange_rate_now'] ); break;
case 'btcamount': $row[$cn] = btcutil::btc_display( $btc_amount ); break;
case 'fiatamount': $row[$cn] = btcutil::fiat_display( $fiat_amount ); break;
case 'fiatamountnow': $row[$cn] = btcutil::fiat_display( $fiat_amount_now ); break;
case 'fiatgain': $row[$cn] = btcutil::fiat_display( $fiat_gain ); break;
case 'fiatgainbalance': $row[$cn] = btcutil::fiat_display( $fiat_gain_balance ); break;
case 'realizedgain': $row[$cn] = btcutil::fiat_display( $realized_gain, true ); break;
case 'realizedgainlong': $row[$cn] = btcutil::fiat_display( $realized_gain_long, true ); break;
case 'realizedgainshort': $row[$cn] = btcutil::fiat_display( $realized_gain_short, true ); break;
case 'realizedgainfifo': $row[$cn] = btcutil::fiat_display( $realized_gain_fifo, true ); break;
case 'realizedgainfifolong': $row[$cn] = btcutil::fiat_display( $realized_gain_fifo_long, true ); break;
case 'realizedgainfifoshort': $row[$cn] = btcutil::fiat_display( $realized_gain_fifo_short, true ); break;
case 'realizedgainlifo': $row[$cn] = btcutil::fiat_display( $realized_gain_lifo, true ); break;
case 'realizedgainlifolong': $row[$cn] = btcutil::fiat_display( $realized_gain_lifo_long, true ); break;
case 'realizedgainlifoshort': $row[$cn] = btcutil::fiat_display( $realized_gain_lifo_short, true ); break;
case 'type': $row[$cn] = $r['type']; break;
case 'txshort': $row[$cn] = $this->shorten_addr( $r['txid'] ); break;
case 'tx': $row[$cn] = $r['txid']; break;
}
if( $map[$col]['total'] ) {
$total = @$col_totals[$col] ?: 0;
$col_totals[$col] = $total + $row[$cn];
}
}
$nr[] = $row;
$metalist[] = $meta;
}
// Add Totals Row
$found_empty = false;
$row = [];
foreach( $params['cols'] as $col ) {
$cn = $map[$col]['title']; // column name
if( !$found_empty && !$map[$col]['total'] ) {
$row[$cn] = 'Totals:';
$found_empty = true;
}
else if( isset( $col_totals[$col] ) ) {
$row[$cn] = strstr( $col, 'btc' ) ? btcutil::btc_display( btcutil::btc_to_int( $col_totals[$col] ) ) :
btcutil::fiat_display( btcutil::fiat_to_int( $col_totals[$col] ) );
}
else {
$row[$cn] = null;
}
}
$nr[] = $row;
return array( $nr, $metalist );
}
/**
* calculate realized gains using fifo or lifo method.
*/
protected function calc_fifo_stack( $r, &$fifo_stack, $is_fifo, $callback ) {
$params = $this->get_params();
$out = $r['amount_out'];
while( $out > 0 && count($fifo_stack) ) {
$first =& $fifo_stack[0];
if( !$is_fifo ) {
$first =& $fifo_stack[count($fifo_stack)-1];
}
$age = $r['block_time'] - $first['block_time'];
$longterm = $age > 31536000; // 1 year. 86400 * 365;
$orig_qty = $first['qty'];
$orig_exchange_rate = $first['exchange_rate'];
$lot_id = $first['lot_id'];
if( $out < $first['qty'] ) {
$qty = $out;
$proceeds = $qty * $r['exchange_rate'];
$cost_basis = $qty * $first['exchange_rate'];
$realized_gain = $proceeds - $cost_basis;
$first['qty'] -= $out;
$out = 0;
}
else {
$qty = $first['qty'];
$proceeds = $qty * $r['exchange_rate'];
$cost_basis = $qty * $first['exchange_rate'];
$realized_gain = $proceeds - $cost_basis;
$out -= $first['qty'];