blib/script/igdisp.pl untested

filter: Statementstmt 0.0% 0 / 227 Branchbran 0.0% 0 / 110 Conditioncond 0.0% 0 / 136 MC/DCmcdc 0.0% 0 / 77 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 566 CC 9 SCAR 24.4
CC
9
Cov
0%
datecmp
30.0
expression
12.0
help
12.0
CRAP 11.5
1 #!/usr/bin/env perl
2 use FindBin;
3 use lib $FindBin::RealBin."/../lib";
4 use lib $FindBin::RealBin."/../..";
5  
6 use Finance::IG;
7 use Getopt::Std;
8 use Time::Piece;
9 use strict;
10 no strict 'refs';
11 use warnings;
12  
13  
14 my %opt;
15  
16 my @credentials=(
17 $FindBin::RealBin.'/../../credentials.pl' ,
18 $FindBin::RealBin.'/../credentials.pl',
19 $FindBin::RealBin.'/credentials.pl',
20 './credentials.pl',
21 $ENV{HOME}.'/.config/IG/credentials.pl',
22 );
23  
24 our $VERSION=0.103;
25 ######### code for multiiple -n x arguments treat as single joined with |. Not handled with getopts.
26 $opt{n}=[];
27 for my $i (0..$#ARGV)
28 {
29 next if (!defined $ARGV[$i]);
30 if ($ARGV[$i] eq '-n')
31 {
32 push(@{$opt{n}},$ARGV[$i+1]);
33 $ARGV[$i]=$ARGV[$i+1]=undef;
34 $i+=2;
35 }
36 elsif ($ARGV[$i]=~s/^-n//)
37 {
38 push(@{$opt{n}},$ARGV[$i]);
39 $ARGV[$i++]=undef;
40 }
41 }
42 @ARGV=grep { defined $_ } @ARGV;
43 die "-n requires an argument, not provided" if (0<grep { !defined $_ } @{$opt{n}}) ;
44 $opt{n}=join('|',@{$opt{n}});
45 $opt{n} or delete $opt{n};
46 $opt{a}=1;
47 #########
48  
49 getopts('ra:c:eotf:FNhn:s:SO:g:v:', \%opt) or help("Aborted! -h for help ");
50  
51 my $ig;
52 # IG Credentials needed.
53 # You can add them to enviroment variables as bellow or
54 # directly hardcode them below.
55 # It can be useful to have a demo account to, this should be a seperate instance of the
56 # object.
57  
58 my $capital; # hardcode your capital here if you want.
59  
60 $opt{c}.='/credentials.pl' if ($opt{c} and ! -f $opt{c});
61 unshift(@credentials,$opt{c}) if ($opt{c});
62  
63 if ($opt{e})
64 {
65 if ($ENV{IGUSER} and $ENV{IGPASS} and $ENV{IGAPIKEY})
66 {
67 print "Environment variables IGUSER, and IGPASS. and IGAPIKEY
68 are all set and accessible so will use those.\n";
69 exit 1;
70 }
71
72 print "IGUSER is missing\n" if (!$ENV{IGUSER});
73 print "IGPASS is missing\n" if (!$ENV{IGPASS});
74 print "IGAPIKEY is missing\n" if (!$ENV{IGAPIKEY});
75  
76 }
77
78 if ($ENV{IGUSER} and $ENV{IGPASS} and $ENV{IGAPIKEY})
79 {
80 $ig=Finance::IG->new(
81 username=> $ENV{IGUSER},
82 password=> $ENV{IGPASS},
83 apikey=> $ENV{IGAPIKEY},
84 isdemo=>0,
85 col=>0,
86 );
87 }
88 else
89 {
90 # eval { require $FindBin::RealBin.'/../../credentials.pl' } or
91 # eval { require $FindBin::RealBin.'/../credentials.pl' } or
92 # eval { require $FindBin::RealBin.'/credentials.pl' } or
93 # eval { require './credentials.pl' } or
94  
95 my $reqok=0;
96 map { $reqok ||=eval { require $_ } } @credentials;
97  
98
99 $reqok or die "Need a credentials.pl file, looks something like this but contains actual metrobank login credentials:
100 sub cred
101 {
102 return {
103 username=>'', # Your ig username
104 password=>'', # Your ig password
105 apikey=>'' , # Your ig apikey
106 }
107 };
108 1;
109  
110 You can alternatively use 3 environment variables named IGUSER,IGPASSWORD, IGAPIKEY.
111 The credentials file is searched for in the following paths:
112 @credentials
113 You can also use -c path or file.
114 " ;
115 $ig=Finance::IG->new(cred(),isdemo=>0,col=>0);
116  
117 # This hack allows you to set your starting capital in the credentials file if you wish
118 my %x=cred();
119 $capital//=$x{capital};
120 }
121  
122 if ($opt{e})
123 {
124 my ($e)=grep { m/credentials/ } keys %INC;
125 $e=~s#/[^/]+/\.\.##g;
126 $e=~s#/[^/]+/\.\.##g;
127 print "credentials.pl from : ".$e."\n";
128 exit;
129 }
130  
131 # map { $ENV{$_}//='' } qw(IGUSER IGPASS IGAPIKEY); # empty allowed but caught, undef not allowed
132 #$ig=Finance::IG->new(
133 # username=> $ENV{IGUSER},
134 # password=> $ENV{IGPASS},
135 # apikey=> $ENV{IGAPIKEY},
136 # isdemo=>0,
137 #);
138  
139 die "missing credentials username, try setting the environment variable IGUSER" if ($ig->username eq '');
140 die "missing credentials password, try setting the environment variable IGPASS" if ($ig->username eq '');
141 die "missing credentials apikey, try setting the environment variable IGAPIKEY" if ($ig->username eq '');
142 my $sortlist;
143  
144 # -o auto-generate a time based file and use this to send output to
145 # t display headers every 10 lines
146 # n no headers
147 # f n : use format number
148 # h help
149 # g grep
150 # S print NO summary line
151 # s sort list
152 # sort list can be
153 # a comma seperated list of fields each with an optional minus sign eg
154 # -s'-profitpc,instrumentName' sorts by profit highest first, and if the same, then orders by name
155 # Here the following can be used as abbreviations
156 # n instrumentName
157 # o open => level
158 # b bid
159 # v value => atRisk
160 # p profitpe
161 # if no commas
162 # or a comma seperated list of elements, each of which may be optionally started with - for reverse sort
163 # the above abbrevs may be used. default is -p,n or -profitpc,instrumentName or -pn
164  
165 if (exists $opt{s} and defined $opt{s})
166 {
167 my @list;
168 if ($opt{s}=~m/^[-nobvp]+$/)
169 {
170 @list=split(//,$opt{s});
171 }
172 else
173 {
174 @list=split(/,/,$opt{s});
175 @list=map { s/^-//?('-',$_):$_ } @list;
176 }
177 for (@list)
178 {
179 $_='instrumentName' if ($_ eq 'n');
180 $_='level' if ($_ eq 'o');
181 $_='bid' if ($_ eq 'b');
182 $_='atrisk' if ($_ eq 'v');
183 $_='profitpc' if ($_ eq 'p');
184 }
185 map { ($list[$_] eq '-') and $list[$_+1]='-'.$list[$_+1]; } (0..$#list);
186 @list=grep { $_ ne '-' } @list;
187 $sortlist=\@list;
188 }
189  
190 my $gel;
191 my $maskint;
192 if ($opt{O})
193 {
194 $gel=1; # default is date must be greater than specified.
195 if ($opt{O}=~s/^([-\+=><])//)
196 {
197 $gel=-1 if ($1 eq '-' or $1 eq '<');
198 $gel=1 if ($1 eq '+' or $1 eq '>');
199 $gel=0 if ($1 eq '=');
200 }
201 $opt{O}=~s#/#-#g;
202  
203 my $warning;
204 my $tt;
205 {
206 local $SIG{__WARN__} = sub {$warning = shift};
207 $tt=Time::Piece->strptime($opt{O},"%Y-%m-%dT%H:%M:%S") or die "strptime failed for -O $opt{O} " ;
208 }
209 $tt or die "#2strptime failed for -O $opt{O} ";
210 my @a=split(/[-:T]/,$opt{O}); # how many elements were parsed?
211 # we expect that for <, =, or > it always means or equal to, and we need to mask the comparison.
212 # so that if all before a day was given we expect to mask the hrs min and sec and then do <= to
213 # likewise if = is specified, gel==0, then we expect to mask the result and then do --
214 # likewise uf > is specified we implement >= on the masked value.
215 # to mask a Time::Piece object, we subtract the curent minor units, eg to mask sec and mins $t=$t-$t->sec-$t->min*60;
216 # Easy way to mask is to change the format string used to convert the data
217 $maskint=@a; # so 6 means all supplied, 3 means format string truncated to %Y-%m-%d etc
218 $opt{O}=$tt;
219 }
220  
221 $opt{h} and help();
222 $opt{g}//='';
223  
224 if (exists $opt{n} and !$opt{t})
225 {
226 $opt{S}=1;
227 $opt{N}=!$opt{N};
228 }
229  
230 my $f="";
231 my $out="stdout";
232  
233 $ig->login();
234  
235 my $p=$ig->positions();
236 if ($opt{a})
237 {
238 $p=$ig->agg($p,$sortlist);
239 }
240 else
241 {
242 $p=$ig->nonagg($p,$sortlist);
243 }
244 # $ig->sorter(['-atrisk'],$p);
245  
246  
247 if ($opt{o})
248 {
249 # output file auto generated
250
251 my $date=Time::Piece->gmtime();
252 my $d="/home/mark/igrec/r2";
253 my $f=$date->strftime("$d/%Y-%m-%d-%H.%M.txt");
254  
255 open($out,">$f") or die "failed to open $f";
256
257 }
258  
259 my @format=(
260 "%03drank %-41sinstrumentName %+6.2fsize %-9.2flevel ".
261 "%-9.2fbid £%-8.2fprofit %5.1fprofitpc%% £%10.2fatrisk\n",
262
263 "%sepic|%sinstrumentName|%0.2fsize|%-0.2flevel|".
264 "%-0.2fbid|£%-0.2fprofit|%0.1fprofitpc%%|£%0.2fatrisk\n",
265
266 "%sepic|%sinstrumentName|%0.2fsize|%-0.2flevel|".
267 "%-0.2fbid|£%-0.2fprofit|%0.1fprofitpc%%|£%0.2fatrisk|%smarketStatus\n",
268  
269 #4
270 "%-41sinstrumentName %screatedDateUTC %+6.2fsize %-9.2flevel ".
271 "%-9.2fbid £%-8.2fprofit %5.1fprofitpc%% £%10.2fatrisk\n",
272  
273 #5
274 #"%-41sinstrumentName %6sheld %-6.2fdailyp %+4.2fsize %-9.2flevel %-41sinstrumentName %screatedDateUTC %+6.2fsize %-9.2flevel\n",
275 "%-41sinstrumentName %8sheld %-6.2fdailyp %+4.2fsize %-9.2flevel %screatedDateUTC ".
276 "£%-7.2fprofit %8.1fprofitpc%% £%9.2fatrisk\n",
277 ,
278
279 );
280 my $format;
281  
282 if (defined($opt{f}))
283 {
284 if ($opt{f}=~m/^[0-9]+$/)
285 {
286 die "option fn out of range (0..".(@format+0).")" if ($opt{f}<1 || $opt{f}>@format+0);
287 $format=$format[$opt{f}-1];
288 if ($opt{f}>1)
289 {
290 $ig->uds('');
291 }
292 }
293 else
294 {
295 $format=$opt{f}."\n";
296 }
297 }
298 else
299 {
300 $format=$format[0]; # default value.
301 }
302  
303 $opt{F} and print $format and exit;
304 # printf "%d Positions\n",@$p+0 if (!$opt{S});
305  
306 my $count=0;
307 if (!$opt{S})
308 {
309 for my $position (@$p)
310 {
311 if ((!$opt{n} or $position->{instrumentName}=~m/$opt{n}/i) and
312 (!$opt{O} or datecmp($position->{createdDateUTC},$opt{O},$maskint,$gel)) and
313 ($opt{g}!~m/t/ or $position->{marketStatus} eq 'TRADEABLE') and
314 ($opt{g}!~m/n/ or $position->{marketStatus} ne 'TRADEABLE') and # not tradeable
315 (!defined $opt{v} or expression($opt{v},$position)) and
316 1
317 )
318 {
319 $count++;
320 }
321 }
322 if (@$p==$count)
323 {
324 printf "%d Positions\n",$count;
325 }
326 else
327 {
328 printf "%d of %d Positions\n",$count,0+@$p;
329 }
330 }
331  
332  
333 my $titles=undef;
334  
335 my $value=0;
336 my $profit=0;
337 $count=0;
338  
339 for my $position (@$p)
340 {
341 # $ig-> printpos($out,$position,$format,-0.5,+0.5);
342 $position->{rank}=$count+1;
343 if ((!$opt{n} or $position->{instrumentName}=~m/$opt{n}/i) and
344 (!$opt{O} or datecmp($position->{createdDateUTC},$opt{O},$maskint,$gel)) and
345 ($opt{g}!~m/t/ or $position->{marketStatus} eq 'TRADEABLE') and
346 ($opt{g}!~m/n/ or $position->{marketStatus} ne 'TRADEABLE') and # not tradeable
347 (!defined $opt{v} or expression($opt{v},$position)) and
348 1
349 )
350 {
351 if (!$opt{N} and ($count==0 or ( $opt{t} and ($count+1)%10==0)))
352 {
353 $ig->printpos($out , $titles, $format);
354 }
355 $count++;
356 $ig-> printpos($out,$position,$format);
357 }
358  
359 $value+=$position->{bid}*$position->{size};
360 $profit+=$position->{profit};
361 }
362  
363 print $out "Rank " if ($opt{r});
364 $ig->printpos($out , $titles, $format) if (!$opt{N});
365  
366 my $accounts=$ig->accounts();
367 # my ($account)=grep { $_->{accountId} eq "..." } @$accounts;
368 my ($account)=grep { $_->{accountType} eq "SPREADBET" } @$accounts;
369  
370 my $balance=$account->{balance}->{balance};
371 my $margin=$account->{balance}->{balance}+$account->{balance}->{profitLoss}-$account->{balance}->{available};
372 my $available=$account->{balance}->{available};
373  
374 my $pc;
375 $pc=int(1000*($profit+$balance-$capital)/$capital)/10 if ($capital);
376 my $ppc=int(1000*$profit/$value)/10;
377 my $equity=sprintf("%0.2f",$balance+$profit);
378 if (!$opt{S})
379 {
380 print "# Total value £$value balance=£$balance equity=£$equity profit on open trades=£$profit as % of value $ppc% ";
381 print "capital=£$capital " if ($capital);
382 print "margin/av=£$margin/£$available ";
383 print "profit/capital=$pc%"if ($capital);
384 print "\n";
385 }
386  
387 sub datecmp
388 {
389 my ($t1,$t2,$maskint,$gel)=@_;
390  
391 my @f=qw(%Y %m %d T%H %M %S);
392 @f=@f[0..$maskint-1];
393 my $f=join(':',@f);
394 $f=~s/:/-/ for 1 .. 2;
395 $f=~s/://;
396
397 my $warning;
398 {
399 local $SIG{__WARN__} = sub {$warning = shift};
400 $t1=Time::Piece->strptime($t1,$f) if (ref($t1) ne 'Time::Piece');
401 $t2=Time::Piece->strptime($t2,$f) if (ref($t2) ne 'Time::Piece');
402 }
403 return $t1==$t2 if ($gel==0);
404 return $t1<=$t2 if ($gel==-1);
405 return $t1>=$t2; # if ($gel==1);
406 }
407 sub expression
408 {
409 my ($expr,$position)=@_;
410 my $eval;
411  
412 # the expression consists of lines like
413 # $held>100 and $dailyp>0.1
414 # the evaluated value is returned by the function
415 # is important to substitute variables longest first so profitpc is done before profit
416 for my $key (sort { length($b) <=> length($a) } keys %$position)
417 {
418 my $x=$position->{$key};
419 if (defined($x))
420 {
421 $x=~s/[%£]//g;
422 $x=~s/ av// if ($key eq 'dailyp');
423 $expr=~s/\$$key/$x/g;
424 }
425 else
426 {
427 $expr=~s/\$$key/undef/g;
428 }
429 }
430 $eval=eval $expr ;
431 # print "$position->{instrumentName} => $eval\n";
432 return $eval ;
433 }
434 sub help
435 { my ($mess)=@_;
436 # -o auto-generate a time based file and use this to send output to
437 # t display headers every 10 lines
438 # n no headers
439 # f n : use format number
440 # h help
441 # g grep
442 # s print NO summary line
443  
444 my $name=$0;
445 $name=~s#^.*/([^/]+)$#$1#;
446 print "$mess\n" if (defined $mess and length($mess)>1);
447 print "$name Version $VERSION\n";
448 print "
449 This program is both an example of usage and a practical utility in its own right.
450  
451 It will print out your spreadbet positions in IG in various ways using your
452 username, password and apikey. These can be supplied in a cedentials.pl file in the script directory
453 or 1 or 2 directories up or the current directory. Or you can set
454 the environment variables IGPASS, IGUSER, IGAPIKEY.
455  
456 The default display is decending order of percent profit. Various formats are possible.
457 -a n aggregate 1 (default) , nonaggregate 0 = show individual holdings
458 -e explain where credentials for login are coming from, then exit.
459 -o Send output to an autogenerated, time based file.
460 -f n use one of the inbuilt formats 1 to 5. Or provide the format to use.
461 -F print the current format and exit .
462 -h this message and exit
463 -n xxx use xxx as a pattern in name to grep for particular positions. Can use | for or. (Must be quoted)
464 multipl -n allowed.
465 -S print no summary line.
466 -N toggle printing of headers.
467 -t print title lines every 10 lines.
468 -s x Sort output by x where x is a comma seperated list of fields
469 optionaly preceded by a minus (for reverse sort). Common fields
470 can be abrievated by the following single letter abbreviations,
471 n instrumentName
472 o level (opening price for position)
473 b bid
474 v atRisk (value atRisk in a position)
475 p profitpe (percentage profit. )
476 The default could be written in any of the following ways:
477 -s-profitpc,instrumentName or -s-pn or -s-p,n
478 It sorts by decending order of profit and where this is the
479 same, orders by name. Case is significant.
480 -O [+-=]date[time] Show only positions held Opened later or equal (+) equal to (-)
481 or earlier or equal (-) than the given date or datetime, eg
482 -O 2020/11/05 or -O 2020/11/05T15:00:00
483 Equal to means with ref to the format so that
484 2020/11/05 means the days are equal while 2020/11 means amy time that month
485 -g x print only tradeable (x=t) or non-tradable (x=n) positions
486 -v exp Evaluate expression and print if true. Example expressions (format id perl format)
487 '\$dailyp> 0.1 and \$held>100' means daily profit more than 0.1% and held for more than 100 days
488 Any variable (full list below) can be used
489 ";
490 exit 1 if (defined $mess and length($mess)>1);
491 print "\n A complete list of fields in a position is as follows. Some of these
492 are IG things, and some are calculated:
493  
494 bid
495 contractSize
496 controlledRisk
497 createdDate
498 createdDateUTC
499 currency
500 dailyp profit in % per day averaged over holding time
501 dealId
502 dealReference
503 delayTime
504 direction
505 epic
506 expiry
507 held days held
508 high
509 instrumentName
510 instrumentType
511 limitedRiskPremium
512 limitLevel
513 lotSize
514 low
515 marketStatus
516 netChange
517 offer
518 percentageChange
519 profit
520 scalingFactor
521 size
522 stopLevel
523 streamingPricesAvailable
524 rank calculated, first row is 1, 2 etc.
525 trailingStep
526 trailingStopDistance
527 updateTime
528 updateTimeUTC
529 ";
530 exit(1);
531 }