chiark / gitweb /
911242c82a5f3a6963e22a7079ce5e2ab86808d4
[ypp-sc-tools.db-test.git] / pctb / yppsc-commod-processor
1 #!/usr/bin/perl -w
2
3 # helper program for processing commodity output
4
5 # This is part of ypp-sc-tools, a set of third-party tools for assisting
6 # players of Yohoho Puzzle Pirates.
7 #
8 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 # are used without permission.  This program is not endorsed or
25 # sponsored by Three Rings.
26
27
28 use strict (qw(vars));
29 use HTTP::Request;
30 use IO::File;
31 use POSIX;
32 use LWP::UserAgent;
33 use XML::Parser;
34
35 # $commod{'Hemp'}{Buy|Sell}{'stall'}{Stall}
36 # $commod{'Hemp'}{Buy|Sell}{'stall'}{Price}
37 # $commod{'Hemp'}{Buy|Sell}{'stall'}{Qty}
38 # $commod{'Hemp'}{Hold}
39
40 our @v;
41 our ($commod,$stall,%commod);
42
43 @ARGV==1 or die "You probably don't want to run this program directly.\n";
44 our ($mode) = shift @ARGV;
45
46 # ./yppsc-commod-processor tsv <t |less -x40,80,90,100,110
47
48 sub bs_read ($$) {
49     my ($bs,$c) = @_;
50     return if @v <= $c;
51     my ($price,$qty) = @v[$c..$c+1];
52     return if !length($price) && !length($qty);
53     die "$_ ?" unless length($price) && length($qty);
54     $commod{$commod}{$bs}{$stall}= {
55         Stall => $stall,
56         Price => $price,
57         Qty => $qty,
58     };
59 }
60
61 while (<>) {
62     chomp;
63     @v= split /\t/;
64 #print STDERR "[".join("|",@v)."]\n";
65     ($commod,$stall) = @v;
66     bs_read(Buy,  2);
67     bs_read(Sell, 4);
68     $commod{$commod}{Hold}= $v[6]+0 if @v>6;
69 }
70
71 our $current;
72
73 sub bs_p ($$$) {
74     my ($commod,$bs,$sortmul) = @_;
75     my $ary= $current->{$bs};
76     my $r= [ ];
77 #print Dumper($ary);
78     foreach my $stall (sort {
79         $sortmul * ($ary->{$a}{Price} <=> $ary->{$b}{Price});
80     } keys %$ary) {
81         push @$r, $ary->{$stall};
82     }
83     return $r;
84 }
85
86 sub bs_p_bestprice ($) {
87     my ($l) = @_;
88     if (@$l) {
89         printf("| %-25.25s %4d", $l->[0]{Stall}, $l->[0]{Price}) or die $!;
90     } else {
91         printf("| %25s %4s","","") or die $!;
92     }
93 }
94
95 our $arbitrage_only= 0;
96
97 sub main__arbitrage () {
98     my @arbs= ();
99     foreach $commod (sort keys %commod) {
100         $current= $commod{$commod};
101         my @buys=  @{ bs_p($commod,Buy, -1) };
102         my @sells= @{ bs_p($commod,Sell,+1) };
103         my $profit= 0;
104         my $cqty= 0;
105         my $info= '';
106         my $arbs= [];
107         for (;;) {
108 #print Dumper($commod,\@buys,\@sells);
109             last unless @buys;
110             last unless @sells;
111             my $pricediff= $buys[0]{Price} - $sells[0]{Price};
112             last unless $pricediff > 0;
113             our $qty= 1000;
114             sub arb_check_qty (\@) {
115                 my ($verbs) = @_;
116                 my $vqty= $verbs->[0]{Qty};
117                 return if $vqty =~ m/^\>/;
118                 $qty= $vqty if $qty > $vqty;
119                 return if $vqty;
120                 my $verb= shift @$verbs;
121             }
122             arb_check_qty(@buys);
123             arb_check_qty(@sells);
124             next unless $qty;
125             my $tprofit= $qty*$pricediff;
126             $profit += $tprofit;
127             $cqty += $qty;
128             
129             $info.=
130                 sprintf("%-13.13s| %-19.19s %4d| %-19.19s %4d|%3d x%3d =%3d\n",
131                        $commod,
132                        $buys[0]{Stall},$buys[0]{Price},
133                        $sells[0]{Stall},$sells[0]{Price},
134                        $qty, $pricediff, $tprofit);
135             sub arb_subtract_qty (\@) {
136                 my ($verbs) = @_;
137                 my $verb= shift @$verbs;
138                 unshift @$verbs, {
139                     Stall => $verb->{Stall},
140                     Price => $verb->{Price},
141                     Qty => $verb->{Qty} - $qty
142                 };
143             }
144             arb_subtract_qty(@buys);
145             arb_subtract_qty(@sells);
146         }
147         next unless $profit;
148         $info.=
149             sprintf("%-13.13s| %19s %4s| %19s %4s|%3d      %4d\n",
150                     $commod, '','', '','', $cqty, $profit);
151         push @arbs, { Profit => $profit, Info => $info };
152     }
153     my $allprofit;
154
155     if (!@arbs) {
156         print "No arbitrage opportunities.\n" or die $!;
157         return;
158     }
159     my $bigdiv= <<END;
160 =============+=========================+=========================+=============
161 END
162
163     print <<END or die $!;
164
165 commodity    | seller             price| buyer              price| qty  ea prof
166 END
167
168     my $div= $bigdiv;
169     foreach my $arb (sort {
170         $b->{Profit} <=> $a->{Profit};
171     } @arbs) {
172         print $div,$arb->{Info} or die $1;
173         $div= <<END;
174 -------------+-------------------------+-------------------------+-------------
175 END
176         $allprofit += $arb->{Profit};
177     }
178     print $bigdiv or die $!;
179     printf("%-13.13s  %19s %4s  %19s %4s %-5s %7d\n",
180            '', '','', '','', 'TOTAL', $allprofit)
181         or die $!;
182 }
183
184 sub main__bestprices () {
185     foreach $commod (sort keys %commod) {
186         $current= $commod{$commod};
187         my $buys=  bs_p($commod,Buy, -1);
188         my $sells= bs_p($commod,Sell,+1);
189         if ($arbitrage_only) {
190         }
191         printf("%-15.15s", $commod) or die $!;
192         bs_p_bestprice($buys);
193         bs_p_bestprice($sells);
194         print("\n") or die $!;
195     }
196 }
197
198 sub bs_p_tsv ($) {
199     my ($bs) = @_;
200     if (exists $current->{$bs}{$stall}) {
201         my $si= $current->{$bs}{$stall};
202         printf("\t%d\t%s", $si->{Price}, $si->{Qty}) or die $!;
203     } else {
204         printf("\t\t") or die $!;
205     }
206 }
207
208 sub main__tsv () {
209     foreach $commod (sort keys %commod) {
210         $current= $commod{$commod};
211         my %stalls;
212         map { $stalls{$_}=1; } keys %{ $current->{Buy}  };
213         map { $stalls{$_}=1; } keys %{ $current->{Sell} };
214         foreach $stall (sort keys %stalls) {
215             printf("%s\t%s", $commod, $stall) or die $!;
216             bs_p_tsv(Buy);
217             bs_p_tsv(Sell);
218             print("\n") or die $!;
219         }
220     }
221 }
222
223
224 our (%commodmap);
225 our ($pctb) = 'http://pctb.ilk.org/';
226 our ($ua);
227
228 sub load_commodmap() {
229     undef %commodmap;
230     my $c= new IO::File "#commodmap#.tsv";
231     if (!$c) { $!==&ENOENT or die $!; return; }
232     while (<$c>) {
233         m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
234         $commodmap{$1}= $2;
235     }
236     $c->error and die $!;
237     close $c;
238 }
239
240 sub refresh_commodmap() {
241     my $ua= LWP::UserAgent->new;
242     my $resp= $ua->get("$pctb/commodmap.php");
243     die $resp->status_line unless $resp->is_success;
244
245     my $cdata='';
246     my $incommodmap=0;
247     my $intag='';
248     my %got;
249     my $o= new IO::File "#commodmap#.tsv.new",'w' or die $!;
250
251     my $xp= new XML::Parser
252         (Handlers =>
253          {
254              Start => sub {
255                  $_=$_[1];
256 print STDERR "START [$_] intag=$intag icm=$incommodmap\n";
257                  if (m/^commodmap$/i) {
258                      $incommodmap++;
259                      undef %got;
260                  } elsif (m/^(?:name|index)$/i) {
261                      $cdata='';
262                      $intag=lc($_) if $incommodmap;
263                      print STDERR "START RECOGNISED $intag icm=$incommodmap\n";
264                  } else {
265                      print STDERR "START UNRECOGNISED\n";
266                  }
267              },
268              End => sub {
269                  $_=$_[1];
270 print STDERR "END [$_] intag=$intag icm=$incommodmap\n";
271                  if (m/^commodmap$/i) {
272                      $incommodmap--;
273                      die unless exists $got{'name'};
274                      die unless exists $got{'index'};
275                      die unless $got{'index'} =~ m/^\s*([1-9]\d{0,3})\s*$/;
276                      my $index= $1;
277                      $_= $got{'name'};
278                      s/^\s+//; s/\s+$//; s/\n/ /g; s/\s+/ /;
279                      die if exists $commodmap{$_};
280                      $commodmap{$_}= $index;
281                      print $o "$_\t$index\n" or die $!;
282                  } elsif (lc $_ eq $intag) {
283                      $got{$intag}= $cdata;
284                  }
285              },
286              Char => sub {
287 print STDERR "CHAR [$_[1]] intag=$intag icm=$incommodmap\n";
288                  $cdata .= $_[1];
289              }
290          }) or die;
291     my $content= $resp->content;
292
293     # hacks to strip off drivel that seems to have been added!
294     $content =~ s/^.*\n(\<\?xml)/$1/s;
295     $content =~ s/\<\/body\>.*//s;
296     print STDERR "[[[$content]]]\n";
297     $xp->parse($content);
298     close $o or die $!;
299     rename "#commodmap#.tsv.new","#commodmap#.tsv" or die $!;
300 }
301         
302 #
303 #sub bs_gen_md ($) {
304 #    my ($bs) = @_;
305         
306
307 sub main__genmarketdata () {
308     our $version= '005b';
309
310     load_commodmap();
311     my @missing= grep { !exists $commodmap{$_} } keys %commod;
312     if (@missing) {
313         refresh_commodmap();
314         my $missing=0;
315         foreach $commod (sort keys %commod) {
316             next if exists $commodmap{$commod};
317             print STDERR "Unknown commodity \`%s'!\n";
318             $missing++;
319         }
320         die "$missing unknown commodities.  OCR failure?\n"
321             if $missing;
322     }    
323     
324  #   foreach $commod (sort keys %commod) {
325 #       next if 
326         
327
328 #    bs_gen_md(Buy);
329 #    bs_gen_md(Sell);
330 }
331
332
333 sub main__upload () {
334     die "\nUploading not yet implemented, sorry.\n";
335 }
336
337
338 $mode =~ s/\-//;
339 &{"main__$mode"};
340 close(STDOUT) or die $!;