API

Client

Client Object

class pygindex.client.IGClient(auth: pygindex.models.IGUserAuth = None, api_config: pygindex.models.IGAPIConfig = None)

This is a class implementing basic IG Index API Client actions.

Parameters
close_position(position: pygindex.models.IGPosition)dict

This method closes an open position

Parameters

position (IGPosition) – Position to close

Returns

Response from IG API service

Return type

dict

get_accounts()dict

This method retrieves account details

Example:

c = IGClient()
s = c.get_accounts()

Account details:

{
    "accounts": [
        {
            "accountAlias": null,
            "accountId": "XXXXX",
            "accountName": "CFD",
            "accountType": "CFD",
            "balance": {
                "available": 0.0,
                "balance": 0.0,
                "deposit": 0.0,
                "profitLoss": 0.0
            },
            "canTransferFrom": true,
            "canTransferTo": true,
            "currency": "GBP",
            "preferred": false,
            "status": "ENABLED"
        },
        {
            "accountAlias": null,
            "accountId": "XXXXX",
            "accountName": "Spread bet",
            "accountType": "SPREADBET",
            "balance": {
                "available": 0.0,
                "balance": 0.0,
                "deposit": 0.0,
                "profitLoss": 0.0
            },
            "canTransferFrom": true,
            "canTransferTo": true,
            "currency": "GBP",
            "preferred": true,
            "status": "ENABLED"
        }
    ]
}
Returns

Dictionary with all accounts available on the platform as documented in Accounts API

Return type

dict

get_instrument(instrument: Union[str, pygindex.models.IGInstrument])pygindex.models.IGInstrument

Retrieve instrument details

For the description of all available fields and options please refer to IG Index Market documentation.

Example:

c = IGClient()
i = c.get_instrument("UA.D.AAPL.DAILY.IP")

The above query will return an instance of IGInstrument containing the following attributes:

  • IGInstrument.dealing_rules

  • IGInstrument.instrument

  • IGInstrument.snapshot

Dealing rules data example:

{
    "minStepDistance": {
        "unit": "POINTS",
        "value": 1.0
    },
    "minDealSize": {
        "unit": "POINTS",
        "value": 0.1
    },
    "minControlledRiskStopDistance": {
        "unit": "PERCENTAGE",
        "value": 5.0
    },
    "minNormalStopOrLimitDistance": {
        "unit": "POINTS",
        "value": 5.0
    },
    "maxStopOrLimitDistance": {
        "unit": "PERCENTAGE",
        "value": 90.0
    },
    "controlledRiskSpacing": {
        "unit": "POINTS",
        "value": 100.0
    },
    "marketOrderPreference": "AVAILABLE_DEFAULT_OFF"
}

Instrument data example:

{
    "epic": "UA.D.AAPL.DAILY.IP",
    "expiry": "DFB",
    "name": "Apple Inc (All Sessions)",
    "forceOpenAllowed": true,
    "stopsLimitsAllowed": true,
    "lotSize": 1.0,
    "unit": "AMOUNT",
    "type": "SHARES",
    "controlledRiskAllowed": true,
    "streamingPricesAvailable": false,
    "marketId": "AAPL-US",
    "currencies": [
        {
            "code": "$.",
            "name": "USD",
            "symbol": "$",
            "baseExchangeRate": 1.384415,
            "exchangeRate": 0.77,
            "isDefault": false
        },
        {
            "code": "#.",
            "name": "GBP",
            "symbol": "£",
            "baseExchangeRate": 1.0,
            "exchangeRate": 1.0,
            "isDefault": true
        }
    ],
    "marginDepositBands": [
        {
            "min": 0,
            "max": 324,
            "margin": 20
        },
        {
            "min": 324,
            "max": 1782,
            "margin": 20
        },
        {
            "min": 1782,
            "max": 5184,
            "margin": 40
        },
        {
            "min": 5184,
            "max": null,
            "margin": 75
        }
    ],
    "margin": 20.0,
    "slippageFactor": {
        "unit": "pct",
        "value": 100.0
    },
    "openingHours": {
        "marketTimes": [
            {
                "openTime": "09:00",
                "closeTime": "01:00"
            }
        ]
    },
    "expiryDetails": {
        "lastDealingDate": "06/04/29 21:00",
        "settlementInfo": "DFBs settle on the Last Dealing Day at the closing market bid/offer price
                           of the share, plus or minus half the IG spread. "
    },
    "rolloverDetails": null,
    "newsCode": "AAPL.O",
    "chartCode": "AAPL",
    "country": "US",
    "valueOfOnePip": null,
    "onePipMeans": null,
    "contractSize": null,
    "specialInfo": [
        "MIN KNOCK OUT LEVEL DISTANCE",
        "MAX KNOCK OUT LEVEL DISTANCE",
        "DEFAULT KNOCK OUT LEVEL DISTANCE",
        "Please note US (All Sessions) shares close early at 22:00 UK time on Friday evenings."
    ]
}

Snapshot data example:

{
    "marketStatus": "EDITS_ONLY",
    "netChange": -46,
    "percentageChange": -0.34,
    "updateTime": "21:59:15",
    "delayTime": 0,
    "bid": 13398.0,
    "offer": 13411.0,
    "high": 13498.0,
    "low": 13324.0,
    "binaryOdds": null,
    "decimalPlacesFactor": 1,
    "scalingFactor": 1,
    "controlledRiskExtraSpread": 0
}
Parameters

instrument

Instrument to retrieve. Possible options:

  • IG Index specific instrument identifier (EPIC) as str

  • Existing instrument data structure, IGInstrument

Returns

A fully populated instance of IGInstrument

Return type

IGInstrument

get_positions() → List[pygindex.models.IGPosition]

This method retrieves all positions for authenticated account from the API.

Example:

c = IGClient()
p = c.get_positions()

Positions details:

[
    IGPosition(raw_data={'position': {...}, 'market': {...}},
               instrument_name='UA.D.AAPL.DAILY.IP',
               instrument_text='Apple Inc (All Sessions)',
               sell=12257.0, buy=12267.0, high=12590.0, low=12221.0, change_net=-329.5, change_pct=-2.62,
               deal_size=0.1, open_level=13664.0,
               direction=<IGPositionDirection.BUY: 'BUY'>, position_open_ts='yyyy/mm/dd hh:mm:ss:000',
               deal_id='XXXXXXXXXXXXXXXX'),
    IGPosition(...),
    ...
]
Returns

List of IGPosition instances

Return type

list

get_prices(instrument: pygindex.models.IGInstrument, resolution: pygindex.models.IGPriceResolution = <IGPriceResolution.MINUTE: 'MINUTE'>, start_time: datetime.datetime = None, end_time: datetime.datetime = None, max_data_points: int = None)pygindex.models.IGInstrumentPrices

Retrieve historical data for the given instrument

Example:

c = IGClient()
i = c.get_instrument("UA.D.AAPL.DAILY.IP")
p = c.get_prices(i,
                 resolution=IGPriceResolution.HOUR_4,
                 start_time=datetime.now() - timedelta(days=1),
                 end_time=datetime.now())

Produces the following data:

Instrument type:

"SHARES"

Metadata:

{
    "response": {
        "allowance": {
            "remainingAllowance": 9881,
            "totalAllowance": 10000,
            "allowanceExpiry": 597200
        },
        "size": 4,
        "pageData": {
            "pageSize": 4,
            "pageNumber": 1,
            "totalPages": 1
        }
    }
}

Price data:

[
    {
        "snapshotTime": "2021/04/19 08:00:00",
        "snapshotTimeUTC": "2021-04-19T07:00:00",
        "openPrice": {
            "bid": 13315.0,
            "ask": 13444.0,
            "lastTraded": null
        },
        "closePrice": {
            "bid": 13391.0,
            "ask": 13412.0,
            "lastTraded": null
        },
        "highPrice": {
            "bid": 13437.0,
            "ask": 13448.0,
            "lastTraded": null
        },
        "lowPrice": {
            "bid": 13315.0,
            "ask": 13380.0,
            "lastTraded": null
        },
        "lastTradedVolume": 63705
    },
    {
        "snapshotTime": "2021/04/19 12:00:00",
        <...>
    },
    {
        "snapshotTime": "2021/04/19 16:00:00",
        <...>
    },
    {
        "snapshotTime": "2021/04/19 20:00:00",
        <...>
    }
]
Parameters
  • instrument (IGInstrument) – Instrument to get the price data for

  • resolution (IGPriceResolution) – Resolution of the price data

  • start_time (datetime.datetime) – Start time of the lookup date range

  • end_time (datetime.datetime) – End time of the lookup date range

  • max_data_points (int) – Maximum data points to fetch. This is ignored if date range is specified

Returns

Data structure that holds retrieved instrument prices

Return type

IGInstrumentPrices

get_session_details()dict

This method retrieves IG API specific session details.

Example:

c = IGClient()
s = c.get_session_details()

Session details:

{
  'clientId': 'XXXXXXXXX',
  'accountId': 'XXXXX',
  'timezoneOffset': 1,
  'locale': 'en_GB',
  'currency': 'GBP',
  'lightstreamerEndpoint': 'https://apd.marketdatasystems.com'
}
Returns

Dictionary with session details as documented in Session API

Return type

dict

open_position(instrument: pygindex.models.IGInstrument, direction: pygindex.models.IGPositionDirection, size: float = None)dict

This method opens a new position

Example:

c = IGClient(ig_auth, ig_api)
i = c.get_instrument("UA.D.AAPL.DAILY.IP")
r = c.open_position(i, IGPositionDirection.BUY, 0.5)

The result of this operation will be a deal reference code if successful:

{'dealReference': 'TV3XXXXXXXXXXXX'}
Parameters
  • instrument (IGInstrument) – Open position for specified instrument

  • direction (IGPositionDirection) – Direction of the position

  • size (float) – Size of the position

Returns

Confirmation ID of the operation or an error message from IG Index platform

search_markets(term)dict

Search for markets on IG Index platform that match specified criteria

Example:

c = IGClient()
m = c.search_markets("AAPL")

This search yields a list of all matching products:

{
    "markets": [
        {
            "epic": "UA.D.AAPL.DAILY.IP",
            "instrumentName": "Apple Inc (All Sessions)",
            "instrumentType": "SHARES",
            "expiry": "DFB",
            "high": 13498.0,
            "low": 13324.0,
            "percentageChange": -0.34,
            "netChange": -46.0,
            "updateTime": "04:50:07",
            "updateTimeUTC": "03:50:07",
            "bid": 13400.0,
            "offer": 13408.0,
            "delayTime": 0,
            "streamingPricesAvailable": false,
            "marketStatus": "EDITS_ONLY",
            "scalingFactor": 1
        },
        [...]
    ]
}
Parameters

term (str) – Search term

Returns

List of markets that matched search criteria