lib/Finance/IG.pm

filter: Statementstmt 88.2% 15 / 17 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.3% 21 / 23 CC 1 SCAR 0.5
CC
1
Cov
88%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Finance/IG.pm ↑ Summary
1 package Finance::IG;
2  
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 =encoding utf8
9 =head1 NAME
10  
11 Finance::IG - - Module for doing useful stuff with IG Markets REST API.
12  
13 This is very much a first draft, but will enable you to get simple arrays of positions, print them out possily some simple trading.
14  
15 Its proof of concept in perl beyond anything else, extend it as you need to.
16  
17 I have only used it for spreadbet accounts, it would be simple to extend to CFD's but I dont have CFD data or an interest in CFD's so have not done this.
18  
19 You will need an API key to use this module, available free from IG Markets.
20  
21 =head1 VERSION
22  
23 Version 0.01
24  
25 =cut
26  
27 our $VERSION = '0.02';
28  
29  
30 =head1 SYNOPSIS
31  
32 use Finance::IG;
33 use strict;
34 no strict 'refs';
35 use warnings;
36  
37 my $ig=iFinance::IG->new(
38 username=> "demome",
39 password=> "mypassword",
40 apikey=> "4398232394029341776153276512736icab",
41 isdemo=>0,
42 );
43 $ig->login;
44
45 my $p=$ig->positions(); # Get a list of positions
46 $p=$ig->agg($p,$sortlist); # Aggregate them, so one item per instrument.
47  
48 my $format="%-41sinstrumentName %+6.2fsize %-9.2flevel ".
49 "%-9.2fbid £%-8.2fprofit %5.1fprofitpc%% £%10.2fatrisk\n",
50  
51 $ig->printpos("stdout" , [], $format);
52  
53 for my $position (@$p)
54 {
55 $ig-> printpos("stdout" ,$position,$format);
56 }
57  
58 =head1 SUBROUTINES/METHODS
59  
60 This is a list of currently implemented methods
61  
62 =head2 new
63
64 Normal parameters, as above.
65  
66 col=>1
67  
68 Causes Finance::IG to try to use Term::Chrome to do some simple coloration of output.
69 If Term::Chrome is not installed, it will be silently ignored. See printpos.
70  
71 =head2 login, needs to be called once after new and before other calls.
72  
73 No Parameters.
74  
75 =head2 printpos print out a formatted hash as one line
76  
77 Parameters
78
79 file - can be a file handle or the string stdout or the glob *STDOUT
80 A position of other shallow hash,
81 A format string. The format string is similar to a printf format string, for example %s says print out a string
82 however, the name of the item to be printed follows the letter, eg %sinstrumentName print the string instrument name.
83 optional up
84 optional down
85  
86 A title line can be printed by either passing an array ref instead of a position, in which case the array ref can contain
87 the titles to print. If the array is empty then the titles will be generated from the format string.
88  
89 up and down can be provided and represent negative and posite limits on dbid element by default.
90 Alternatively, provide up only and make it a subroutine ref.
91  
92 The subroutime takes parameter a position, and should return escape characters (from Term::Chrome to colorise the line.
93  
94 =head2 transactions - retrieve transactions history
95  
96 transactions(++$page,Time::Piece->strptime("2020-01-01","%Y-%m-%d-%H.%M"),scalar localtime)
97  
98 Parameters
99  
100 Paging number, start at 1
101 Start time, can be a string or a Time::Piece
102 Endtime
103  
104 return a reference to an array of transactions for that time span. Each transaction is a hash of data.
105  
106 =cut
107  
108 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
109 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=2.6
110 use REST::Client;
111 use Data::Dump qw(dump);
112 use Scalar::Util;
113 use Time::Piece;
114  
115 BEGIN {
116 if (eval("require Term::Chrome"))
117 {
118 Term::Chrome->import();
119 }
120 else
121 {
122 map { eval ("sub $_ {}") } qw(Red Blue Bold Reset Underline Green color); # need these to avoid compile time errors.
123 }
124 }
125 has 'apikey' => (
126 is=>'ro',
127 isa=>'Str',
128 required=>1,
129 );
130 has 'username' => (
131 is=>'ro',
132 isa=>'Str',
133 required=>1,
134 );
135 has 'password' => (
136 is=>'ro',
137 isa=>'Str',
138 required=>1,
139 );
140 has 'isdemo' => (
141 is=>'ro',
142 isa=>'Bool',
143 required=>1,
144 );
145 has 'CST' => (
146 is=>'rw',
147 isa=>'Str',
148 );
149 has 'XSECURITYTOKEN' => (
150 is=>'rw',
151 isa=>'Str',
152 );
153  
154 has 'XSTTIME' => (
155 is=>'rw',
156 isa=>'Int',
157 );
158 has 'col' => ( # set to 1 to use Term::Chrome for coloration.
159 is=>'rw',
160 isa=>'Bool',
161 default=>0,
162 );
163 has 'uds' => (
164 is=>'rw',
165 isa=>'Str',
166 default=>'',
167 );
168  
169 sub _url
170 {
171 my ($self) = @_;
172 return 'https://demo-api.ig.com/gateway/deal' if ( $self->isdemo);
173 return 'https://api.ig.com/gateway/deal';
174 }
175  
176  
177 ##########################################################################
178 =head2 login - loginto the account.
179  
180 Parameters - none
181  
182 login to the object, using the parameters provided to new.
183  
184 You should call this just once per object after calling new.
185  
186 =cut
187 ##########################################################################
188 sub login {
189 my ($self) = @_;
190 my $headers =
191 {
192 'Content-Type' => 'application/json; charset=UTF-8',
193 'Accept' => 'application/json; charset=UTF-8',
194 VERSION => 2,
195 'X-IG-API-KEY'=> $self->apikey
196 };
197 my $data = {
198 identifier => $self->username,
199 password => $self->password,
200 };
201 # my $jdata = encode_json($data);
202 my $jdata=JSON->new->canonical->encode($data);
203  
204 my $client = REST::Client->new();
205 $client->setHost($self->_url);
206  
207  
208 $client->POST (
209 '/session',
210 $jdata,
211 $headers
212 );
213 my $code=$client->responseCode();
214 die "response code from login $code" if ($code!=200);
215 $self->CST($client->responseHeader('CST') // die "No CST header in login response");
216 $self->XSECURITYTOKEN($client->responseHeader('X-SECURITY-TOKEN') // die "No X-SECURITY-TOKEN in login response header");
217 $self->XSTTIME(time());
218 return;
219 }
220 ##########################################################################
221  
222 =head2 flatten
223  
224 Parameters
225 1 Ref to array of hashes to flatten or a ref to a hash to flatten
226 2 ref to an array of items to flatten, or just a single item name.
227  
228 Typical use of this is for a position that as it comes back from IG contains a market and a position
229 byut we would prefer all items at the top level. This would moves all the keys of position and market up one level and
230 would remove the keys market and position.
231  
232 $self->flatten($hash, [qw(market position)]);
233  
234 =cut
235 ##########################################################################
236 sub flatten
237 {
238 my ($self)=shift;
239 my ($hash)=shift;
240 my ($toflatten)=shift;
241  
242 $hash=[$hash] if (ref($hash) ne 'ARRAY');
243 $toflatten=[$toflatten] if (ref($toflatten) ne 'ARRAY');
244  
245 for my $h (@$hash)
246 {
247 for my $key (@$toflatten)
248 {
249 if (exists($h->{$key}))
250 {
251 if (defined($h->{$key}))
252 {
253 die "key $key to flatten is not a hash" if (ref($h->{$key}) ne 'HASH');
254 for my $subkey (keys %{$h->{$key}})
255 {
256 die "subkey exists $subkey" if (exists($h->{$subkey}));
257 $h->{$subkey}=$h->{$key}->{$subkey};
258 }
259 }
260 delete $h->{$key};
261 }
262 }
263 }
264 }
265 sub transactions
266 {
267  
268 my ($self) = shift;
269 my ($pageNumber)=shift;
270 my ($from) =shift;
271 my ($to)=shift;
272  
273 my $pageSize=50;
274  
275 $from//='';
276 $to//='';
277  
278 if (ref($to) eq 'Time::Piece')
279 {
280 $to=$to->strftime("%Y-%m-%dT%H:%M:%S");
281 }
282 if (ref($from) eq 'Time::Piece')
283 {
284 $from=$from->strftime("%Y-%m-%dT%H:%M:%S");
285 }
286 $to=~m/^[-0-9T:]*$/ or die "Invalid date format for 'to' $to, is a ".ref(\$to);
287 $from=~m/^[-0-9T:]*$/ or die "Invalid date format for 'from' $from";
288  
289 my $headers = {
290 'Content-Type' => 'application/json; charset=UTF-8',
291 'Accept' => 'application/json; charset=UTF-8',
292 VERSION => 2,
293 CST=>$self->CST,
294 'X-SECURITY-TOKEN'=> $self->XSECURITYTOKEN,
295 'X-IG-API-KEY'=> $self->apikey,
296 };
297 #my $jheaders = encode_json($headers);
298 my $jheaders=JSON->new->canonical->encode($headers);
299  
300 my $client = REST::Client->new();
301 $client->setHost($self->_url);
302  
303 $from and $from="from=$from";
304 $to and $to="to=$to";
305 my $rpage=$pageNumber; # requested page number as integer, 1 is first
306 $pageNumber and $pageNumber="pageNumber=$pageNumber";
307 $pageSize and $pageSize="pageSize=$pageSize";
308  
309 my $url=join '', map { $_?'&'.$_:'' } ($from,$to,$pageNumber,$pageSize);
310 $url=~s/^&//;
311 $url='?'.$url if ($url);
312  
313 $url='/history/transactions'.$url;
314 $client->GET (
315 $url,
316 $headers
317 );
318  
319 my $code=$client->responseCode();
320 if ($code==200)
321 {
322 my $resp=decode_json($client->responseContent());
323 # $resp=$self->flatten($resp,[qw/transactions metadata/]);
324 #die encode_json($resp);
325  
326 my @activities=@{$resp->{transactions}};
327 # pncerint encode_json( $resp->{metadata} );
328 # {"pageData":{"totalPages":11,"pageNumber":11,"pageSize":50},"size":534}***** 34
329 return undef if ($rpage > $resp->{metadata}->{pageData}->{pageNumber});
330 # return undef if (@activities==0);
331 return \@activities;
332 }
333 else
334 {
335 print "failed $code: ".$client->responseContent()."\n";
336 return undef;
337 }
338 }
339  
340 # example from/ to sting format:
341 # 2020-10-28
342 # 2020-10-28T15:30
343  
344 # keys in retirn, when called with detailed=1
345 # type, goodTillDate, actions(ARRAY) , epic, direction, level, channel, marketName, date, dealReference, guaranteedStop, stopLevel, size, currency, stopDistance, trailingStep, status, trailingStopDistance, limitLevel, description, dealId, period, limitDistance
346 # without:
347 # period, details, date, dealId, epic, description, channel, status, type
348  
349 sub history
350 {
351 my ($self) = shift;
352 my ($detailed)=shift; ## undef, not detailed, 1 for detailed.
353 my ($pageNumber)=shift;
354  
355  
356 my ($from) = shift;
357 my ($to) = shift;
358  
359 $pageNumber//='';
360 my $pageSize=50;
361  
362 $from//='';
363 $to//='';
364  
365 if (ref($to) eq 'Time::Piece')
366 {
367 $to=$to->strftime("%Y-%m-%dT%H:%M:%S");
368 }
369 if (ref($from) eq 'Time::Piece')
370 {
371 $from=$from->strftime("%Y-%m-%dT%H:%M:%S");
372 }
373  
374 $to=~m/^[-0-9T:]*$/ or die "Invalid date format for 'to' $to";
375 $from=~m/^[-0-9T:]*$/ or die "Invalid date format for 'from' $from";
376  
377 my $headers = {
378 'Content-Type' => 'application/json; charset=UTF-8',
379 'Accept' => 'application/json; charset=UTF-8',
380 VERSION => 2,
381 CST=>$self->CST,
382 'X-SECURITY-TOKEN'=> $self->XSECURITYTOKEN,
383 'X-IG-API-KEY'=> $self->apikey,
384 };
385 #my $jheaders = encode_json($headers);
386 my $jheaders=JSON->new->canonical->encode($headers);
387  
388 my $client = REST::Client->new();
389 $client->setHost($self->_url);
390 $from="from=$from" if ($from ne '');
391 $to="to=$to" if ($to ne '');
392 if ($detailed)
393 {
394 $detailed="detailed=true"
395 }
396 else
397 {
398 $detailed='';
399 }
400  
401 $pageNumber="pageNumber=$pageNumber" if ($pageNumber);
402 $pageSize//='';
403 $pageSize="pageSize=$pageSize" if ($pageSize);
404  
405 # my $sep='?';
406 # map { $_ eq '' or $_=$sep.$_ and $sep='&'} ($from,$to,$detailed,$pageNumber,$pageSize);
407  
408 my $url=join '', map { $_?'&'.$_:'' } ($from,$to,$detailed,$pageNumber,$pageSize);
409 $url=~s/^&//;
410 $url='?'.$url if ($url);
411  
412 $url='/history/activity'.$url;
413  
414 # die $url;
415  
416 $client->GET (
417 $url,
418 $headers
419 );
420  
421 my $code=$client->responseCode();
422  
423 if ($code==200)
424 {
425 my $resp=decode_json($client->responseContent());
426 my @activities=@{$resp->{activities}};
427 return undef if (@activities==0);
428 $self->flatten(\@activities,'details');
429 return \@activities;
430 }
431 else
432 {
433 print "failed $code: ".$client->responseContent()."\n";
434 return undef;
435 }
436 }
437 # example response:
438 #{"metadata":{"paging":{"size":50,"next":"/history/activity?version=3&from=2020-10-28T00:00:00&to=2020-10-29T16:41:45&detailed=false&pageSize=50"}}
439 # "activities": [.... ]
440 # }
441 # each activity looks like:
442 #{
443 # details=>null,
444 # dealId=>"DIAAAAFRS39HJAK",
445 # period=>"DFB",
446 # type=>"POSITION",
447 # epic=>"UA.D.ATVI.DAILY.IP",
448 # description=>"Position partially closed=> J6GK8WA9",
449 # date=>"2020-10-29T17:47:46",
450 # status=>"ACCEPTED",
451 # channel=>"SYSTEM"
452 #
453 # or with detail
454 # {"activities":
455 # [
456 # [
457 # {"date":"2020-11-19T18:41:04",
458 # "epic":"UC.D.MU.DAILY.IP",
459 # "period":"DFB",
460 # "dealId":"DIAAAAFVXZV5LA5",
461 # "channel":"WEB",
462 # "type":"POSITION",
463 # "status":"ACCEPTED",
464 # "description":"Position opened: VXZV5LA5",
465 # "details":
466 # {
467 # "dealReference":"6XQESB1EQGWY4FR2",
468 # "actions":
469 # [
470 # {"actionType":"POSITION_OPENED",
471 # "affectedDealId":"DIAAAAFVXZV5LA5"
472 # }
473 # ],
474 # "marketName":"Micron Technology Inc (All Sessions)",
475 # "goodTillDate":null,
476 # "currency":"GBP",
477 # "size":0.4,
478 # "direction":"BUY",
479 # "level":6123,
480 # "stopLevel":null,
481 # "stopDistance":null,
482 # "guaranteedStop":false,
483 # "trailingStopDistance":null,
484 # "trailingStep":null,
485 # "limitLevel":null,
486 # "limitDistance":null
487 # }
488 # },
489 # {"date":"2020-11-17T11:33:52",
490 #"epic":"KA.D.FSTA.DAILY.IP",
491 #"period":"DFB",
492 #"dealId":"DIAAAAFVEFD4GAG",
493 #"channel":"WEB",
494 #"type":"POSITION",
495 #"status":"ACCEPTED",
496 #"description":"Position/s closed: HH93GXAZ",
497 #"details":{"dealReference":"6XQESB1EQAZNR6V3",
498 #"actions":[{"actionType":"POSITION_CLOSED",
499 #"affectedDealId":"DIAAAAFHH93GXAZ"}],
500 #"marketName":"Fuller Smith & Turner",
501 #"goodTillDate":null,
502 #"currency":"GBP",
503 #"size":1,
504 #"direction":"SELL",
505 #"level":726.2,
506 #"stopLevel":null,
507 #"stopDistance":null,
508 #"guaranteedStop":false,
509 #"trailingStopDistance":null,
510 #"trailingStep":null,
511 #"limitLevel":null,
512 #"limitDistance":null}},
513 #}
514  
515 # with detailed=1
516  
517 #{
518 # "activities": [
519 # {
520 # "date": "2020-11-19T18:41:04",
521 # "epic": "UC.D.MU.DAILY.IP",
522 # "period": "DFB",
523 # "dealId": "DIAAAAFVXZV5LA5",
524 # "channel": "WEB",
525 # "type": "POSITION",
526 # "status": "ACCEPTED",
527 # "description": "Position opened: VXZV5LA5",
528 # "details": {
529 # "dealReference": "6XQESB1EQGWY4FR2",
530 # "actions": [
531 # {
532 # "actionType": "POSITION_OPENED",
533 # "affectedDealId": "DIAAAAFVXZV5LA5"
534 # }
535 # ],
536 # "marketName": "Micron Technology Inc (All Sessions)",
537 # "goodTillDate": null,
538 # "currency": "GBP",
539 # "size": 0.4,
540 # "direction": "BUY",
541 # "level": 6123,
542 # "stopLevel": null,
543 # "stopDistance": null,
544 # "guaranteedStop": false,
545 # "trailingStopDistance": null,
546 # "trailingStep": null,
547 # "limitLevel": null,
548 # "limitDistance": null
549 # }
550 # },
551 # {
552 # "date": "2020-11-17T11:33:52",
553 # "epic": "KA.D.FSTA.DAILY.IP",
554 # "period": "DFB",
555 # "dealId": "DIAAAAFVEFD4GAG",
556 # "channel": "WEB",
557 # "type": "POSITION",
558 # "status": "ACCEPTED",
559 # "description": "Position/s closed: HH93GXAZ",
560 # "details": {
561 # "dealReference": "6XQESB1EQAZNR6V3",
562 # "actions": [
563 # {
564 # "actionType": "POSITION_CLOSED",
565 # "affectedDealId": "DIAAAAFHH93GXAZ"
566 # }
567 # ],
568 # "marketName": "Fuller Smith & Turner",
569 # "goodTillDate": null,
570 # "currency": "GBP",
571 # "size": 1,
572 # "direction": "SELL",
573 # "level": 726.2,
574 # "stopLevel": null,
575 # "stopDistance": null,
576 # "guaranteedStop": false,
577 # "trailingStopDistance": null,
578 # "trailingStep": null,
579 # "limitLevel": null,
580 # "limitDistance": null
581 # }
582 # },
583 # {
584 # "date": "2020-11-17T11:33:09",
585 # "epic": "KA.D.FSTA.DAILY.IP",
586 # "period": "DFB",
587 # "dealId": "DIAAAAFVEFBBKA4",
588 # "channel": "WEB",
589 # "type": "POSITION",
590 # "status": "ACCEPTED",
591 # "description": "Position opened: VEFBBKA4",
592 # "details": {
593 # "dealReference": "6XQESB1EQAZKR1V2",
594 # "actions": [
595 # {
596 # "actionType": "POSITION_OPENED",
597 # "affectedDealId": "DIAAAAFVEFBBKA4"
598 # }
599 # ],
600 # "marketName": "Fuller Smith & Turner",
601 # "goodTillDate": null,
602 # "currency": "GBP",
603 # "size": 2,
604 # "direction": "BUY",
605 # "level": 779.9,
606 # "stopLevel": null,
607 # "stopDistance": null,
608 # "guaranteedStop": false,
609 # "trailingStopDistance": null,
610 # "trailingStep": null,
611 # "limitLevel": null,
612 # "limitDistance": null
613 # }
614 # },
615 # {
616 # "date": "2020-11-16T17:17:29",
617 # "epic": "UD.D.WIXUS.DAILY.IP",
618 # "period": "DFB",
619 # "dealId": "DIAAAAFU94TQRAR",
620 # "channel": "WEB",
621 # "type": "POSITION",
622 # "status": "ACCEPTED",
623 # "description": "Position opened: U94TQRAR",
624 # "details": {
625 # "dealReference": "6XQESB1EQ90XNSR2",
626 # "actions": [
627 # {
628 # "actionType": "POSITION_OPENED",
629 # "affectedDealId": "DIAAAAFU94TQRAR"
630 # }
631 # ],
632 # "marketName": "Wix.com Ltd",
633 # "goodTillDate": null,
634 # "currency": "GBP",
635 # "size": 0.31,
636 # "direction": "BUY",
637 # "level": 24142,
638 # "stopLevel": null,
639 # "stopDistance": null,
640 # "guaranteedStop": false,
641 # "trailingStopDistance": null,
642 # "trailingStep": null,
643 # "limitLevel": null,
644 # "limitDistance": null
645 # }
646 # },
647 # {
648 # "date": "2020-11-16T17:08:33",
649 # "epic": "UD.D.ZMUS.DAILY.IP",
650 # "period": "DFB",
651 # "dealId": "DIAAAAFU924B7A3",
652 # etc....
653 ##########################################################################
654 #
655  
656 =head2 accounts - retrieve a list of accounts
657  
658 Parameters - none
659  
660 Return value - Array ref containing hashes of accounts.
661  
662 =cut
663 ##########################################################################
664 sub accounts
665 {
666 my ($self) = shift;
667  
668 my $headers = {
669 'Content-Type' => 'application/json; charset=UTF-8',
670 'Accept' => 'application/json; charset=UTF-8',
671 VERSION => 1,
672 CST=>$self->CST,
673 'X-SECURITY-TOKEN'=> $self->XSECURITYTOKEN,
674 'X-IG-API-KEY'=> $self->apikey,
675 };
676 #my $jheaders = encode_json($headers);
677 my $jheaders=JSON->new->canonical->encode($headers);
678  
679 my $client = REST::Client->new();
680 $client->setHost($self->_url);
681 my $r=$client->GET ( '/accounts', $headers);
682  
683 my $resp=decode_json($client->responseContent());
684  
685 my $accounts=[];
686 @$accounts=@{$resp->{accounts}};
687  
688 return $accounts;
689  
690 }
691  
692 # Typical return data:
693 #[
694 # {"accountId":"...",
695 # "status":"ENABLED",
696 # "canTransferFrom":true,
697 # "preferred":true,
698 # "accountAlias":null,
699 # "accountType":"SPREADBET",
700 # "accountName":"Spread bet",
701 # "balance":{
702 # "deposit":89051.36,
703 # "balance":152475.8,
704 # "available":85942.65,
705 # "profitLoss":22518.21
706 # },
707 # "canTransferTo":true,
708 # "currency":"GBP"
709 # },
710 # {"accountId":"...",
711 # "status":"ENABLED",
712 # "canTransferFrom":true,
713 # "preferred":false,
714 # "accountAlias":null,
715 # "accountType":"CFD",
716 # "accountName":"CFD",
717 # "balance":{
718 # "available":0,
719 # "profitLoss":0,
720 # "balance":0,
721 # "deposit":0
722 # },
723 # "canTransferTo":true,
724 # "currency":"GBP"
725 # }
726 #]
727 ##########################################################################
728 #
729 # Return a ref to an array of positions. Each position is
730 # a variable structure deep hash
731 #
732 ##########################################################################
733 sub positions
734 {
735 my ($self) = shift;
736  
737 my $headers = {
738 'Content-Type' => 'application/json; charset=UTF-8',
739 'Accept' => 'application/json; charset=UTF-8',
740 VERSION => 2,
741 # 'IG-ACCOUNT-ID'=> $accountid,
742 CST=>$self->CST,
743 'X-SECURITY-TOKEN'=> $self->XSECURITYTOKEN,
744 'X-IG-API-KEY'=> $self->apikey,
745 };
746 #my $jheaders = encode_json($headers);
747 my $jheaders=JSON->new->canonical->encode($headers);
748  
749 # my $data = {
750 # encryptedPassword => "false",
751 # identifier => $self->username,
752 # password => $self->password
753 # };
754 my $client = REST::Client->new();
755 $client->setHost($self->_url);
756 #my $r;
757 # $headers->{VERSION}=2;
758 #$r=$client->GET (
759 $client->GET ( '/positions',
760 $headers
761 );
762 my $resp=decode_json($client->responseContent());
763  
764 my $positions=[];
765 @$positions=@{$resp->{positions}};
766  
767 return $positions;
768 }
769 # example of the structure of a position
770 # Regeneron Pharmaceuticals Inc, 0.06
771 # {
772 # "position" : {
773 # "trailingStopDistance" : null,
774 # "size" : 0.06,
775 # "limitedRiskPremium" : null,
776 # "stopLevel" : 50128,
777 # "direction" : "BUY",
778 # "level" : 50303,
779 # "dealReference" : "6XQESB1E506WW334",
780 # "controlledRisk" : false,
781 # "currency" : "GBP",
782 # "contractSize" : 1,
783 # "createdDateUTC" : "2020-04-03T14:26:07",
784 # "trailingStep" : null,
785 # "createdDate" : "2020/04/03 15:26:07:000",
786 # "limitLevel" : null,
787 # "dealId" : "DIAAAAEL2T7AEAS"
788 # },
789 # "market" : {
790 # "lotSize" : 1,
791 # "marketStatus" : "EDITS_ONLY",
792 # "instrumentType" : "SHARES",
793 # "expiry" : "DFB",
794 # "streamingPricesAvailable" : false,
795 # "instrumentName" : "Regeneron Pharmaceuticals Inc",
796 # "offer" : 60261,
797 # "delayTime" : 0,
798 # "updateTime" : "20:59:56",
799 # "high" : 61455,
800 # "percentageChange" : -2.01,
801 # "netChange" : -1236,
802 # "low" : 59886,
803 # "bid" : 60261,
804 # "updateTimeUTC" : "19:59:56",
805 # "scalingFactor" : 1,
806 # "epic" : "UC.D.REGN.DAILY.IP"
807 # }
808 # }
809 #####################################################################
810 # Aggregate an array of positions into an array of unique
811 # positions with 1 element per instrument, Items will be combined
812 # where more than one position is combined, in a field dependent way.
813 # for exeample sizes will be added as will be profit
814 # a reference to an array is expected and a reference to a new array
815 # returned.
816 #####################################################################
817  
818 =head2 agg - aggregate positions into a flattened 1 element per instrument form.
819  
820 Parameters
821  
822 1 Reference to an array of positions
823 2 (Optional) Ref to an array of keys to sort on
824  
825 agg does three things actually. First, it joins together multiple positions of the same instrument,
826 generating sensible values for things like profit/loss and size
827  
828 Second, it performs some flattening of the deep structure for a position which comes from IG.
829  
830 Third it sorts the result. The default sort order I use is -profitpc instrumentName, but
831 you can provide a 2rd parameter, a reference to an array of items to sort by.
832 Each item can optionally be preceeded by - to reverse the prder. If the first item equates equal, then
833 the next item is used.
834  
835 =cut
836 #####################################################################
837 sub agg
838 {
839 my ($self,$positions,$sortlist)=@_;
840 my %totals; # aggregated totals as arrays of individuals.
841  
842 for my $position (@$positions)
843 {
844  
845 my $json = JSON->new;
846  
847 $position->{profit}=($self->fetch($position,'bid')-$self->fetch($position,'level'))*$self->fetch($position,'size');
848 # create new profits element
849  
850 my $ra=($totals{$self->fetch($position,'instrumentName')}||=[]);
851 push(@$ra,$position);
852 }
853  
854 # totals is a hash on instrument name each element is a pointer to an array of positions for the same instrument.
855  
856 my $aggregated=[];
857 for my $total (values %totals)
858 { # for one particular name
859 my $position={}; # initialise the new aggregate position
860  
861 $position->{size}=0;
862 $position->{profit}=0;
863 # $position->{stopLevel}=[];
864 $position->{createdDate}='';
865 my $sl=[];
866 #for my $subtotal (sort {"$a->{createdDate}" cmp "$b->{createdDate}" } @$total) # go through all the positions for that one name
867 for my $subtotal ( @$total) # go through all the positions for that one name
868 {
869 $position->{instrumentName}//=$self->fetch($subtotal,'instrumentName');
870 $position->{size}+=$self->fetch($subtotal,'size');
871 $position->{bid}//=$self->fetch($subtotal,'bid');
872 $position->{profit}+=$self->fetch($subtotal,'profit');
873 $position->{epic}//=$self->fetch($subtotal,'epic');
874  
875 $position->{currency}//=$self->fetch($subtotal,'currency');
876 $position->{marketStatus}//=$self->fetch($subtotal,'marketStatus');
877  
878 #$sl=($position->{stopLevel}//=[]);
879  
880 @$sl=map {defined($_) } @$sl;
881 if (0==grep {$_==($self->fetch($subtotal,'stopLevel')//0) } @$sl)
882 # if (0==grep {$_==$self->fetch($subtotal,'stopLevel') } @$sl)
883 {
884 push(@$sl,$self->fetch($subtotal,'stopLevel'));
885 # print "pushing ".fetch($subtotal,'stopLevel')."\n";
886 }
887 #$position->{createdDate}.=$self->fetch($subtotal,'createdDate').",";
888 #$position->{createdDateUTC}.=$self->fetch($subtotal,'createdDateUTC').",";
889  
890 # if ($position->{createdDate})
891 # {
892 # $position->{createdDate}=~s/-.*$//;
893 # $position->{createdDate}.="-".$self->fetch($subtotal,'createdDate');
894 # }
895 # else
896 # {
897 # $position->{createdDate}=$self->fetch($subtotal,'createdDate');
898 # }
899 $position->{createdDateUTC}=$self->fetch($subtotal,'createdDateUTC');
900 $position->{createdDate}=$self->fetch($subtotal,'createdDate');
901 }
902 my $open=$position->{bid}-$position->{profit}/$position->{size};
903 $position->{level}=$open;
904 $position->{profitpc}=int(0.5+1000*$position->{profit}/($position->{level}*$position->{size}))/10;
905 $position->{atrisk}=$position->{bid}*$position->{size};
906 $position->{createdDateOnly}=$position->{createdDate};
907 $position->{createdDateOnly}=~s/ .*$//;
908 if (@$sl==0 || 1)
909 {
910 $position->{stopLevel}='';
911 $position->{slpc}='';
912 }
913 else
914 {
915 $position->{stopLevel}=join(',',map { $_//''} @$sl);
916 $position->{slpc}=join(',', map { $_?(int(1000.0*$_/$position->{bid})/10):''} @$sl);
917 }
918 push(@$aggregated,$position);
919 }
920  
921 # @$aggregated=sort { $b->{profitpc}<=>$a->{profitpc} } @$aggregated;
922 $sortlist//=[qw(-profitpc instrumentName)]; # default sort
923 $self->sorter($sortlist,$aggregated);
924 return $aggregated;
925  
926 }
927 # like agg, but do not do actual aggregation.
928 # so we sort, add certain extra characteristics but thats all.
929 ##########################################################################
930 #
931  
932 =head2 nonagg - like agg but do not do actual aggregation
933  
934 Parameters
935  
936 1 Reference to an array of positions
937 2 (Optional) Ref to an array of keys to sort on
938  
939 Return value - Array ref containing hashes of accounts. Should be the same size as the original.
940  
941 =cut
942 ##########################################################################
943 sub nonagg
944 {
945 my ($self,$positions,$sortlist)=@_;
946 my %totals; # aggregated totals as arrays of individuals.
947  
948 $self->flatten($positions, [qw/market position/]);
949 for my $position (@$positions)
950 {
951  
952 my $json = JSON->new;
953  
954 $position->{profit}=($self->fetch($position,'bid')-$self->fetch($position,'level'))*$self->fetch($position,'size');
955 # create new profits element
956  
957 my $open=$position->{bid}-$position->{profit}/$position->{size};
958 $position->{level}=$open;
959 $position->{profitpc}=int(0.5+1000*$position->{profit}/($position->{level}*$position->{size}))/10;
960 $position->{atrisk}=$position->{bid}*$position->{size};
961 $position->{createdDateOnly}=$position->{createdDate};
962 $position->{createdDateOnly}=~s/ .*$//;
963 }
964  
965 $sortlist//=[qw(-profitpc instrumentName)]; # default sort
966 $self->sorter($sortlist,$positions);
967 return $positions;
968 }
969 ####################################################################
970 # General array sort function.
971 # Given an array of hash refs, and a sort key
972 # considtying of an array of an array of keys to the hashes
973 # sort in place the array.
974 #
975 # sortkey, arrayref of keys. Sort order direction reversed
976 # if key has - appended to start, eg -profitpc gives largest first
977 # pos array eo be sorted, its an inplace sort.
978 # uses the determinant $x eq $x+0 to determine if numeric or not.
979 # improvements: may need to use a deep fetch to locate the items
980 ####################################################################
981  
982 =head2 sorter - general array sort function for an array of hashes
983  
984 Parameters
985  
986 1 Ref to array of keys to sort. Each my be prefixed with a - to
987 reverse the order on that key. If keys compare equal the next key is used.
988 2 Ref to an array of positions to sort.
989  
990 The array is sorted in-place. A numeric comparison is done if for
991 both items $x == $x+0
992  
993 Formatted datetimes are correctly sorted.
994  
995 =cut
996 ####################################################################
997 sub sorter
998 {
999 my ($self,$sortkey,$pos)=@_;
1000  
1001 @$pos= sort {
1002 my ($result)=0;
1003 for my $fkey (@$sortkey)
1004 {
1005 my $key=$fkey;
1006 my $dir=1;
1007 $dir=-1 if ($key=~s/^-//);
1008 # die "key=$key value=$b->{createdDateUTC} keys are ".join(', ',keys %$a); ;
1009 next if (!exists($a->{$key}) or !exists($b->{$key}));
1010 my ($x1,$x2)=($a->{$key},$b->{$key});
1011 map { s/[£%]//g } ($x1,$x2);
1012  
1013 { no warnings qw(numeric);
1014 my $warning;
1015  
1016 if ($x1 eq $x1+0 and $x2 eq $x2+0)
1017 {
1018 $result=$x1<=>$x2;
1019 }
1020 else
1021 { # note that this correctly handles a formatted date
1022 $result=$x1 cmp $x2;
1023 }
1024 }
1025 return $result*$dir if ($result);
1026 }
1027 return 0;
1028 }
1029 @$pos;
1030  
1031 }
1032 ####################################################################
1033 # The idea is this will close all the supplied positions, optionally returning a reference to
1034 # either/both an array of closed/non closed positions;
1035 # This is not quite working yet, needs more work,
1036 ####################################################################
1037  
1038 =head2 close - close the supplied positions.
1039  
1040  
1041  
1042 Parameters
1043  
1044 1 Ref to array of positions to close.
1045 reverse the order on that key.
1046 2/3 ref to done / notdone arrays to sort succesful / failed
1047 closes in to.
1048  
1049 The idea is this will close all the supplied positions, optionally returning a reference to
1050  
1051  
1052 =head3 Status - very experimental.
1053  
1054 Contains die / print statements that you may wish to remove
1055  
1056 =cut
1057 ####################################################################
1058 sub close
1059 {
1060 my $self=shift;
1061 my $positions=shift; # to close
1062 my $done=shift;
1063 my $notdone=shift;
1064  
1065 my $verbose=0;
1066  
1067 my @done;
1068 my @notdone;
1069  
1070 my $headers = {
1071 'Content-Type' => 'application/json; charset=UTF-8',
1072 'Accept' => 'application/json; charset=UTF-8',
1073 VERSION => 1,
1074 # 'IG-ACCOUNT-ID'=> $accountid,
1075 CST=>$self->CST,
1076 'X-SECURITY-TOKEN'=> $self->XSECURITYTOKEN,
1077 'X-IG-API-KEY'=> $self->apikey,
1078 '_method'=>'DELETE',
1079 };
1080  
1081 my $data = {
1082 #encryptedPassword => "false",
1083 #identifier => $self->username,
1084 #password => $self->password
1085 #direction => 'BUY',
1086 # epic=>
1087 # expiry=>
1088 orderType=>'MARKET',
1089 #size=>0.1
1090 ##guaranteedStop=>'false',
1091 forceOpen=>'true',
1092 #timeInForce => "EXECUTE_AND_ELIMINATE", # "GOOD_TILL_CANCELLED"
1093 timeInForce => "", # "GOOD_TILL_CANCELLED"
1094 };
1095 my $client = REST::Client->new();
1096  
1097 $client->setHost($self->_url);
1098  
1099  
1100 my %existhash;
1101 map { $existhash{$self->fetch($_,'epic')}=$_ } @$positions; # creat a hash on epic
1102  
1103 for my $position (@$positions)
1104 {
1105 # die dump($position);
1106  
1107 my $existingsize=0;
1108 my $epic=$self->fetch($position,'epic');
1109 my $name=$self->fetch($position,'instrumentName');
1110  
1111 my $ms=$self->fetch($position,'marketStatus');
1112  
1113 if ($ms ne 'TRADEABLE')
1114 {
1115 push(@notdone,$position);
1116 print "$name, market status is $ms\n";
1117 next;
1118 }
1119  
1120  
1121 #$data->{epic}=$self->fetch($position,'epic');
1122 $data->{epic}=$epic;
1123 $data->{size}=$self->fetch($position,'size');
1124 # $data->{currencyCode}=$self->fetch($position,'currency');
1125 $data->{expiry}='DFB';
1126 # $data->{expiry}='-';
1127 $data->{direction}='SELL';
1128  
1129 #my $jdata = encode_json($data);
1130 my $jdata=JSON->new->canonical->encode($data);
1131 $client->PUT (
1132 '/positions/otc',
1133 $jdata,
1134 $headers
1135 );
1136 my $code=$client->responseCode();
1137 if ($code==200)
1138 {
1139 my $resp=decode_json($client->responseContent());
1140 my $dealReference=$resp->{dealReference};
1141 print "$name, dr=$dealReference\n";
1142 if (defined $dealReference and length($dealReference)>5)
1143 {
1144 push(@done,$position);
1145 die;
1146 next;
1147 next;
1148 }
1149 }
1150 else
1151 {
1152 print "$name failed $code: ".$client->responseContent()."\n";
1153 push(@notdone,$position);
1154 }
1155 }
1156 @$done=@done if ($done);
1157 @$notdone=@notdone if ($notdone);
1158  
1159 printf "done=%d notdone=%d\n",0+@done,0+@notdone;
1160 print "notdone:\n";
1161  
1162 my $cpc='%%';
1163 my $format="%-41sinstrumentName %+4.2fsize %-9.2flevel ".
1164 "%-8.2fbid £%-8.2fprofit %4.1fprofitpc%% £%10.2fatrisk %-9sstopLevel %-4sslpc$cpc\n";
1165  
1166 $self->printpos("stdout" , ['Name','Size','Open','Latest','P/L','P/L%','Value','Stop','Stop'], $format);
1167  
1168 map { $self->printpos("stdout" , $_, $format) } @notdone;
1169  
1170 }
1171 #####################################################################
1172 # given a ref to an array of positions, attempt to buy the same
1173 # position in this object.
1174 # if the position already exists or is succesfully brought, count as success.
1175 # If the buy fails, include it in the returned list.
1176 # If all buys succesful then return an empty list.
1177 # done and notdone references may be supplied and if they are these should point to arrays
1178 # of the succesful and unsuccesful positions.
1179 # return value is NOT now used.
1180 # ignortradeable ... use this if the positionis an old one, so that tradeable status could
1181 # be out of date.
1182 #####################################################################
1183  
1184 =head2 buy - attempt to buy a number of instruments.
1185  
1186 Parameters
1187  
1188 1 Reference to an array of positions
1189 2 Optional ref to an array done, to be filled with succesful buys
1190 3 Optional ref to an array notdone, to be filled with the failed
1191 4 ignore tradeable, one of the fields in a position relates to the market
1192 being open or closed (TRADEABLE) If this field is current, its a
1193 good indication to skip this one (place it in the notdone array.
1194 But if its out of date then setting this flag 1 attempts the trade
1195 anyway.
1196  
1197 Attempt to buy positions. I have used this to move positions
1198 between a demo account and real account or vice-versa.
1199  
1200 =head3 Status - very experimental.
1201  
1202 Contains print statements that should
1203 probably be removed.
1204  
1205 =cut
1206 #####################################################################
1207 sub buy
1208 {
1209 my $self=shift;
1210 my $positions=shift; # to buy
1211 my $done=shift;
1212 my $notdone=shift;
1213 my $ignoretradeable=shift;
1214  
1215 my $verbose=0;
1216  
1217 my @done;
1218 my @notdone;
1219 my $headers = {
1220 'Content-Type' => 'application/json; charset=UTF-8',
1221 'Accept' => 'application/json; charset=UTF-8',
1222 VERSION => 2,
1223 # 'IG-ACCOUNT-ID'=> $accountid,
1224 CST=>$self->CST,
1225 'X-SECURITY-TOKEN'=> $self->XSECURITYTOKEN,
1226 'X-IG-API-KEY'=> $self->apikey,
1227 };
1228  
1229 my $data = {
1230 direction => 'BUY',
1231 #epic=>
1232 #size=>0.1
1233 orderType=>'MARKET',
1234 guaranteedStop=>'false',
1235 forceOpen=>'false',
1236 timeInForce => "EXECUTE_AND_ELIMINATE", # "GOOD_TILL_CANCELLED"
1237 };
1238 my $client = REST::Client->new();
1239 $client->setHost($self->_url);
1240  
1241 my $existing=$self->positions;
1242 my %existhash;
1243 map { $existhash{$self->fetch($_,'epic')}=$_ } @$existing;
1244  
1245 for my $position (@$positions)
1246 {
1247 # die dump($position);
1248  
1249 my $existingsize=0;
1250 my $epic=$self->fetch($position,'epic');
1251 my $name=$self->fetch($position,'instrumentName');
1252  
1253 my $ms=$self->fetch($position,'marketStatus');
1254  
1255  
1256 if (exists $existhash{$epic})
1257 {
1258 my $existingposition=$existhash{$epic};
1259 $existingsize=$self->fetch($existingposition,'size');
1260 }
1261  
1262 my $demandsize=$self->fetch($position,'size');
1263 my $wantedsize=$demandsize-$existingsize;
1264  
1265 print "existingsize=$existingsize wantedsize=$wantedsize, demandsize=$demandsize\n";
1266 if ($wantedsize<=0)
1267 {
1268 push(@done,$position);
1269 print "$name, not needed\n";
1270 next;
1271 }
1272  
1273 if ($ms ne 'TRADEABLE' and !$ignoretradeable)
1274 {
1275 push(@notdone,$position);
1276 print "$name, market status is $ms\n";
1277 next;
1278 }
1279  
1280  
1281 #$data->{epic}=$self->fetch($position,'epic');
1282 $data->{epic}=$epic;
1283 $data->{size}=$wantedsize;
1284 $data->{currencyCode}=$self->fetch($position,'currency');
1285 $data->{expiry}='DFB';
1286  
1287 #my $jdata = encode_json($data);
1288 my $jdata=JSON->new->canonical->encode($data);
1289 # die $jdata;
1290 print "$data->{direction}: $position->{instrumentName} $position->{size}\n";
1291 $client->POST (
1292 '/positions/otc',
1293 $jdata,
1294 $headers
1295 );
1296 my $code=$client->responseCode();
1297 if ($code==200)
1298 {
1299 print "200: ".$client->responseContent()."\n";
1300 my $resp=decode_json($client->responseContent());
1301 my $dealReference=$resp->{dealReference};
1302 print "$name, dr=$dealReference\n";
1303 if (defined $dealReference and length($dealReference)>5)
1304 {
1305 push(@done,$position);
1306 next;
1307 }
1308 }
1309 print "$name, failed code $code \n";
1310 push(@notdone,$position);
1311 }
1312 @$done=@done if ($done);
1313 @$notdone=@notdone if ($notdone);
1314 printf "done=%d notdone=%d\n",0+@done,0+@notdone;
1315 print "notdone:\n";
1316  
1317 return;
1318  
1319 my $format="%-41sinstrumentName %+4.2fsize %-9.2flevel ".
1320 "%-8.2fbid £%-8.2fprofit %4.1fprofitpc%% £%10.2fatrisk\n";
1321  
1322 $self->printpos("stdout" , ['Name','Size','Open','Latest','P/L','P/L%','Value','Stop','Stop'], $format);
1323  
1324 map { $self->printpos("stdout" , $_, $format) } @notdone;
1325  
1326 }
1327  
1328  
1329 #####################################################################
1330 # uses known structure of supplied deep hash to search for item
1331 # should probably replace with a more generalised deep fetch function.
1332 #####################################################################
1333  
1334 =head2 fetch
1335  
1336 This function is a way to hide the various structures a position may have
1337  
1338 Parameters
1339  
1340 1 A position hash ref, $h
1341 2 The name of the item to be retrieved.
1342  
1343 Returns undef if not found, or the value of item if it is.
1344  
1345 The function looks first in $h->{item} then
1346 in $h->{position}=>{item} and then in $h->{market}->{item}
1347  
1348 Its only useful with positions, not hashes in general.
1349  
1350 =cut
1351 #####################################################################
1352 sub fetch
1353 {
1354 my ($self,$position,$item)=@_;
1355  
1356 # return "NOT A HASREF $position"if (ref($position) ne 'HASH');
1357 die "supplied position $position to fetch() is not a HASHREF" if (ref($position) ne 'HASH');
1358 defined $item or die "fetch, item undefined";
1359 my $p=$position->{position};
1360 my $m=$position->{market};
1361  
1362 if (exists $position->{$item}) { return $position->{$item}; }
1363 elsif (exists $p->{$item}) { return $p->{$item}; }
1364 elsif (exists $m->{$item}) { return $m->{$item}; }
1365 else {
1366 return undef;
1367 }
1368  
1369 }
1370  
1371 #####################################################################
1372 # given an instrument name in search, look for it inside the instrumentName, and return
1373 # the epic. Fail if result is not 1 item.
1374 # used for filling in the epic (a unique identifier) in old data files
1375 # where I forgot to store it.
1376 #####################################################################
1377  
1378 =head2 epicsearch
1379  
1380 Find the epic (unique identifier) for an instrument from the underlying share.
1381  
1382 Parameters
1383  
1384 1 A aubstring to be searched for in the name.
1385  
1386 This function calls IG's search API looking for a match to the name. If found
1387 the value of the epic is returned.
1388  
1389 =head3 Status - very experimental.
1390  
1391 Contains print and die statements. Useful if you forgot to record the epic.
1392  
1393 =cut
1394 #####################################################################
1395 sub epicsearch
1396 {
1397 my ($self,$search)=@_;
1398 my $headers =
1399 {
1400 'Content-Type' => 'application/json; charset=UTF-8',
1401 'Accept' => 'application/json; charset=UTF-8',
1402 VERSION => 1,
1403 CST=>$self->CST,
1404 'X-SECURITY-TOKEN'=> $self->XSECURITYTOKEN,
1405 'X-IG-API-KEY'=> $self->apikey,
1406 };
1407 #my $jheaders = encode_json($headers);
1408 my $jheaders=JSON->new->canonical->encode($headers);
1409 my $client = REST::Client->new();
1410 $client->setHost($self->_url);
1411 $search=~s#/#%2F#g;
1412 my $url="/markets?searchTerm=$search";
1413 $search=~s#%2F#/#g;
1414 $url=~s/ /%20/g;
1415 my $r=$client->GET ( $url, $headers);
1416  
1417 # my $resp=decode_json($client->responseContent());
1418  
1419  
1420 #print "url=$url\n";
1421 my $code;
1422  
1423 $code=$client->responseCode();
1424  
1425 my $retried=0;
1426 while ($code==403 and $retried<4)
1427 {
1428 sleep 10;
1429 $retried++;
1430 $r=$client->GET ( $url, $headers);
1431 $code=$client->responseCode();
1432 # print "search retried\n";
1433 }
1434  
1435 die "response code from url='$url' code=$code retried $retried times" if ($code!=200);
1436  
1437 my $markets=decode_json($client->responseContent);
1438 # print JSON->new->ascii->pretty->encode($markets)."\n";
1439  
1440 my @wantedmarkets=grep { $_->{expiry} eq 'DFB' } @{$markets->{markets}};
1441 @wantedmarkets=grep { $self->_nothe($self->fetch($_,'instrumentName') , $search) } @wantedmarkets;
1442  
1443 @wantedmarkets=map { $_->{epic} } @wantedmarkets;
1444 die "Zero epics found for search $search" if (@wantedmarkets==0);
1445 die "Multiple epics found @wantedmarkets for search $search" if (@wantedmarkets!=1);
1446  
1447 return $wantedmarkets[0];
1448  
1449 }
1450 #####################################################
1451 # remove a trailing 'the'
1452 #####################################################
1453 sub _nothe
1454 {
1455 my ($self,$x,$y)=@_;
1456  
1457 # print "comparing $x $y \n";
1458 $x=~s#/.*$##;
1459 $y=~s#/.*$##;
1460  
1461 return $x eq $y;
1462 }
1463 # so this is used to read one of my old data files.
1464 ##################################################################################
1465 # Reads am ascii file - older format and returns a list of positions,
1466 # a hashref keyed on epic.
1467 ##################################################################################
1468  
1469 =head2 readfile_oldformat
1470  
1471  
1472 Parameters
1473  
1474 1 Path to a file to read
1475  
1476 A file readable by this function may be generated by using printpos with format as follows:
1477 "%-41sinstrumentName %+6.2fsize %-9.2flevel ".
1478 "%-9.2fbid £%-8.2fprofit %5.1fprofitpc%% £%10.2fatrisk\n",
1479  
1480 This file was originally generated to be human readable so reading by machine is a stretch.
1481  
1482 =head3 Status - downright broken (for you). Sorry!
1483  
1484 May contains print and die statements. Contaions hardcoded paths that will need to be
1485 changed.
1486  
1487 =cut
1488 ##################################################################################
1489 sub readfile_oldformat
1490 {
1491 my ($self, $f,$writenewfile)=@_;
1492 my $positions={};
1493 my $totalline;
1494 $f="/home/mark/igrec/results/$f";
1495 open(F,$f) or die "cannot open $f";
1496 #Roku Inc +0.38 16501.00 21842.0 £2029.58 32.4% £ 8299.96
1497 my @fieldhashnames=qw(epic instrumentName size level bid profit profitpc atrisk);
1498 while (<F>)
1499 {
1500 my @fields;
1501 my @names=@fieldhashnames;
1502 my $position={};
1503  
1504 chomp;
1505 if (m/\|/)
1506 {
1507 die;
1508 }
1509 elsif (m/^Name/)
1510 {
1511 s/[£%]//g;
1512 @fields=split(/ +/);
1513 unshift(@fields,'Epic');
1514 # print "#".join("\|",@fields)."\n";
1515 }
1516 elsif (m/^Total/)
1517 {
1518 $totalline=$_;
1519 }
1520 else
1521 {
1522 my $name=substr($_,0,42);
1523 my $line=substr($_,43);
1524 $name=~s/ +$//;
1525 $line=~s/[\$£%]//g;
1526 @fields=split(/ +/,$line);
1527 my $epic=$self->epicsearch($name);
1528 unshift(@fields,$epic,$name);
1529 #die "$line\n@fields\n@names";
1530 while (@names)
1531 {
1532 $position->{shift(@names)}=shift(@fields);
1533 }
1534 $positions->{$epic}=$position;
1535 }
1536 }
1537 # close F;
1538 if ($writenewfile)
1539 {
1540 $f=~s/results/r2/;
1541 if (! -e $f)
1542 {
1543 open(my $g,">" , $f) or die "Cannot open $f for write";
1544 my $format= "%sepic|%sinstrumentName|%0.2fsize|%-0.2flevel|".
1545 "%-0.2fbid|£%-0.2fprofit|%0.1fprofitpc%%|£%0.2fatrisk\n",
1546 print $g "Epic|Instrumentname|Size|Level|Bid|Profit£|Profitpc%|Atrisk£\n";
1547 my $a=$self->agg([values %$positions]);
1548 for (@$a)
1549 {
1550 $self->printpos($g,$_,$format);
1551 }
1552 print $g $totalline."\n";
1553 }
1554 }
1555 return $positions;
1556 }
1557 ##################################################################################
1558 # Reads am ascii file and returns a list of positions,
1559 # a hashref keyed on epic.
1560 ##################################################################################
1561  
1562 =head2 readfile
1563  
1564  
1565 Parameters
1566  
1567 1 Path to a file to read
1568  
1569 This function calls IG's search API looking for a match to the name. If found
1570 the value of the epic is returned.
1571  
1572 A file readable by this function may be generated by using printpos with format as follows:
1573 "%sepic|%sinstrumentName|%0.2fsize|%-0.2flevel|".
1574 "%-0.2fbid|£%-0.2fprofit|%0.1fprofitpc%%|£%0.2fatrisk|%smarketStatus\n",
1575  
1576 =head3 Status - downright broken (for you). Sorry!
1577  
1578 May contains print and die statements. Contaions hardcoded paths that will need to be
1579 changed.
1580  
1581 =cut
1582 ##################################################################################
1583 sub readfile
1584 {
1585 my ($self,$f)=@_;
1586  
1587 my $positions={};
1588 $f="/home/mark/igrec/r2/$f";
1589 open(F,$f) or die "cannot open $f";
1590 my @fieldhashnames=qw(epic instrumentName size level bid profit profitpc atrisk tradeable);
1591 my $ln=0;
1592 while (<F>)
1593 {
1594 my @fields;
1595 my @names=@fieldhashnames;
1596 my $position={};
1597  
1598 $ln++;
1599 chomp;
1600 if (m/^Total/)
1601 {
1602 next;
1603 }
1604 elsif (m/ Positions$/)
1605 {
1606 next;
1607 }
1608 elsif (m/^ *$/)
1609 {
1610 next;
1611 }
1612 elsif (m/#/)
1613 {
1614 next;
1615 }
1616 elsif (!m/\|/)
1617 {
1618 die "No | lin line $ln file $f";
1619 }
1620 elsif (m/Epic/)
1621 {
1622 next;
1623 }
1624 else
1625 {
1626 s/[£&]//g;
1627 @fields=split(/\|/);
1628 for my $fieldname (@fieldhashnames)
1629 {
1630 die if (!defined $names[0]);
1631 #print "names[0]=$names[0]\n";
1632 $position->{$fieldname}=shift(@fields);
1633 }
1634 $positions->{$position->{epic}}=$position;
1635 $position->{marketStatus}//=''; # older files do not record this.
1636 }
1637 }
1638 return $positions;
1639 }
1640 #####################################################################
1641 # format strings contained embedded printf specifiers followed by
1642 # a hash element name .
1643 #
1644 # eg "%sdate %sdescription %sepic %sstatus\n";
1645 # eg "%-20sdate %-30sdescription %-20sepic %-15sstatus\n";
1646 # eg
1647 # "%sepic|%sinstrumentName|%6.2fsize|%-9.2flevel|".
1648 # "%-9.2fbid|£%-8.2fprofit|%5.1fprofitpc%%|£%10.2fatrisk\n",
1649 #eg
1650 # "%-41sinstrumentName %+6.2fsize %-9.2flevel ".
1651 # "%-9.2fbid £%-8.2fprofit %5.1fprofitpc%% £%10.2fatrisk\n",
1652 # Arguments:
1653 # 1) An IG object ref. (self) Is not really used.
1654 # 2) Either "stdout" or an open writable file handle.
1655 # 3) A hash possibly deep, with items. Ig the item is not found directly in the hash,
1656 # the $self->fetch function is used for access. If still not found
1657 # then "UNDEF" is printed.
1658 # CHANGED to $self->uds
1659 # OR: If this is an array ref, then a title line is ptinted using the format string
1660 # and the referenced array of titles
1661 # OR: If empty dtring ort undef, derive titles from the format
1662 # string and print a title line.
1663 # 4) A formatting string. Can contain text, containing embedded
1664 # format instructions like %6.2fsize here %6.2f is a print f
1665 # specifier and size is the name of the item to retrieve from the hash.
1666 # 5,6) up /down can be percent gives green if > up, bold green if > 5*up.
1667 # can be a coloration function of position.
1668 # just one function, so no down ever.
1669 # function takes argument position, and returns optional colors
1670 #####################################################################
1671 sub printpos
1672 {
1673  
1674 my ($self,$out,$position,$format,$up,$down)=@_;
1675  
1676 my $colsub;
1677  
1678 $out=*STDOUT if ($out eq "stdout");
1679  
1680 $down=-$up if (defined $up and ref($up) eq '' and !defined $down) ;
1681  
1682 if (defined $up and ref($up) ne 'CODE')
1683 {
1684 $colsub=sub
1685 {
1686 my ($position)=shift;
1687 my $v1=$position->{dbid};
1688 my $col='';
1689 $v1=~s/%//;
1690 $col=Green if (defined $up and $v1>$up);
1691 $col=Red if (defined $down and $v1<$down);
1692 $col=Green+Bold if (defined $up and $v1>$up*5);
1693 $col=Red+Bold if (defined $down and $v1<5*$down);
1694 return $col;
1695 };
1696 }
1697 $colsub=$up if (defined $up and ref($up) eq 'CODE');
1698 $colsub=sub {''} if (!defined $up);
1699  
1700  
1701 my $titles=$format;
1702 if (ref($position) eq 'ARRAY') # its titles to print!
1703 {
1704 #$format=~s/%[-+]/%/g;
1705 #print "$format\n";
1706 while ($format=~m/[-+]?([0-9]+)\.([0-9]+)/)
1707 {
1708 my $x;
1709 $x=$1;
1710 abs($2)>abs($x) and $x=$2;
1711 $format=~s/%([-+]?)([0-9]+)\.([0-9]+)/%$1$x/;
1712 }
1713 #print "#1 $format\n";
1714 $format=~s/%\+\+/%+/g;
1715 #print "#2 $format\n";
1716 $format=~s/%([-\+]?[0-9]+)\.[0-9]+/%$1/g;
1717 #print "#3 $format\n";
1718 $format=~s/%([-\+]?[0-9]+)[fd]/%$1s/g;
1719 #print "#4 $format\n";
1720 $format=~s/%([-\+]?[0-9]*)([a-zA-Z_][a-zA-Z0-9_]*)/%$1s/g;
1721 #die $format;
1722 # print "$format\n"; exit;
1723 #$"=":"; print "@$position\n";
1724  
1725  
1726 #$format="%-41s %+7s %11s %-10s £%-10s %5s%% £%12s %-9s %-4s";
1727 #print "$format\n"; #exit;
1728 print $out Bold if ($self->col and defined $INC{'Term/Chrome.pm'});
1729 # print "format='$format' @$position\n";
1730 printf $out $format,@$position;
1731 print $out Reset if ($self->col and defined $INC{'Term/Chrome.pm'});
1732 return;
1733 }
1734  
1735 # auto generated title list from the names
1736 if (!defined $position or $position eq '')
1737 {
1738 $titles=~s/\n//g;
1739 $titles=~s/%([-+0-9.]*)([sf])/%/g;
1740 $titles=~s/%%/__PC__/g;
1741 $titles=~s/%//; # just one
1742 $titles=~s/£%([a-zA-Z]+)/%$1£/g;
1743 my @titles=split(/%/,$titles);
1744 map {s/[|,]//g } @titles;
1745 map {s/ +//g } @titles;
1746 map { s/__PC__//g; } @titles;
1747 map { s/([\w']+)/\u\L$1/g; } @titles;
1748 while ($format=~m/%[-+]?([0-9]+)\.([0-9]+)/)
1749 {
1750 my $x;
1751 #my $x=$1+$2;
1752 $x=$1;
1753 $2>$x and $x=$2;
1754 $format=~s/%([-+]?)([0-9]+)\.([0-9]+)/%$1$x/;
1755 }
1756 $format=~s/(%[-+0-9.]*)[a-zA-Z]+/$1s/g;
1757 #$format=~s/(%[-+0-9]+)\.[0-9]+/$1/g;
1758 $format=~s/£//g;
1759 #die "format=$format titles=@titles";
1760 print $out Bold if ($self->col and defined $INC{'Term/Chrome.pm'});
1761 printf $out $format, @titles;
1762 print $out Reset if ($self->col and defined $INC{'Term/Chrome.pm'});
1763 return;
1764 }
1765  
1766  
1767  
1768 # $p=$position->{position};
1769 # $m=$position->{market};
1770  
1771 $format=~s/%%/##/g;
1772  
1773  
1774 # while (($format=~s/%([-+0-9]+\.[0-9]+)([a-z][a-zA-Z0-9]*)/%$1__S__/) || ($format=~s/%([-+0-9]*)([a-z][a-zA-Z0-9]*)/%$1__F__/))
1775 # {
1776 # my $s;
1777 # $s=$activity->{$2};
1778 # my $pos=$1;
1779 # $pos=~s/-//;
1780 # $s=substr($s,0,$pos) if (defined(pos) and $pos ne '' and $pos<length($s));
1781 # push(@args,$s);
1782 # }
1783  
1784 my $col='';
1785 while ($format=~s/%([-+0-9.]*[dsf])([a-zA-Z_][a-zA-Z0-9_]*)/%s/)
1786 {
1787 my $s;
1788  
1789 my $item=$2;
1790 my $len=$1//"";
1791 # die "item is UNDEF" if ($item eq 'UNDEF');
1792 # die "len is UNDEF" if ($len eq 'UNDEF');
1793 # $len='' if ($len eq 'UNDEF');
1794 $len="%".$len if ($len);
1795 if (defined $item and $item ne '' and exists $position->{$item} and defined $position->{$item})
1796 {
1797 $position->{$item}=~s/%//g;
1798 #$position->{$item}='0' if ($position->{$item} eq 'UNDEF');
1799 $s=sprintf($len,$position->{$item});
1800 if ($item eq 'dbid' and exists $INC{'Term/Chrome.pm'} and $self->col)
1801 {
1802 ##my $v1=$position->{dbid};
1803 ##$v1=~s/%//;
1804 ##$col=Green if (defined $up and $v1>$up);
1805 ##$col=Red if (defined $down and $v1<$down);
1806 ##$col=Green+Bold if (defined $up and $v1>$up*5);
1807 ##$col=Red+Bold if (defined $down and $v1<5*$down);
1808  
1809 # $col=&$colsub($position);
1810 }
1811 # $col=Yellow if (defined $up);
1812 # $col=&$colsub($position);
1813 }
1814 elsif (defined $self->fetch($position,$item))
1815 {
1816 #$s=sprintf($len,$self->fetch($position,$2)//"UNDEF");
1817 $s=sprintf($len,$self->fetch($position,$item)//$self->uds);
1818 if ($item eq 'dbid' and defined $INC{'Term/Chrome.pm'} and $self->col)
1819 {
1820 #my $v1;
1821  
1822 #$v1=$self->fetch($position,'dbid');
1823 #$v1=~s/%//;
1824 #$v1=100*$v1/$self->fetch($position,'bid');
1825 ###$col=Green if (defined $up and $self->col and $self->fetch($position,'dbid')/$self->fetch($position,'bid')>$up/100);
1826 ###$col=Red if (defined $down and $self->col and $self->fetch($position,'dbid')/$self->fetch($position,'bid')<$down/100);
1827 #$col=Green if (defined $up and $self->col and $v1>$up);
1828 #$col=Red if (defined $down and $self->col and $v1<$down);
1829 #$col=Green+Bold if (defined $up and $self->col and $v1>$up*5);
1830 #$col=Red+Bold if (defined $down and $self->col and $v1<5*$down);
1831 #$col=&$colsub($position);
1832 }
1833 #$col=&$colsub($position);
1834  
1835 }
1836 else
1837 {
1838 $len=~s/[df]/s/;
1839 $len=~s/\.[0-9]+//;
1840 #$s=sprintf($len,"UNDEF");
1841 $s=sprintf($len,$self->uds);
1842 }
1843  
1844 $col=&$colsub($position);
1845 $len=~s/[sf]$//;
1846 if ($len ne '') # len can be something like 0.2
1847 {
1848 $len=~s/%//;
1849 $len=abs($len) if ($len ne '');
1850 $s=substr($s,0,$len) if ($len and $len<length($s) and $len>=1);
1851 }
1852  
1853 $format=~s/%s/$s/;
1854 }
1855  
1856 $col=&$colsub($position)//'' if ($self->col and defined $INC{'Term/Chrome.pm'});
1857 $format=~s/##/%/g;
1858 $format=~s/£-/-£/g;
1859 print $out $col, $format;
1860 if (ref($col) ne '')
1861 { print $out Reset;
1862 }
1863  
1864 }
1865  
1866 =head1 DEPENDENCIES
1867  
1868 Moose
1869 Term::Chrom if available.
1870  
1871 =head1 UTILITIES
1872  
1873 A more complete position lister is given as igdisp.pl
1874  
1875 =head1 AUTHOR
1876  
1877 Mark Winder, C<< <markwin at cpan.org> >>
1878  
1879 =head1 BUGS
1880  
1881 Please report any bugs or feature requests to C<bug-finance-ig at rt.cpan.org>, or through
1882 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Finance-IG>. I will be notified, and then you'll
1883 automatically be notified of progress on your bug as I make changes.
1884  
1885  
1886  
1887  
1888 =head1 SUPPORT
1889  
1890 You can find documentation for this module with the perldoc command.
1891  
1892 perldoc Finance::IG
1893  
1894  
1895 You can also look for information at:
1896  
1897 =over 4
1898  
1899 =item * RT: CPAN's request tracker (report bugs here)
1900  
1901 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Finance-IG>
1902  
1903 =item * CPAN Ratings
1904  
1905 L<https://cpanratings.perl.org/d/Finance-IG>
1906  
1907 =item * Search CPAN
1908  
1909 L<https://metacpan.org/release/Finance-IG>
1910  
1911 =back
1912  
1913  
1914 =head1 ACKNOWLEDGEMENTS
1915  
1916 =head1 FURTHER READING
1917  
1918 IG REST API Reference https://labs.ig.com/rest-trading-api-reference
1919  
1920 =head1 LICENSE AND COPYRIGHT
1921  
1922 This software is Copyright (c) 2020 by Mark Winder.
1923  
1924 This is free software, licensed under:
1925  
1926 The Artistic License 2.0 (GPL Compatible)
1927  
1928  
1929 =cut
1930  
1931 1; # End of Finance::IG
« blib/lib/Finance/IG.pm ↑ Summary