trading-ig Documentation

repository·master·Indexed 18 days ago

https://github.com/ig-python/trading-ig

A lightweight Python wrapper for the IG Markets API (version 0.0.24) that simplifies interaction with REST and Streaming endpoints for trading and data retrieval. It includes features for handling API rate limits via a built-in rate limiter or tenacity retries, support for v2 and v3 sessions, and optional pandas integration for time series data.

Tokens
13.2K
Snippets
46
Records
58
Agent score
60%

What's inside trading-ig

  1. Overview of trading-ig

    master

    trading-ig is a lightweight Python wrapper designed to simplify access to the IG Markets API. It provides programmatic access to both the IG REST and Streaming APIs, allowing developers to retrieve live and historical data, automate trades, and build custom trading applications.

    Important Note: This is not an official IG project. Use it at your own risk. For official API details and support, refer to the IG Labs website.

  2. Choose between v2 and v3 sessions

    master

    IG provides different session versions. Choosing the right one depends on your account type and requirements.

    • Simplicity: Easier to implement; tokens are extended automatically while in use.
    • Behavior: Uses your IG default account (e.g., Spread Bet or CFD). You can switch accounts using switch_account().
    • Best for: Most standard trading applications.

    v3 Sessions (OAuth-style)

    • Complexity: Tokens expire every 1 minute, requiring the library to manage refreshes automatically.
    • Behavior: You must specify the acc_number at the time of IGService creation.
    • Mandatory Use Case: If you use IG's L2 Dealer product (which requires your default account to be set to ISA, SIPP, etc.), you must use v3 sessions.

    How to connect with a v3 session

    To use v3, provide the acc_number and call create_session(version='3'):

    from trading_ig.rest import IGService
    from trading_ig.config import config
    
    ig_service = IGService(
        config.username,
        config.password,
        config.api_key,
        config.acc_type,
        acc_number=config.acc_number
    )
    ig_service.create_session(version='3')
    from trading_ig.rest import IGService
    from trading_ig.config import config
    
    ig_service = IGService(
            config.username,
            config.password,
            config.api_key,
            config.acc_type,
            acc_number=config.acc_number)
    ig_service.create_session(version='3')
  3. Understand optional dependencies (pandas, munch, tenacity)

    master

    The library uses optional dependencies in pyproject.toml to provide flexibility depending on your environment:

    • pandas: If pandas is installed, the library will automatically convert time series data (like historical price data or account activity) into a pandas.DataFrame. If not installed, it returns a standard Python dict.
    • munch: If munch is installed, market info for a given epic will be returned as a munch object. Otherwise, it returns a dict.
    • tenacity: This is used for handling IG rate limits via a retry mechanism. It is optional because while it works for non-latency-sensitive tasks (like nightly tests), it may not be suitable for high-speed trading applications.
  4. Install trading-ig

    master

    You can install the core library using pip. If you require advanced functionality like data manipulation with pandas, or specific utility libraries like munch and tenacity, you should install the package with the optional dependencies included.

    # Install core library
    $ pip install trading-ig
    
    # Install with all optional dependencies (pandas, munch, tenacity)
    $ pip install "trading-ig[pandas, munch, tenacity]"
  5. Enable logging for ig_trading

    master

    To view log messages from the ig_trading library, configure the standard Python logging module in your application. This is useful for debugging and monitoring the rate limiter's activity.

    import logging
    
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s %(levelname)s %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    logging.info("Log something")
    import logging
    
    logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s %(levelname)s %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
    
    logging.info("Log something")
  6. Cache API requests using requests-cache

    master

    To avoid redundant network calls, you can use requests-cache with IGService. You can apply a CachedSession either globally when initializing the service or specifically to individual method calls.

    Global Caching

    Pass a requests_cache.CachedSession instance to the IGService constructor. This will apply the caching policy to all requests made by that service instance.

    Per-method Caching

    Pass a session object as an argument to specific methods (e.g., fetch_historical_prices_by_epic_and_date_range) to cache only those specific calls.

    Cache Configuration

    • Use expire_after=timedelta(...) to set a specific expiration time.
    • Use expire_after=None to disable cache expiration.
    • Use expire_after=0 to prevent caching queries entirely.
    from datetime import datetime, timedelta
    import requests_cache
    from trading_ig import IGService
    
    # Create a cached session
    session = requests_cache.CachedSession(cache_name='cache', backend='sqlite', expire_after=timedelta(hours=1))
    
    # Option 1: Apply globally
    ig_service = IGService(username, password, api_key, acc_type, session)
    ig_service.create_session()
    
    # Option 2: Apply to a specific method call
    epic = 'CS.D.EURUSD.MINI.IP'
    resolution = 'D'
    start_date = '2014-12-15'
    end_date = '2014-12-20'
    response = ig_service.fetch_historical_prices_by_epic_and_date_range(epic, resolution, start_date, end_date, session)
  7. Configure trading-ig

    master

    You can configure your credentials using either a Python config file or environment variables.

    Using a Config File

    Copy trading_ig_config.default.py to trading_ig_config.py and populate the config class with your credentials:

    Using Environment Variables

    If the config file fails to load, IGService will look for these specific environment variables:

    • IG_SERVICE_USERNAME
    • IG_SERVICE_PASSWORD
    • IG_SERVICE_API_KEY
    • IG_SERVICE_ACC_NUMBER
    • IG_SERVICE_ACC_TYPE
    class config(object):
        username = "your_username"
        password = "your_password"
        api_key = "your_api_key"
        acc_type = "DEMO"
        acc_number = "your_account_number"
  8. How to use the IGService library

    master

    To interact with the IG Markets REST API, import the IGService class, instantiate it with your credentials, and call create_session(). The library provides methods for most API endpoints, such as switching accounts, fetching open positions, and retrieving historical prices. Many methods return pandas DataFrames, Series, or Panels.

    from trading_ig import IGService
    from trading_ig.config import config
    
    # Initialize and authenticate
    ig_service = IGService(config.username, config.password, config.api_key, config.acc_type)
    ig_service.create_session()
    
    # Switch to a specific account (optional)
    account_info = ig_service.switch_account(config.acc_number, False)
    print(account_info)
    
    # Fetch open positions
    open_positions = ig_service.fetch_open_positions()
    print("open_positions:\n%s" % open_positions)
    
    # Fetch historical prices
    epic = 'CS.D.EURUSD.MINI.IP'
    resolution = 'D'
    num_points = 10
    response = ig_service.fetch_historical_prices_by_epic_and_num_points(epic, resolution, num_points)
    df_ask = response['prices']['ask']
    print("ask prices:\n%s" % df_ask)
  9. Connect to the IG REST API

    master

    To interact with the REST API, instantiate IGService with your credentials and then call create_session() to get an active session object.

    from trading_ig.rest import IGService
    from trading_ig.config import config
    
    ig_service = IGService(config.username, config.password, config.api_key)
    ig = ig_service.create_session()
  10. Find a market epic

    master

    An 'epic' is a unique identifier for a market. You can find it using several methods:

    1. IGService.search_markets(): Use this method within the library to search for markets by name.
    2. IG API Companion: Use the Search Markets tool in the REST API Companion.
    3. Browser Developer Tools (Recommended):
      • Log in to the IG website.
      • Open your browser's Developer Tools (Network tab).
      • Navigate to the desired market.
      • Inspect the network requests. The epic is typically part of the URL. For example, in https://deal.ig.com/nwtpdeal/v2/markets/details/CS.D.USCGC.TODAY.IP?_=1626527237228, the epic is CS.D.USCGC.TODAY.IP.
    4. Navigation Tree: You can use fetch_top_level_navigation_nodes() and fetch_sub_nodes_by_node() to traverse the market tree, though this is slow due to rate limits.
  11. Configure IGService credentials

    master

    You can configure the library using a Python configuration object or environment variables.

    Using a Python config object

    Create a trading_ig_config.py file with a config class containing your credentials:

    class config(object):
        username = "YOUR_USERNAME"
        password = "YOUR_PASSWORD"
        api_key = "YOUR_API_KEY"
        acc_type = "DEMO" # Use "LIVE" or "DEMO"
        acc_number = "ABC123"

    Using Environment Variables

    Alternatively, set the following environment variables:

    export IG_SERVICE_USERNAME="..."
    export IG_SERVICE_PASSWORD="..."
    export IG_SERVICE_API_KEY="..."
    export IG_SERVICE_ACC_TYPE="DEMO" # LIVE or DEMO
    export IG_SERVICE_ACC_NUMBER="..."
    class config(object):
        username = "YOUR_USERNAME"
        password = "YOUR_PASSWORD"
        api_key = "YOUR_API_KEY"
        acc_type = "DEMO" # LIVE / DEMO
        acc_number = "ABC123"