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