-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathticker-old.cgi
executable file
·1689 lines (1454 loc) · 51.4 KB
/
ticker-old.cgi
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/perl -T
use strict;
use warnings;
use DBI;
use CGI qw(:standard start_ul *table);
use CGI::Carp qw(fatalsToBrowser);
use JSON;
use Term::ANSIColor qw(:constants);
use List::Util qw(min max first);
use Number::Format;
use DateTime;
use Time::Local;
use Time::Seconds;
use Data::Dumper;
my $driver = 'SQLite';
my $database = '/home/www/gerikson.com/cgi-bin/data/historical-prices.db';
my $dsn = "DBI:$driver:dbname=$database";
my ( $user, $pass ) = ( '', '' );
my $dbh = DBI->connect( $dsn, $user, $pass, { RaiseError => 1 } )
or die $DBI::errstr;
### keep the SQLs separate ########################################
my %Sql;
$Sql{'latest_price'} =
qq/select strftime('%s', timestamp), last, high, low, volume,
open_hour, change_pct_hour, change_price_hour,
open_day, change_pct_day, change_price_day,
open_week, change_pct_week, change_price_week
from ticker order by timestamp desc limit 10/;
$Sql{'last_hour_ticker'} =
qq/select last from ticker where timestamp >= datetime('now','-1 hour')/;
$Sql{'days_ago'} = qq/select
timestamp, high, low, average, volume
from history
where strftime('%Y-%m-%d',timestamp) = strftime('%Y-%m-%d', 'now', ?)
and volume is not null/;
$Sql{'ath'} = qq/select
cast(julianday('now') - julianday(timestamp) as int),
timestamp, high, low, average, volume
from history
where (high is not null and high <> '')
order by high desc limit 1/;
$Sql{'ytd'} = qq/select
cast(julianday('now') - julianday(timestamp) as int),
timestamp, high, low, average, volume
from history
where strftime('%Y-%m-%d', timestamp) = strftime('%Y-01-01', 'now')/;
$Sql{'yhi'} = qq/select
cast(julianday('now') - julianday(timestamp) as int),
timestamp, high, low, average, volume
from history
where (high is not null and high <> '')
and timestamp>= strftime('%Y-01-01 00:00:00','now')
order by high desc limit 1/;
$Sql{'ylo'} = qq/select
cast(julianday('now') - julianday(timestamp) as int),
timestamp, high, low, average, volume
from history
where (low is not null and low <> '')
and timestamp>= strftime('%Y-01-01 00:00:00','now')
order by low asc limit 1/;
$Sql{'zhi'} = qq/select
cast(julianday('now') - julianday(timestamp) as int),
timestamp, high, low, average, volume
from history
where (high is not null and high <> '')
and strftime('%Y-%m-%d',timestamp) >= strftime('%Y-%m-%d','now', '-365 days')
order by high desc limit 1/;
$Sql{'zlo'} = qq/select
cast(julianday('now') - julianday(timestamp) as int),
timestamp, high, low, average, volume
from history
where (low is not null and low <> '')
and strftime('%Y-%m-%d',timestamp) >= strftime('%Y-%m-%d','now', '-365 days')
order by low asc limit 1/;
$Sql{'24h'} = qq/select
timestamp, last, high, low, volume
from ticker
where strftime('%s', timestamp)
between ? and ?/;
$Sql{'anniv'} = qq/select
strftime('%s',timestamp_1), average_1,
strftime('%s',timestamp_2), average_2
from ranges
where ? between average_1 and average_2
order by timestamp_1 limit 1/;
$Sql{'coeffs'} = qq/select * from coefficients order by timestamp desc limit 1/;
$Sql{'first_date'} =
qq/select julianday(timestamp) from history order by timestamp limit 1/;
$Sql{'daily_min_max'} =
qq/select min(p.last), max(p.last) from ticker p where p.timestamp > datetime('now','-1 day')/;
$Sql{'monthly_min_max'} =
qq/select min(h.low), max(h.high) from history h where h.timestamp > datetime('now', '-30 day')/;
$Sql{'historical_coins'} =
qq/select julianday(timestamp) as ts, block, no_of_coins as coins from blocks/;
$Sql{'marketcap'} =
qq/select timestamp, data from coinmarketcap order by timestamp desc limit 1/;
### Other vars ########################################
my $historical_coins;
my $config = { show_cap_html => 0 };
### HELPER FUNCTIONS ########################################
sub large_num;
my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
my @wdays = qw/Sun Mon Tue Wed Thu Fri Sat/;
sub epoch_to_parts;
sub datetime_to_parts;
sub julian_to_epoch;
sub eta_time;
sub hum_duration;
sub color_num;
sub number_of_bitcoins;
sub nformat;
sub by_number;
sub myfetchall;
### OUTPUT FUNCTIONS ########################################
my $api_down = 1;
my $api_down_text = "Issues with the price API, investigating...";
sub debug_out;
sub console_out;
sub json_out;
sub html_out;
sub oneline_out;
sub mcap_out;
#### MAIN ################################################################
my $query = new CGI;
my $output = $query->param('o') || '';
####
my $Data = {};
my $sth;
my $rv;
### current price, from DB
my $result = myfetchall('latest_price'); #$sth->fetchall_arrayref();
my $latest = $result->[0];
my @_10min;
for my $r ( @{$result} ) {
push @_10min, [ $r->[0], $r->[1], $latest->[1] - $r->[1] ];
}
### last hour ticker data - hour open , max, min
$result = myfetchall('last_hour_ticker');
my $hour_open = $result->[0]->[0];
my $ntl_diff = $latest->[1] - $hour_open;
my @latest;
foreach my $item (@$result) {
push @latest, $item->[0];
}
my $hour_high = max(@latest);
my $hour_low = min(@latest);
$Data->{"price_history_last_hours"} = \@_10min;
$Data->{changes}->{hour} = {
open => $hour_open,
change_pct => $latest->[6],
change_price => $latest->[7],
hour_high => $hour_high,
hour_low => $hour_low,
};
$Data->{changes}->{day} = {
open => $latest->[8],
change_pct => $latest->[9],
change_price => $latest->[10]
};
$Data->{changes}->{week} = {
open => $latest->[11],
change_pct => $latest->[12],
change_price => $latest->[13]
};
#$sth->finish();
my $now = time();
my $_24h_ref =
$dbh->selectcol_arrayref( $Sql{daily_min_max}, { Columns => [ 1, 2 ] } );
my ( $_24h_min, $_24h_max ) = @{$_24h_ref};
my $last = $latest->[1];
$Data->{ticker} = {
timestamp => $latest->[0],
age => $now - $latest->[0],
last => $last,
'24h_max' => $_24h_max,
'24h_min' => $_24h_min,
volume => $latest->[4],
ntl_diff => $ntl_diff,
};
### 30 day min/max
my $_30d_ref =
$dbh->selectcol_arrayref( $Sql{monthly_min_max}, { Columns => [ 1, 2 ] } );
my ( $_30d_min, $_30d_max ) = @{$_30d_ref};
if ( $_24h_max > $_30d_max ) { $_30d_max = $_24h_max }
if ( $_24h_min < $_30d_min ) { $_30d_min = $_24h_min }
$Data->{ticker}->{'30d_min'} = $_30d_min;
$Data->{ticker}->{'30d_max'} = $_30d_max;
### historical coins
$sth = $dbh->prepare( $Sql{historical_coins} );
$rv = $sth->execute();
warn DBI->errstr if $rv < 0;
$historical_coins = $sth->fetchall_hashref(1); # used in the sub
$sth->finish();
my $coins_now = number_of_bitcoins( DateTime->now->jd() );
### historical data ########################################
my $history;
my %fixed;
$fixed{180} = { label => '6 months ago', short => '6mo' };
$fixed{1} = { label => '24 hours ago', short => '24h' };
$fixed{30} = { label => '1 month ago', short => '1mo' };
$fixed{90} = { label => '3 months ago', short => '3mo' };
$fixed{365} = { label => '1 year ago', short => '1yr' };
$fixed{3} = { label => '3 days ago', short => '3dy' };
#$fixed{730} = { label => '2 years ago', short => '2yr' };
$fixed{7} = { label => '1 week ago', short => '1wk' };
#$fixed{1095}= { label => '3 years ago', short=>'3yr' };
for my $yr ( 2, 3, 4 ) {
$fixed{ $yr * 365 } = { label => "$yr years ago", short => $yr . 'yr' };
}
my $labels = {
ath => { label => 'Record high ("ATH")' },
ytd => { label => "Year to date" },
'yhi' => { label => "This year's high" },
'ylo' => { label => "This year's low" },
'zhi' => { label => "365d rolling high", short => 'rhi' },
'zlo' => { label => "365d rolling low", short => 'rlo' }
};
foreach my $day ( sort { $a <=> $b } keys %fixed ) {
if ( $day == 1 ) { # special case
my $yesterday = time - 24 * 3600;
$sth = $dbh->prepare( $Sql{'24h'} );
$rv = $sth->execute( $yesterday - 5 * 60, $yesterday + 5 * 60 );
warn DBI->errstr if $rv < 0;
while ( my $ary = $sth->fetchrow_arrayref ) {
$history->{ sprintf( "%03d_day", $day ) } = {
timestamp => $ary->[0],
average => $ary->[1],
high => $ary->[2],
low => $ary->[3],
volume => $ary->[4],
label => $fixed{$day}->{label},
short => $fixed{$day}->{short}
};
}
$sth->finish();
next;
}
$sth = $dbh->prepare( $Sql{days_ago} );
$rv = $sth->execute("-$day days");
warn DBI->errstr if $rv < 0;
while ( my $aryref = $sth->fetchrow_arrayref ) {
my ( $timestamp, $high, $low, $average, $volume ) = @$aryref;
$history->{ sprintf( "%03d_day", $day ) } = {
timestamp => $timestamp,
high => $high,
low => $low,
average => $average,
volume => $volume,
short => $fixed{$day}->{short},
label => $fixed{$day}->{label}
};
}
}
$sth->finish();
foreach my $tag (qw(ath ytd yhi ylo zhi zlo)) {
my $short;
if ( defined $labels->{$tag}->{short} ) {
$short = $labels->{$tag}->{short};
}
else {
$short = $tag;
}
$sth = $dbh->prepare( $Sql{$tag} );
$rv = $sth->execute();
warn DBI->errstr if $rv < 0;
while ( my $ary = $sth->fetchrow_arrayref ) {
my ( $day, $timestamp, $high, $low, $average, $volume ) = @$ary;
$history->{ sprintf( "%03d_%s", $day, $tag ) } = {
timestamp => $timestamp,
high => $high,
low => $low,
average => $average,
volume => $volume,
short => $short,
label => $labels->{$tag}->{label}
};
}
}
$sth->finish();
# exponential and linear trend coefficients
$sth = $dbh->prepare( $Sql{coeffs} );
$sth->execute();
my $coefficients_ref = $sth->fetchall_arrayref( {} );
my $coefficients = $coefficients_ref->[0];
$Data->{scaffolding}->{coefficients} = $coefficients;
$sth->finish();
# get first julian day in history
my $first_jd_ref = $dbh->selectcol_arrayref( $Sql{first_date} );
my $first_jd = $first_jd_ref->[0];
$Data->{scaffolding}->{first_jd} = $first_jd;
### stuff info into some structures to pass to subs
# common format for console and HTML - overview
$Data->{layout} = [ # last, update, date, ago
[ $last, $ntl_diff, $latest->[0], $now - $latest->[0] ],
# Max row, volume
[
$_24h_max, $last - $_24h_max, $_30d_max, $last - $_30d_max, $latest->[4]
],
# Min row, Mcap
[
$_24h_min,
$last - $_24h_min,
$_30d_min,
$last - $_30d_min,
$last * $coins_now
],
# spread, no of coins
[
$_24h_max - $_24h_min,
( $_24h_max - $_24h_min ) / $last * 100,
$_30d_max - $_30d_min,
( $_30d_max - $_30d_min ) / $last * 100,
$coins_now
],
];
# common format for historical data
my %seen;
my $date_list;
### linear and exponential predictions
my ( $k_e, $m_e, $k_l, $m_l ) = map { $coefficients->{$_} }
qw/slope_exp intercept_exp slope_lin intercept_lin/;
my $exp_price = sub { my ($d) = @_; return exp($m_e) * exp( $k_e * $d ); };
my $lin_price = sub { my ($d) = @_; return $k_l * $d + $m_l; };
foreach my $tag ( sort by_number keys %{$history} ) {
push @{$date_list}, $tag;
next if $tag !~ m/^\d+/;
my $price;
if ( $tag =~ 'yhi$' or $tag =~ 'ath$' or $tag =~ 'zhi$' ) {
$price = $history->{$tag}->{high};
}
elsif ( $tag =~ 'ylo$' or $tag =~ 'zlo$' ) {
$price = $history->{$tag}->{low};
}
else {
$price = $history->{$tag}->{average};
}
my $diff = $last - $price;
my $pct = ( $last - $price ) / $price * 100;
my $vol = $history->{$tag}->{volume};
my $tot = $vol * $price;
my $date = datetime_to_parts( $history->{$tag}->{timestamp} )->{ymd};
push @{ $seen{$date} }, $tag;
my $jd = datetime_to_parts( $history->{$tag}->{timestamp} )->{jd};
my $no_of_coins = number_of_bitcoins($jd);
my $market_cap = $no_of_coins * $price;
next if ( scalar @{ $seen{$date} } > 1 and $tag =~ /[hi|lo]$/ );
# exp and lin price diffs
# $first_jd
my $exp_pred = &$exp_price( $jd - $first_jd );
my $lin_pred = &$lin_price($jd);
my $exp_diff = $price - $exp_pred;
my $lin_diff = $price - $lin_pred;
push @{ $Data->{history} },
[
$history->{$tag}->{label}, $date,
$price, $diff,
$pct, $vol,
$market_cap, $history->{$tag}->{short},
$exp_pred, $exp_diff,
$lin_pred, $lin_diff
];
}
### short term price predictions ########################################
my ( $K, $M ) = map { $coefficients->{$_} } qw/slope_30d intercept_30d/;
my $date_from_price = sub { my ($p) = @_; return ( $p - $M ) / $K; };
my $price_from_date = sub { my ($d) = @_; return $K * $d + $M; };
my %price_targets = (
apr2013hi => { p => 213.72, label => "Apr 2013 high" },
prebubbleline => { p => 125, label => "Pre-bubble price level" },
gox_end => { p => 133.35, label => 'Gox last price' },
apr2014lo => { p => 347.68, label => "Apr 2014 low" },
dollar_parity => { p => 1, label => 'Dollar parity' },
blaze => { p => 420, label => "Blazin'" },
ten_k => { p => 10_000, label => "USD 10k" },
million => { p => 1_000_000, label => 'MOON' },
twice_current => { p => 2 * $last, label => "Twice current price" },
spartans_hodl => { p => 300, label => "Spartans HODL!!!" },
sixtynine => { p => 69, label => "Sixty-Nine, \@Hubbabubba's fav" },
bitfinex_1B => {
p => 1_000_000_000 / 119_756,
label => "Stolen Bitfinex coins worth \$1.00B"
},
five_k => { p => 5_000, label => 'USD 5k' },
);
foreach my $tag (
sort { $price_targets{$b}->{p} <=> $price_targets{$a}->{p} }
keys %price_targets
)
{
my $p = $price_targets{$tag}->{p};
my $jd = &$date_from_price($p);
next if $jd < 0;
my $epoch = julian_to_epoch($jd);
next if ( ( $epoch - $now ) < 2 * 30 * 24 * 3600 );
next if ( abs( $last - $p ) / $last < 0.1 );
if ( ( $K > 0 and $last < $p ) or ( $K < 0 and $last > $p ) ) {
push @{ $Data->{future_prices}->{table} },
[
$price_targets{$tag}->{label}, nformat($p),
hum_duration( $epoch - $now )
];
}
}
#### Coinmarketcap data ########################################
my $marketcap_ref =
$dbh->selectcol_arrayref( $Sql{marketcap}, { Columns => [ 1, 2 ] } );
my $marketcap_data = $api_down ? [] : decode_json( $marketcap_ref->[1] );
my $marketcap_table;
my $metadata = pop @{$marketcap_data};
foreach my $entry ( @{$marketcap_data} ) {
push @{$marketcap_table},
{ map { $_ => $entry->{$_} }
qw/rank name symbol market_cap_usd total_supply percent_change_7d percent_change_1h percent_change_24h available_supply price_usd 24h_volume_usd price_btc/
};
}
$Data->{marketcap}->{fetched} = $marketcap_ref->[0];
foreach my $tag ( "active_other_coins", "total_other_coins", "total_mcap" ) {
$Data->{marketcap}->{$tag} = $metadata->{$tag};
}
$Data->{marketcap}->{list} = $marketcap_table;
# legacy info for external interface
$Data->{draper} = {
coins => 29656.51306529,
price_at_purchase => 600,
purchase_value => 600 * 29656.51306529,
current_value => $last * 29656.51306529,
win_loss => ( $last - 600 ) * 29656.51306529
};
### output options
if ( $output eq 'json' ) {
json_out($Data);
}
elsif ( $output eq 'console' ) {
console_out($Data);
}
elsif ( $output eq 'irc' ) {
oneline_out($Data);
}
elsif ( $output eq 'debug' ) {
debug_out($Data);
}
elsif ( $output eq 'mcap' ) {
mcap_out($Data);
}
else {
html_out($Data);
}
$dbh->disconnect();
###############################################################################
### HELPER SUBROUTINES
sub large_num { # return numbers in K, M, B based on size
my ($x) = @_;
my $negative = 1 if $x < 0;
$x = -$x if $negative;
return $negative ? -$x : $x if $x < 1_000;
return sprintf( "%.02fk", $negative ? -$x / 1_000 : $x / 1_000 )
if ( $x >= 1_000 and $x < 1_000_000 );
return sprintf( "%.02fM", $negative ? -$x / 1_000_000 : $x / 1_000_000 )
if ( $x >= 1_000_000 and $x < 1_000_000_000 );
return
sprintf( "%.02fB", $negative ? -$x / 1_000_000_000 : $x / 1_000_000_000 )
if ( $x >= 1_000_000_000 );
}
sub epoch_to_parts {
# EX format_utc
# in: epoch seconds,
# output: hashref with named fields
# std: <weekday day mon year HH:MI:SS>
# iso: YYYY-MM-DD HH:MM:SS
# ymd: YYYY-MM-DD
# hms: HH:MM:SS
# jd: Julian TODO
my ( $e, $flag ) = @_;
my $out;
# 0 1 2 3 4 5 6 7 8
my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
gmtime($e);
if ( $e > ( 1436044942 + 500 * 365 * 24 * 3600 ) ) { # far in the future
$out->{out} = sprintf( "In the year %d", $year + 1900 );
}
else {
$out->{std} = sprintf(
"%s %02d %s %04d %02d:%02d:%02d",
$wdays[$wday], $mday, $months[$mon], $year + 1900,
$hour, $min, $sec
);
}
my $dt = DateTime->from_epoch( epoch => $e );
$out->{iso} = sprintf(
"%04d-%02d-%02d %02d:%02d:%02d",
$year + 1900,
$mon + 1, $mday, $hour, $min, $sec
);
$out->{ymd} = sprintf( "%04d-%02d-%02d", $year + 1900, $mon + 1, $mday );
$out->{hms} = sprintf( "%02d:%02d:%02d", $hour, $min, $sec );
$out->{jd} = $dt->jd();
return $out;
}
sub datetime_to_parts {
# EX date_parts
# EX date_time
# input: "YYYY-MM-DD HH:MI:SS" string
# output: hashref with named fields
# ymd (0): YYYY-MM-DD string
# hms (1): HH:MI:SS string
# str (2): DD mon YYYY string
# jd (3): Julian date
# ep (4): epoch seconds
my ($ts) = @_;
if ( $ts =~
m/(?<Y>\d{4})-(?<M>\d{2})-(?<D>\d{2}) (?<h>\d{2}):(?<m>\d{2}):(?<s>\d{2})/
)
{
my $dt = DateTime->new(
year => $+{Y},
month => $+{M},
day => $+{D},
hour => $+{h},
minute => $+{m},
second => $+{s}
);
return {
ymd => sprintf( "%04d-%02d-%02d", $+{Y}, $+{M}, $+{D} ),
hms => sprintf( "%02d:%02d:%02d", $+{h}, $+{m}, $+{s} ),
str => sprintf( "%d %s %04d", $+{D}, $months[ $+{M} - 1 ], $+{Y} ),
jd => $dt->jd(),
ep => $dt->epoch()
};
}
else {
warn "--> $ts is not correctly formatted date string\n";
return [];
}
}
sub julian_to_epoch {
# Ex Jul2Greg
# input: Julian date
# output: epoch seconds
# http://aa.usno.navy.mil/faq/docs/JD_Formula.php
my ($JUL) = @_;
my $D = int($JUL);
my $frac = $JUL - $D;
# Julian dates change at noon, convert so it's at midnight instead
if ( $frac < 0.5 ) {
$frac = $frac + 0.5;
}
else {
$D++;
$frac = $frac - 0.5;
}
my ( $yyyy, $MM, $dd );
{
use integer; # fortran code requires integer division
my $L = $D + 68569;
my $N = 4 * $L / 146097;
$L = $L - ( 146097 * $N + 3 ) / 4;
my $I = 4000 * ( $L + 1 ) / 1461001;
$L = $L - 1461 * $I / 4 + 31;
my $J = 80 * $L / 2447;
my $K = $L - 2447 * $J / 80;
$L = $J / 11;
$J = $J + 2 - 12 * $L;
$I = 100 * ( $N - 49 ) + $I + $L;
( $yyyy, $MM, $dd ) = ( $I, $J, $K );
}
my $span;
my ( $hh, $mm, $ss );
$span = $frac * 24 * 60 * 60; # number of seconds
$hh = ( $span / ( 60 * 60 ) ) % 24;
$mm = ( $span / 60 ) % 60;
$ss = $span % 60;
# return epoch seconds
return timegm( $ss, $mm, $hh, $dd, $MM - 1, $yyyy );
}
sub eta_time {
# input: seconds
# ouput: duration in days, hours, minutes and seconds
my ($ep) = @_;
my ( $dd, $hh, $mm, $ss ) = (
int( $ep / ( 24 * 60 * 60 ) ),
( $ep / ( 60 * 60 ) ) % 24,
( $ep / 60 ) % 60,
$ep % 60
);
if ( $dd > 0 ) {
return sprintf( "%3dd %02dh %02dm %02ds", $dd, $hh, $mm, $ss );
}
elsif ( $hh > 0 ) {
return sprintf( "%02dh %02dm %02ds", $hh, $mm, $ss );
}
else {
return sprintf( "%02dm%02ds", $mm, $ss );
}
}
sub hum_duration {
# in: seconds
# out: nicely formatted string years, months, days
my ($s) = @_;
my %pieces = ( year => 0, month => 0, day => 0 );
my $v = Time::Seconds->new($s);
my $long_years;
# check for years
if ( $v->years > 0 ) {
# don't bother w/ years > 500
if ( $v->years > 500 ) {
$long_years = sprintf( "%.02f years", $v->years );
}
# grab the integer part, remove years from duration
$pieces{year} = int( $v->years );
$s = $s - $pieces{year} * 365 * 24 * 3600;
$v = Time::Seconds->new($s);
}
if ( $v->months > 0 ) {
$pieces{month} = int( $v->months );
$s = $s - $pieces{month} * 30 * 24 * 3600;
$v = Time::Seconds->new($s);
}
if ( $v->days > 0 ) {
$pieces{day} = sprintf( "%.0f", $v->days ); # use rounding
}
my $out;
foreach my $u (qw(year month day)) {
next if $pieces{$u} == 0;
my $suffix = $pieces{$u} > 1 ? $u . 's' : $u;
push @$out, $pieces{$u} . ' ' . $suffix;
}
# return join(', ',@$out);
# http://blog.nu42.com/2013/10/comma-quibbling-in-perl.html - "If
# the maintenance programmer has issues with the use of the array
# slice and range operator above, s/he might use this as an
# opportunity to learn about them."
return $long_years if ( defined $long_years );
my $n = @$out;
return $out->[0] if $n == 1;
return join(
' and ' => join( ', ' => @$out[ 0 .. ( $n - 2 ) ] ),
$out->[-1],
);
}
sub color_num {
my ($x) = @_;
my $is_pct = 0;
my $f = new Number::Format;
if ( $x =~ m/%$/ ) {
$is_pct = 1;
$x =~ s/%$//m;
}
my $dec = $is_pct ? 1 : 2;
if ( $x < 0 ) {
$x = $f->format_number( $x, $dec, 2 ); # if $x < -1_000;
$x = "$x%" if $is_pct;
return "<span class='negative'>$x</span>";
}
else {
$x = $f->format_number( $x, $dec, 2 ); #if $x > 1_000;
$x = "$x%" if $is_pct;
return return "<span class='positive'>$x</span>";
}
}
sub number_of_bitcoins {
# input: julian date
# output: number of bitcoins mined since date
my ($jd) = @_;
my $min_jd = min keys %{$historical_coins};
my $max_jd = max keys %{$historical_coins};
if ( $jd > $max_jd or $jd < $min_jd ) {
return undef;
}
# exact value?
if ( exists $historical_coins->{$jd} ) {
return $historical_coins->{$jd};
}
# find between which historical values input lies
my $jd_2 = first { $_ > $jd } sort keys %{$historical_coins};
my $jd_1 = first { $_ < $jd } reverse sort keys %{$historical_coins};
# number of coins for this segment is a right triangle with base
# $jd_2-$jd_1, resting on a rectangle of height
# $historical{$jd1}. The number we want is the height of the
# triangle at $jd_2, proportional to the distance between $jd_1
# and $jd
my $B = $historical_coins->{$jd_1}->{coins};
my $h = $historical_coins->{$jd_2}->{coins} - $B;
my $x = ( $jd - $jd_1 ) / ( $jd_2 - $jd_1 ) * $h;
return $x + $B;
}
sub nformat {
my ($in) = @_;
my $nf = new Number::Format;
return $nf->format_number( $in, 2, 2 );
}
sub by_number { # http://perlmaven.com/sorting-mixed-strings
my ($anum) = $a =~ /(\d+)/;
my ($bnum) = $b =~ /(\d+)/;
( $anum || 0 ) <=> ( $bnum || 0 );
}
###############################################################################
### OUTPUT SUBS
sub debug_out {
my ($D) = @_;
print header('application/json');
# print to_json( $D->{debug}, { ascii => 1, pretty => 1 } );
}
#### Console ####
sub console_out {
my ($D) = @_;
if ($api_down) {
print $api_down_text, "\n";
return;
}
my $last = sprintf( "%.02f", $D->{ticker}->{last} );
my @out;
my $layout = $D->{layout};
push @out, '';
my $d = shift @{$layout};
my $diff = sprintf( '%+.02f', $d->[1] );
if ( $diff < 0 ) { $diff = RED . $diff . RESET }
else { $diff = GREEN . $diff . RESET }
push @out,
sprintf(
"%8s %16s [%17s] | %34s (%s)",
'Last', BLUE . $last . RESET,
$diff,
epoch_to_parts( $d->[2] )->{std},
eta_time( $d->[3] )
);
my @olh;
my %olh_translate = (
open => BLUE . 'O' . RESET,
hour_low => 'Low',
hour_high => 'High',
);
foreach my $tag ( 'hour_low', 'hour_high' ) {
push @olh, (
$olh_translate{$tag},
$D->{changes}->{hour}->{$tag},
$D->{ticker}->{last} - $D->{changes}->{hour}->{$tag},
( $D->{ticker}->{last} - $D->{changes}->{hour}->{$tag} ) /
$D->{changes}->{hour}->{$tag} * 100,
);
}
push @out,
sprintf( "%8s %8.02f (%+8.02f) [%.01f%%] %8s %8.02f (%+8.02f) [%.01f%%]",
@olh );
$d = shift @{$layout};
push @out,
sprintf( "%8s %8.02f (%+8.02f) | %8s %8.02f (%+8.02f) | %8s %7s",
'24h max', $d->[0], $d->[1], '30d max', $d->[2], $d->[3],
'24h vol', large_num( $d->[-1] ) );
$d = shift @{$layout};
push @out,
sprintf( "%8s %8.02f (%+8.02f) | %8s %8.02f (%+8.02f) | %8s %7s",
'min', $d->[0], $d->[1], 'min', $d->[2], $d->[3],
'Mcap', large_num( $d->[-1] ) );
$d = shift @{$layout};
push @out,
sprintf( "%8s %8.02f [%7.01f%%] | %8s %8.02f [%7.01f%%] | %8s %7s",
'spread', $d->[0], $d->[1], 'spread', $d->[2], $d->[3],
'Coins', large_num( $d->[-1] ) );
# final line with general info
#print "\n";
foreach my $line ( @{ $D->{history} } ) {
my ( $label, $date, $price, $diff, $pct, $vol, $mcap, $short ) =
@{$line}[ 0 .. 7 ];
$vol = large_num($vol);
$mcap = large_num($mcap);
if ( $diff < 0 and $pct < 0 ) {
$diff = RED . sprintf( "%+.02f", $diff ) . RESET;
$pct = RED . sprintf( "%+.01f%%", $pct ) . RESET;
}
else {
$diff = GREEN . sprintf( "%+.02f", $diff ) . RESET;
$pct = GREEN . sprintf( "%+.01f%%", $pct ) . RESET;
}
push @out,
sprintf(
"%19s %10s %8.02f %18s %17s %8s %8s",
$label, '[' . $date . ']',
$price, $diff, $pct, $vol, $mcap
);
}
# pad the output to fit a screen
my $line_diff = 22 - scalar @out;
my $idx = 0;
print join( "\n", @out );
while ( $idx < $line_diff ) {
print "\n";
$idx++;
}
} # console_out
sub json_out {
my ($D) = @_;
print header('application/json');
if ($api_down) {
print '{"'.$api_down_text.'"}';
return;
}
print to_json( $D, { ascii => 1, pretty => 1 } );
} #json_out
#### HTML ######################################################
sub html_out {
my ($D) = @_;
my $about_page = 'http://gerikson.com/btcticker/about.html';
my $last = sprintf( "%.02f", $D->{ticker}->{last} );
my $array = $D->{layout};
my $diff = $array->[0]->[1];
my $coins_now = $D->{est_no_of_coins};
### Build structures ########################################
my $last_prices = $D->{"price_history_last_hours"};
my $current = shift @{$last_prices}; # get rid of current data;
my $t_latest_rows;
foreach my $item ( reverse @{$last_prices} ) {
push @{ $t_latest_rows->[0] }, epoch_to_parts( $item->[0] )->{hms};
push @{ $t_latest_rows->[1] }, sprintf( '%.02f', $item->[1] );
push @{ $t_latest_rows->[2] },
color_num( sprintf( "%.02f", $item->[2] ) );
}
my $latest_table;
push @{$latest_table}, th( $t_latest_rows->[0] );
push @{$latest_table}, td( $t_latest_rows->[1] );
push @{$latest_table}, td( $t_latest_rows->[2] );
my $olh_table;
push @{$olh_table}, th( [ 'Open', 'Low', 'High' ] );
push @{$olh_table},
td(
[
map { $D->{changes}->{hour}->{$_} }
( 'open', 'hour_low', 'hour_high' )