NAME
Finance::IG - - Module for doing useful stuff with IG Markets REST API.
DESCRIPTION
This is very much a first draft, but will enable you to get simple arrays of positions, print them out possily some simple trading.
Its proof of concept in perl beyond anything else, extend it as you need to.
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.
You will need an API key to use this module, available free from IG Markets.
VERSION
Version 0.103
SYNOPSIS
use Finance::IG;
use strict;
no strict 'refs';
use warnings;
my $ig=iFinance::IG->new(
username=> "demome",
password=> "mypassword",
apikey=> "4398232394029341776153276512736icab",
isdemo=>0,
);
my $p=$ig->positions(); # Get a list of positions
$p=$ig->agg($p,$sortlist); # Aggregate them, so one item per instrument.
my $format="%-41sinstrumentName %+6.2fsize %-9.2flevel ".
"%-9.2fbid £%-8.2fprofit %5.1fprofitpc%% £%10.2fatrisk\n",
$ig->printpos("stdout" , [], $format);
for my $position (@$p)
{
$ig-> printpos("stdout" ,$position,$format);
}
UTILITIES
The utility igdisp.pl is installed with this module and may be used to list your positions on IG. A help message can be obtained with igdisp.pl -h
SUBROUTINES/METHODS
This is a list of currently implemented methods
new
Normal parameters, as above.
col=>1
Causes Finance::IG to try to use Term::Chrome to do some simple coloration of output. If Term::Chrome is not installed, it will be silently ignored. See printpos.
login
Originally needed to be called once after new and before other calls. Now this is done automatically, so you do not need to use this or be aware of it. Look for a 401 error if your password is wrong.
No Parameters.
printpos print out a formatted hash as one line
Parameters
file - can be a file handle or the string stdout or the glob *STDOUT
A position of other shallow hash,
A format string. The format string is similar to a printf format string, for example %s says print out a string
however, the name of the item to be printed follows the letter, eg %sinstrumentName print the string instrument name.
optional up
optional down
A title line can be printed by either passing an array ref instead of a position, in which case the array ref can contain the titles to print. If the array is empty then the titles will be generated from the format string.
up and down can be provided and represent negative and posite limits on dbid element by default. Alternatively, provide up only and make it a subroutine ref.
The subroutime takes parameter a position, and should return escape characters (from Term::Chrome to colorise the line.
transactions - retrieve transactions history
transactions(++$page,Time::Piece->strptime("2020-01-01","%Y-%m-%d-%H.%M"),scalar localtime)
Parameters
Paging number, start at 1 Start time, can be a string or a Time::Piece Endtime
return a reference to an array of transactions for that time span. Each transaction is a hash of data.
login - loginto the account.
Parameters - none
login to the object, using the parameters provided to new.
You should call this just once per object after calling new.
flatten
Parameters 1 Ref to array of hashes to flatten or a ref to a hash to flatten 2 ref to an array of items to flatten, or just a single item name.
Typical use of this is for a position that as it comes back from IG contains a market and a position byut we would prefer all items at the top level. This would moves all the keys of position and market up one level and would remove the keys market and position.
$self->flatten($hash, [qw(market position)]);
accounts - retrieve a list of accounts
Parameters - none
Return value - Array ref containing hashes of accounts.
agg - aggregate positions into a flattened 1 element per instrument form.
Parameters
1 Reference to an array of positions
2 (Optional) Ref to an array of keys to sort on
agg does three things actually. First, it joins together multiple positions of the same instrument, generating sensible values for things like profit/loss and size
Second, it performs some flattening of the deep structure for a position which comes from IG.
Third it sorts the result. The default sort order I use is -profitpc instrumentName, but you can provide a 2rd parameter, a reference to an array of items to sort by. Each item can optionally be preceeded by - to reverse the prder. If the first item equates equal, then the next item is used.
nonagg - like agg but do not do actual aggregation
Parameters
1 Reference to an array of positions
2 (Optional) Ref to an array of keys to sort on
Return value - Array ref containing hashes of accounts. Should be the same size as the original.
sorter - general array sort function for an array of hashes
Parameters
1 Ref to array of keys to sort. Each my be prefixed with a - to
reverse the order on that key. If keys compare equal the next key is used.
2 Ref to an array of positions to sort.
The array is sorted in-place. A numeric comparison is done if for both items $x == $x+0
Formatted datetimes are correctly sorted.
close - close the supplied positions.
Parameters
1 Ref to array of positions to close.
reverse the order on that key.
2/3 ref to done / notdone arrays to sort succesful / failed
closes in to.
The idea is this will close all the supplied positions, optionally returning a reference to
Status - very experimental.
Contains die / print statements that you may wish to remove
buy - attempt to buy a number of instruments.
Parameters
1 Reference to an array of positions
2 Optional ref to an array done, to be filled with succesful buys
3 Optional ref to an array notdone, to be filled with the failed
4 ignore tradeable, one of the fields in a position relates to the market
being open or closed (TRADEABLE) If this field is current, its a
good indication to skip this one (place it in the notdone array.
But if its out of date then setting this flag 1 attempts the trade
anyway.
Attempt to buy positions. I have used this to move positions between a demo account and real account or vice-versa.
Status - very experimental.
Contains print statements that should probably be removed.
prices - Obtain historical prices
Obtain historical price information on an instrument.
Parameters
Unused parameters should be set as undef or ''. (either);
1 A aubstring to be searched for in the name. Eg "UB.D.FTNT.DAILY.IP"
2 Resolution. Should be one of the IG defined strings (left) or (in my opinion more memorable) aliases (right)
DAY 1d
HOUR 1h
HOUR_2 1h
HOUR_3 2h
HOUR_4 3h
MINUTE 1m
MINUTE_2 2m
MINUTE_3 3m
MINUTE_5 5m
MINUTE_10 10m
MINUTE_15 15m
MINUTE_30 30m
SECOND 1s
WEEK 1w
MONTH 1M
4, 5 pageNumber, pageSize What page to produce, and how many items on it.
6, 7 from , to (dates) can be a string of the form 2021-01-01T16:15:00 or a Time::Piece
8 max Limits the number of price points (not applicable if a date range has been specified)
flatten_withunder
Flatten a deep structure, up to 3 layers deep using underscores to create new keys by concatenating deeper keys. Deep keys are removed. More than 3 layers can be removed by calling multiply.
Parameters
One or more scalers to opperate on or an array. Each will be flattened
where there are hashes or hashes or hashes of hashes of hashes
to a single depth, with elements joined by underscores
Example
{
"metadata" : {
"allowance" : {
"allowanceExpiry" : 530567,
"remainingAllowance" : 9557,
"totalAllowance" : 10000
},
...
becomes
{
"metadata_allowance_allowanceExpiry" : 530473,
"metadata_allowance_remainingAllowance" : 9556,
"metadata_allowance_totalAllowance" : 10000,
...
The advantage of a flattened structure is its easier to print with existing fuunctions like printpos
fetch
This function is a way to hide the various structures a position may have
Obsolete but still used sometimes.
Parameters
1 A position hash ref, $h
2 The name of the item to be retrieved.
Returns undef if not found, or the value of item if it is.
The function looks first in $h->{item} then in $h->{position}=>{item} and then in $h->{market}->{item}
Its only useful with positions, not hashes in general.
epicsearch
Find the epic (unique identifier) for an instrument from the underlying share.
This function calls IG's search API looking for a match to the name. If found the value of the epic is returned.
Status - very experimental. Seems to work well.
Contains print and die statements. Useful if you forgot to record the epic.
readfile_oldformat
Parameters
1 Path to a file to read
A file readable by this function may be generated by using printpos with format as follows: "%-41sinstrumentName %+6.2fsize %-9.2flevel ". "%-9.2fbid £%-8.2fprofit %5.1fprofitpc%% £%10.2fatrisk\n",
This file was originally generated to be human readable so reading by machine is a stretch.
Status - downright broken (for you). Sorry!
May contains print and die statements. Contaions hardcoded paths that will need to be changed.
readfile
Parameters
1 Path to a file to read
A file readable by this function may be generated by using printpos with format as follows: "%sepic|%sinstrumentName|%0.2fsize|%-0.2flevel|". "%-0.2fbid|£%-0.2fprofit|%0.1fprofitpc%%|£%0.2fatrisk|%smarketStatus\n",
Status - downright broken (for you). Sorry!
The function contains a hardcoded path for reading the files. You would need a crontab entry to generate them.
May contain print and die statements. Contains hardcoded paths that will need to be changed.
printpos
Parmeters
A file handle or the word stdout, all output sent here.
A hashref of items to print OR: If this is an array ref, then a title line is ptinted using the format string and the referenced array of titles OR: If empty string or undef, derive titles from the format string and print a title line.
A formatting string. Can contain text, containing embedded format instructions like %6.2fsize here %6.2f is a print f specifier and size is the name of the item to retrieve from the hash.
OPTIONAL up can be percent gives green if > up, bold green if > 5*up. can be a coloration function of position. Just one function, so no down ever if a function is given function takes argument position, and returns optional colors
OPTIONAL down can be percent gives red if <down , bold red if < 5*down.
Description
This is a very general function will work with any hash.
sortrange
Parameters
Ref to an array containing dates in printed ascii format.
If there are no dates or an empty array, an empty string is returned.
If there is one date, then that date is returned
If there is more than one then the first and last after sorting is returned, with a dash between them.
This is used in aggregation of positions and relates to creation dates with multiple positions in the same security purchased at different times.
Red Blue Bold Reset Underline Green color
Description
The above parameterless functions are provided if Term::Chrome is not available. They are "do nothing" subs provided to satisfy references only.
DEPENDENCIES
Moose
Term::Chrom if available.
UTILITIES
A more complete position lister is given as igdisp.pl
AUTHOR
Mark Winder, <markwin at cpan.org>
BUGS
Please report any bugs or feature requests to bug-finance-ig at rt.cpan.org
, or through the web interface at https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Finance-IG. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Finance::IG
You can also look for information at:
RT: CPAN's request tracker (report bugs here)
CPAN Ratings
Search CPAN
ACKNOWLEDGEMENTS
FURTHER READING
IG REST API Reference https://labs.ig.com/rest-trading-api-reference
LICENSE AND COPYRIGHT
This software is Copyright (c) 2020 by Mark Winder.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)