### Install trading-ig with pip Source: https://github.com/ig-python/trading-ig/blob/master/README.rst Standard installation using pip. This installs the core library. ```bash pip install trading-ig ``` -------------------------------- ### Install trading-ig Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Install the library using pip. Use the optional dependencies for pandas, munch, and tenacity. ```bash $ pip install trading-ig ``` ```bash $ pip install "trading-ig[pandas, munch, tenacity]" ``` -------------------------------- ### Install trading-ig with optional dependencies Source: https://github.com/ig-python/trading-ig/blob/master/README.rst Installation including optional dependencies for enhanced functionality. Use this if you need features that rely on pandas, munch, or tenacity. ```bash pip install "trading-ig[pandas, munch, tenacity]" ``` -------------------------------- ### IGStreamService - Real-time Data Streaming with Lightstreamer Source: https://context7.com/ig-python/trading-ig/llms.txt Use IGStreamService to create raw Subscription objects for live data like prices, account info, or trade updates. Register listener classes to process incoming data. Ensure the Lightstreamer client library is installed. ```python import sys import logging from datetime import datetime from lightstreamer.client import Subscription, SubscriptionListener, ItemUpdate, ClientListener from trading_ig import IGService, IGStreamService from trading_ig.config import config logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s") class PriceListener(SubscriptionListener): def onItemUpdate(self, update: ItemUpdate): ts = datetime.fromtimestamp(int(update.getValue("TIMESTAMP")) / 1000) print( f"{ts.strftime('%H:%M:%S')} | {update.getItemName()} | " f"Bid: {update.getValue('BIDPRICE1')} | Ask: {update.getValue('ASKPRICE1')} | " f"Change: {update.getValue('NET_CHG_')}%" ) class AccountListener(SubscriptionListener): def onItemUpdate(self, update: ItemUpdate): print(f"Funds: {update.getValue('FUNDS')}, Equity: {update.getValue('EQUITY')}") class StatusListener(ClientListener): def onStatusChange(self, status): print(f"{datetime.now()}: ***** {status} *****") # Set up services ig_service = IGService( config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number, ) ig_stream = IGStreamService(ig_service) ig_stream.create_session() # or version="3" for OAuth # Subscribe to live prices (MERGE mode) price_sub = Subscription( mode="MERGE", items=[f"PRICE:{config.acc_number}:CS.D.BITCOIN.TODAY.IP"], fields=["TIMESTAMP", "BIDPRICE1", "ASKPRICE1", "NET_CHG_", "HIGH", "LOW"], ) price_sub.setDataAdapter("Pricing") price_sub.addListener(PriceListener()) ig_stream.subscribe(price_sub) # Subscribe to account balance updates acct_sub = Subscription( mode="MERGE", items=[f"ACCOUNT:{config.acc_number}"], fields=["FUNDS", "MARGIN", "AVAILABLE_TO_DEAL", "PNL", "EQUITY", "EQUITY_USED"], ) acct_sub.addListener(AccountListener()) ig_stream.subscribe(acct_sub) # Subscribe to trade confirmations (DISTINCT mode) trade_sub = Subscription( mode="DISTINCT", items=[f"TRADE:{config.acc_number}"], fields=["CONFIRMS", "OPU", "WOU"], ) ig_stream.subscribe(trade_sub) # Monitor connection status ig_stream.add_client_listener(StatusListener()) # ... receive updates for as long as needed ... ig_stream.disconnect() ``` -------------------------------- ### Format code with ruff Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Use this command to format your Python code according to project standards. Ensure ruff is installed. ```bash $ uv run ruff format ``` -------------------------------- ### Initialize IGService with Tenacity for Rate Limiting Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Configure IGService to automatically retry requests that exceed API rate limits using the tenacity library. This setup waits exponentially between retries for ApiExceededException. ```python from trading_ig.rest import IGService, ApiExceededException from tenacity import Retrying, wait_exponential, retry_if_exception_type retryer = Retrying(wait=wait_exponential(), retry=retry_if_exception_type(ApiExceededException)) ig_service = IGService('username', 'password', 'api_key', retryer=retryer) ``` -------------------------------- ### Fetch Account Activity Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Retrieve account activity history starting from a specified date. ```python >>> from_date = datetime(2021, 1, 1) >>> activities = ig_service.fetch_account_activity(from_date=from_date) >>> activities ``` -------------------------------- ### Get Historical Prices Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Fetch historical price data for a given market epic. ```python >>> result = ig_service.fetch_historical_prices_by_epic(epic='CS.D.USCGC.TODAY.IP') >>> result['prices'] ``` -------------------------------- ### Extract Market Epic from URL Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md This example shows how to identify a market's epic from a URL. The epic is a key identifier for markets in the IG API. ```default https://deal.ig.com/nwtpdeal/v2/markets/details/CS.D.USCGC.TODAY.IP?_=1626527237228 ``` -------------------------------- ### Set up Streaming API Connection Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Initialize IGService and IGStreamService, create a session, and set up a subscription for market data. ```python >>> from trading_ig import IGService, IGStreamService >>> from trading_ig.config import config >>> from trading_ig.lightstreamer import Subscription ``` ```python >>> def on_update(item): >>> print("{UPDATE_TIME:<8} {stock_name:<19} Bid {BID:>5} Ask {OFFER:>5}".format(stock_name=item["name"], **item["values"])) ``` ```python >>> ig_service = IGService(config.username, config.password, config.api_key, config.acc_type, acc_number=config.acc_number) >>> ig_stream_service = IGStreamService(ig_service) >>> ig_stream_service.create_session() >>> sub = Subscription(mode="MERGE", items=["L1:CS.D.GBPUSD.TODAY.IP"], fields=["UPDATE_TIME", "BID", "OFFER"]) >>> sub.addlistener(on_update) >>> ig_stream_service.ls_client.subscribe(sub) >>> ig_stream_service.disconnect() ``` -------------------------------- ### Run Streaming API Sample Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/stream.md Execute the sample script to connect to the streaming API and receive real-time market data. The output shows connection details and streaming price updates. ```bash $ python sample/stream_ig.py INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): demo-api.ig.com INFO:ig_stream:Starting connection with https://demo-apd.marketdatasystems.com L1:CS.D.USDJPY.CFD.IP: Time 20:35:43 - Bid 119.870 - Ask 119.885 L1:CS.D.GBPUSD.CFD.IP: Time 20:35:46 - Bid 1.51270 - Ask 1.51290 ----------HIT CR TO UNSUBSCRIBE AND DISCONNECT FROM LIGHTSTREAMER----------- L1:CS.D.USDJPY.CFD.IP: Time 20:35:43 - Bid 119.870 - Ask 119.885 L1:CS.D.USDJPY.CFD.IP: Time 20:35:48 - Bid 119.871 - Ask 119.886 L1:CS.D.GBPUSD.CFD.IP: Time 20:35:48 - Bid 1.51271 - Ask 1.51291 L1:CS.D.USDJPY.CFD.IP: Time 20:35:48 - Bid 119.870 - Ask 119.885 L1:CS.D.GBPUSD.CFD.IP: Time 20:35:49 - Bid 1.51270 - Ask 1.51290 INFO:lightstreamer:Unsubscribed successfully WARNING:lightstreamer:Server error DISCONNECTED FROM LIGHTSTREAMER ``` -------------------------------- ### Configure with a config file Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Create a `trading_ig_config.py` file and copy the template. Update the variables with your credentials. ```python class config(object): username = "your_username" password = "your_password" api_key = "your_api_key" acc_type = "DEMO" acc_number = "your_account_number" ``` -------------------------------- ### Run Streaming API Sample Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Execute the streaming API sample script from the project root. ```bash $ python sample/stream_ig.py ``` -------------------------------- ### Run REST API Sample Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Execute the REST API sample script from the project root. ```bash $ python sample/rest_ig.py ``` -------------------------------- ### Initialize IGService and Create Session Source: https://github.com/ig-python/trading-ig/blob/master/sample/rest.ipynb Initializes the IGService with configuration details and creates a v2 session. A v3 session can be created by uncommenting the relevant line. ```python from trading_ig.rest import IGService from trading_ig.config import config service = IGService( config.username, config.password, config.api_key, config.acc_type, acc_number=config.acc_number, ) # creating a v2 session service.create_session() # creating a v3 session # service.create_session(version="3") ``` -------------------------------- ### IGService - Creating a Session Source: https://context7.com/ig-python/trading-ig/llms.txt Demonstrates how to instantiate the IGService client and create authenticated sessions using different authentication methods (v2, v3 OAuth, encrypted password). Includes session logout. ```APIDOC ## IGService - Creating a Session `IGService` is the primary REST client. Instantiate it with credentials and call `create_session()` to authenticate. Sessions can be v2 (default, CST/security token) or v3 (OAuth tokens that auto-refresh). The optional `use_rate_limiter=True` flag enables a built-in leaky-bucket rate limiter that respects IG's published per-minute allowances. ```python from trading_ig import IGService from trading_ig.config import config # Standard v2 session (demo account) ig = IGService( config.username, config.password, config.api_key, acc_type="DEMO", # "LIVE" for production acc_number=config.acc_number, use_rate_limiter=True, # optional built-in rate limiter ) ig.create_session() # authenticates; stores CST/X-SECURITY-TOKEN # v3 OAuth session (requires acc_number) ig3 = IGService( config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number, ) ig3.create_session(version="3") # tokens auto-refresh; 60-second validity managed internally # Encrypted password login (some regions require this) ig_enc = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig_enc.create_session(encryption=True) ig.logout() # close the session explicitly ``` ``` -------------------------------- ### Configuration Options for trading-ig Source: https://context7.com/ig-python/trading-ig/llms.txt Demonstrates two methods for providing credentials: a Python configuration file or environment variables. The config file approach uses a class, while environment variables are suitable for CI/CD. ```python # trading_ig_config.py (copy from trading_ig_config.default.py) class config(object): username = "your_ig_username" password = "your_ig_password" api_key = "your_api_key" acc_type = "DEMO" # or "LIVE" acc_number = "ABC123" ``` ```bash # Alternative: environment variables export IG_SERVICE_USERNAME="your_ig_username" export IG_SERVICE_PASSWORD="your_ig_password" export IG_SERVICE_API_KEY="your_api_key" export IG_SERVICE_ACC_TYPE="DEMO" export IG_SERVICE_ACC_NUMBER="ABC123" ``` -------------------------------- ### Configure with environment variables Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Set environment variables for authentication details if the config file is not found. ```bash $ export IG_SERVICE_USERNAME="your_username" $ export IG_SERVICE_PASSWORD="your_password" $ export IG_SERVICE_API_KEY="your_api_key" $ export IG_SERVICE_ACC_NUMBER="your_account_number" $ export IG_SERVICE_ACC_TYPE="your_acc_type" ``` -------------------------------- ### Fetch and Manage Open Positions Source: https://context7.com/ig-python/trading-ig/llms.txt Demonstrates fetching all open positions, creating a new market position, updating an existing position's stop/limit levels, and closing a position. Ensure correct parameters for each operation. ```python positions = ig.fetch_open_positions() print(positions[["dealId", "epic", "direction", "size", "level", "bid", "offer"]]) ``` ```python confirmation = ig.create_open_position( currency_code="GBP", direction="BUY", epic="CS.D.USCGC.TODAY.IP", expiry="DFB", force_open=False, guaranteed_stop=False, level=None, limit_distance=None, limit_level=None, order_type="MARKET", quote_id=None, size=0.5, stop_distance=50, stop_level=None, trailing_stop=False, trailing_stop_increment=None, ) deal_id = confirmation["dealId"] print(f"Opened position: {deal_id}, status: {confirmation['dealStatus']}") ``` ```python update = ig.update_open_position( limit_level=1900.0, stop_level=1750.0, deal_id=deal_id, guaranteed_stop=False, trailing_stop=False, ) print(update["dealStatus"]) ``` ```python close = ig.close_open_position( deal_id=deal_id, direction="SELL", # opposite of opening direction epic="CS.D.USCGC.TODAY.IP", expiry="DFB", level=None, order_type="MARKET", quote_id=None, size=0.5, ) print(close["dealStatus"]) # 'ACCEPTED' ``` -------------------------------- ### Connect and Fetch Data with IGService Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/rest.md Demonstrates connecting to the IG API, switching accounts, retrieving open positions, and fetching historical price data. Requires configuration details for authentication. ```python from trading_ig import IGService from trading_ig.config import config ig_service = IGService(config.username, config.password, config.api_key, config.acc_type) ig_service.create_session() account_info = ig_service.switch_account(config.acc_number, False) # not necessary print(account_info) open_positions = ig_service.fetch_open_positions() print("open_positions:\n%s" % open_positions) print("") 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) ``` -------------------------------- ### Establish REST API Connection Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Create an IGService instance and establish a session using your credentials. ```python >>> 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() >>> ig ``` -------------------------------- ### Session Creation Source: https://github.com/ig-python/trading-ig/blob/master/sample/rest.ipynb Demonstrates how to create a session using the IGService. Supports v2 (default) and v3 sessions. ```APIDOC ## Session Creation ### Description Creates a session with the IG service. By default, it uses v2 of the session API. You can specify `version='3'` to use v3. ### Method `IGService.create_session(version='2')` ### Parameters * **version** (str) - Optional - The version of the session API to use (e.g., '2' or '3'). Defaults to '2'. ### Request Example ```python from trading_ig.rest import IGService from trading_ig.config import config service = IGService( config.username, config.password, config.api_key, config.acc_type, acc_number=config.acc_number, ) # Creating a v2 session (default) service.create_session() # Creating a v3 session # service.create_session(version="3") ``` ``` -------------------------------- ### Manage Watchlists Source: https://context7.com/ig-python/trading-ig/llms.txt Demonstrates fetching all watchlists, creating a new watchlist with specified epics, retrieving markets within a watchlist, adding/removing markets, and deleting a watchlist. Ensure watchlist IDs and epics are correct. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() # All watchlists wls = ig.fetch_all_watchlists() print(wls[["id", "name", "editable", "defaultSystemWatchlist"]]) ``` ```python # Create a new watchlist new = ig.create_watchlist( name="My Watchlist", epics=["CS.D.EURUSD.MINI.IP", "IX.D.FTSE.IFM.IP"], ) watchlist_id = new["watchlistId"] ``` ```python # Markets in a watchlist markets = ig.fetch_watchlist_markets(watchlist_id) print(markets[["epic", "instrumentName", "bid", "offer"]]) ``` ```python # Add/remove a market ig.add_market_to_watchlist(watchlist_id, "CS.D.GBPUSD.MINI.IP") ig.remove_market_from_watchlist(watchlist_id, "CS.D.GBPUSD.MINI.IP") ``` ```python # Delete watchlist ig.delete_watchlist(watchlist_id) ``` -------------------------------- ### Configure Logging Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Set up basic logging to view informational messages from the ig_trading library. Ensure logging level is set to INFO or lower to capture messages. ```python 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") ``` -------------------------------- ### IGService Configuration via Environment Variables Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/rest.md Sets IGService configuration parameters using environment variables. Ensure these variables are exported before running your script. ```bash export IG_SERVICE_USERNAME="..." export IG_SERVICE_PASSWORD="..." export IG_SERVICE_API_KEY="..." export IG_SERVICE_ACC_TYPE="DEMO" # LIVE / DEMO export IG_SERVICE_ACC_NUMBER="..." ``` -------------------------------- ### Initialize IGService with Rate Limiter and Tenacity Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Enable the built-in rate limiter in IGService and configure it with tenacity for automatic retries on rate limit exceptions. This approach queries API limits upon session creation. ```python from trading_ig.rest import IGService, ApiExceededException from tenacity import Retrying, wait_exponential, retry_if_exception_type retryer = Retrying(wait=wait_exponential(), retry=retry_if_exception_type(ApiExceededException)) ig_service = IGService('username', 'password', 'api_key', retryer=retryer, use_rate_limiter=True) ``` -------------------------------- ### Create a v3 session with IGService Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Connect to IG using a v3 session, specifying the account number. This is required for certain account types or when using L2 Dealer. ```python >>> 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') ``` -------------------------------- ### Create, Update, and Delete Working Orders Source: https://context7.com/ig-python/trading-ig/llms.txt Shows how to list, create, update, and delete limit/stop OTC working orders. Ensure correct 'orderType', 'timeInForce', and date parameters are used. ```python from datetime import datetime from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() # List working orders orders = ig.fetch_working_orders() print(orders[["dealId", "epic", "direction", "orderLevel", "orderSize", "orderType"]]) ``` ```python # Create a limit working order conf = ig.create_working_order( currency_code="GBP", direction="BUY", epic="CS.D.USCGC.TODAY.IP", expiry="DFB", guaranteed_stop=False, level=1800.0, # trigger price size=0.5, time_in_force="GOOD_TILL_CANCELLED", order_type="LIMIT", stop_distance=50, limit_distance=100, good_till_date=datetime(2024, 12, 31), ) deal_id = conf["dealId"] ``` ```python # Update the order ig.update_working_order( good_till_date=None, level=1810.0, limit_distance=120, limit_level=None, stop_distance=40, stop_level=None, guaranteed_stop=False, time_in_force="GOOD_TILL_CANCELLED", order_type="LIMIT", deal_id=deal_id, ) ``` ```python # Delete the order ig.delete_working_order(deal_id) ``` -------------------------------- ### Create IGService Session Source: https://context7.com/ig-python/trading-ig/llms.txt Instantiate IGService with credentials and create a session. Supports standard v2 sessions, v3 OAuth sessions with auto-refreshing tokens, and encrypted password logins. An optional rate limiter can be enabled. ```python from trading_ig import IGService from trading_ig.config import config # Standard v2 session (demo account) ig = IGService( config.username, config.password, config.api_key, acc_type="DEMO", # "LIVE" for production acc_number=config.acc_number, use_rate_limiter=True, # optional built-in rate limiter ) ig.create_session() # authenticates; stores CST/X-SECURITY-TOKEN # v3 OAuth session (requires acc_number) ig3 = IGService( config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number, ) ig3.create_session(version="3") # tokens auto-refresh; 60-second validity managed internally # Encrypted password login (some regions require this) ig_enc = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig_enc.create_session(encryption=True) ig.logout() # close the session explicitly ``` -------------------------------- ### Open a Market Position Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Create an open position for a market with specified parameters like currency, direction, size, and order type. ```python >>> resp = ig_service.create_open_position( currency_code='GBP', direction='BUY', epic='CS.D.USCGC.TODAY.IP', order_type='MARKET', expiry='DFB', force_open='false', guaranteed_stop='false', size=0.5, level=None, limit_distance=None, limit_level=None, quote_id=None, stop_level=None, stop_distance=None, trailing_stop=None, trailing_stop_increment=None) >>> resp ``` -------------------------------- ### IGService Configuration via Python Class Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/rest.md Defines configuration parameters for the IGService within a Python class. Replace placeholder values with your actual credentials. ```python class config(object): username = "YOUR_USERNAME" password = "YOUR_PASSWORD" api_key = "YOUR_API_KEY" acc_type = "DEMO" # LIVE / DEMO acc_number = "ABC123" ``` -------------------------------- ### Fetch and Update Account Preferences Source: https://context7.com/ig-python/trading-ig/llms.txt Retrieves all accounts associated with the authenticated client, returning them as a pandas DataFrame. Also demonstrates fetching and updating account preferences. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() accounts = ig.fetch_accounts() print(accounts[["accountId", "accountName", "accountType", "currency", "balance", "available"]]) # Expected output (DataFrame): # accountId accountName accountType currency balance available # 0 ABC123 Demo-CFD CFD GBP 10000.0 9500.0 prefs = ig.fetch_account_preferences() print(prefs) # {'trailingStopsEnabled': False, 'dealingEnabled': True, 'hasActiveDemoAccounts': True, ...} status = ig.update_account_preferences(trailing_stops_enabled=True) print(status) # 'SUCCESS' ``` -------------------------------- ### Fetch Accounts Source: https://github.com/ig-python/trading-ig/blob/master/sample/rest.ipynb Fetches account information using the initialized IGService. Ensure a session has been successfully created prior to calling this. ```python service.fetch_accounts() ``` -------------------------------- ### Configure Client App Rate Limiting Source: https://context7.com/ig-python/trading-ig/llms.txt Shows how to enable and configure the built-in leaky-bucket rate limiter for API requests. This helps pace requests within IG's published limits. Ensure 'use_rate_limiter' is set to True during IGService instantiation. ```python from trading_ig import IGService from trading_ig.config import config # Enable rate limiter at construction time ig = IGService( config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number, use_rate_limiter=True, ) ig.create_session() # automatically calls setup_rate_limiter() after login ``` ```python # Inspect app allowances apps = ig.get_client_apps() for app in apps: print(app["apiKey"], app["allowanceAccountOverall"], app["allowanceAccountTrading"]) ``` ```python # Update app configuration ig.update_client_app( allowance_account_overall=30, allowance_account_trading=10, api_key=config.api_key, status="ENABLED", ) ``` ```python # Disable the API key (re-enable via IG web platform) ig.disable_client_app_key() ``` -------------------------------- ### Client App / Rate Limiting Source: https://context7.com/ig-python/trading-ig/llms.txt Inspect API key allowances and configure the built-in rate limiter. ```APIDOC ## IGService — Client App / Rate Limiting Inspect API key allowances and optionally configure the built-in leaky-bucket rate limiter, which uses background threads to pace requests within IG's published limits. ```python from trading_ig import IGService from trading_ig.config import config # Enable rate limiter at construction time ig = IGService( config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number, use_rate_limiter=True, ) ig.create_session() # automatically calls setup_rate_limiter() after login # Inspect app allowances apps = ig.get_client_apps() for app in apps: print(app["apiKey"], app["allowanceAccountOverall"], app["allowanceAccountTrading"]) # Update app configuration ig.update_client_app( allowance_account_overall=30, allowance_account_trading=10, api_key=config.api_key, status="ENABLED", ) # Disable the API key (re-enable via IG web platform) ig.disable_client_app_key() ``` ``` -------------------------------- ### Manage Positions Source: https://context7.com/ig-python/trading-ig/llms.txt Provides functionality to list, open, update, and close OTC positions. Requires session creation. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() ``` -------------------------------- ### Manage IG Service Sessions and Accounts Source: https://context7.com/ig-python/trading-ig/llms.txt Demonstrates advanced session management including reading session state, switching between accounts, and manually refreshing v3 sessions. Ensure to logout when finished to close the HTTP session. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService( config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number, ) ig.create_session(version="2") # Read current session details session_info = ig.read_session(fetch_session_tokens="true") print(session_info["accountType"], session_info["currentAccountId"]) # Switch to a different account ig.switch_account(account_id="XYZ789", default_account=False) # Check repeat dealing window (prevent rapid re-dealing on same epic) rdw = ig.fetch_repeat_dealing_window(epic="CS.D.USCGC.TODAY.IP") print(rdw) # v3 session refresh (normally handled automatically by _check_session()) ig3 = IGService(config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number) ig3.create_session(version="3") status_code = ig3.refresh_session() # returns 200 on success ig.logout() # closes HTTP session and stops rate-limiter threads ``` -------------------------------- ### IGService Market Navigation Source: https://context7.com/ig-python/trading-ig/llms.txt Navigates the IG market hierarchy, fetching top-level categories, sub-nodes, and client sentiment for instruments. Requires session creation. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() # Get top-level categories top = ig.fetch_top_level_navigation_nodes() print(top["nodes"]) print(top["markets"]) # Drill into a specific node sub = ig.fetch_sub_nodes_by_node("264134") print(sub["nodes"]) print(sub["markets"]) # Client sentiment sentiment = ig.fetch_client_sentiment_by_instrument("EURUSD") print(sentiment) # Multiple instruments multi = ig.fetch_client_sentiment_by_instrument(["EURUSD", "GBPUSD"]) ``` -------------------------------- ### IGService.fetch_accounts Source: https://context7.com/ig-python/trading-ig/llms.txt Retrieves all accounts associated with the authenticated client, returning account details such as balances, type, and currency as a pandas DataFrame. Also shows how to fetch and update account preferences. ```APIDOC ## IGService.fetch_accounts Returns all accounts belonging to the authenticated client as a pandas DataFrame with columns for balances, account type, currency, and preferences. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() accounts = ig.fetch_accounts() print(accounts[["accountId", "accountName", "accountType", "currency", "balance", "available"]]) # Expected output (DataFrame): # accountId accountName accountType currency balance available # 0 ABC123 Demo-CFD CFD GBP 10000.0 9500.0 prefs = ig.fetch_account_preferences() print(prefs) # {'trailingStopsEnabled': False, 'dealingEnabled': True, 'hasActiveDemoAccounts': True, ...} status = ig.update_account_preferences(trailing_stops_enabled=True) print(status) # 'SUCCESS' ``` ``` -------------------------------- ### Fetch Account Activity Source: https://github.com/ig-python/trading-ig/blob/master/sample/rest.ipynb Fetches account activity for a given date range. This version retrieves non-detailed activity. ```python from datetime import datetime, timedelta to_date = datetime.now() from_date = to_date - timedelta(days=7) service.fetch_account_activity(from_date=from_date, to_date=to_date) ``` -------------------------------- ### Fetch Historical Prices with Different Formats Source: https://context7.com/ig-python/trading-ig/llms.txt Fetches historical price data for a given epic with different format options. Use 'flat_prices' for single-level columns and 'mid_prices' for Open/High/Low/Close as mid-price. ```python flat = ig.fetch_historical_prices_by_epic( "CS.D.EURUSD.MINI.IP", resolution="D", numpoints=10, format=ig.flat_prices, ) print(flat["prices"][["open.bid", "close.ask", "volume"]]) ``` ```python mid = ig.fetch_historical_prices_by_epic( "CS.D.EURUSD.MINI.IP", resolution="D", numpoints=10, format=ig.mid_prices, ) print(mid["prices"][[ "Open", "High", "Low", "Close", "Volume"]]) ``` -------------------------------- ### Fetch Historical Prices Source: https://context7.com/ig-python/trading-ig/llms.txt Demonstrates fetching historical prices with different formatting options (flat and mid-price). ```APIDOC ## Fetch Historical Prices ### Description Fetches historical price data for a given epic, with options for different output formats. ### Method `ig.fetch_historical_prices_by_epic(epic: str, resolution: str, numpoints: int, format: str)` ### Parameters - **epic** (str) - The epic identifier for the market. - **resolution** (str) - The resolution of the historical data (e.g., 'D' for daily). - **numpoints** (int) - The number of data points to retrieve. - **format** (str) - The desired output format (e.g., `ig.flat_prices`, `ig.mid_prices`). ### Request Example ```python # Fetching flat prices flat = ig.fetch_historical_prices_by_epic( "CS.D.EURUSD.MINI.IP", resolution="D", numpoints=10, format=ig.flat_prices, ) print(flat["prices"][["open.bid", "close.ask", "volume"]]) # Fetching mid prices mid = ig.fetch_historical_prices_by_epic( "CS.D.EURUSD.MINI.IP", resolution="D", numpoints=10, format=ig.mid_prices, ) print(mid["prices"][["Open", "High", "Low", "Close", "Volume"]]) ``` ### Response Returns a dictionary containing historical price data. The structure depends on the `format` parameter. #### Success Response (200) - **prices** (DataFrame/dict) - Contains the historical price data. ``` -------------------------------- ### Lint code with ruff Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Run ruff to check for code style and potential errors in your project files. Specify target directories as needed. ```bash $ uv run ruff check trading_ig docs sample tests ``` -------------------------------- ### Fetch Detailed Account Activity Source: https://github.com/ig-python/trading-ig/blob/master/sample/rest.ipynb Fetches detailed account activity for a given date range. Set 'detailed=True' to retrieve more granular information. ```python from datetime import datetime, timedelta to_date = datetime.now() from_date = to_date - timedelta(days=7) service.fetch_account_activity(from_date=from_date, to_date=to_date, detailed=True) ``` -------------------------------- ### Create Open Position with Correct Expiry for Spread Bet Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Demonstrates how to correctly set the 'expiry' parameter when creating an open position for a spread bet to avoid the REJECT_CFD_ORDER_ON_SPREADBET_ACCOUNT error. Use 'DFB' for spread bets. ```python resp = ig_service.create_open_position( currency_code='GBP', direction='BUY', epic='CS.D.USCGC.TODAY.IP', order_type='MARKET', expiry='DFB', force_open='false', ...) ``` -------------------------------- ### Fetch Account Activity Source: https://context7.com/ig-python/trading-ig/llms.txt Fetches account activity, optionally filtering by deal ID or using v2 with a maximum span in seconds. ```python single = ig.fetch_account_activity(deal_id="ABCDE12345") ``` ```python recent = ig.fetch_account_activity_v2(max_span_seconds=3600, page_size=20) ``` -------------------------------- ### Run all tests with pytest Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Execute all tests, including unit and integration tests, using pytest. This command may take a significant amount of time. ```bash $ uv run pytest ``` -------------------------------- ### Search Markets and Fetch Market Details Source: https://context7.com/ig-python/trading-ig/llms.txt Searches for tradeable markets by name or retrieves full instrument details for a specific epic. Supports fetching multiple epics at once. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() # Search by name → DataFrame of matching markets results = ig.search_markets("gold") print(results[["epic", "instrumentName", "instrumentType", "bid", "offer"]]) # Full details for a specific epic (v3, returns Munch if munch is installed) market = ig.fetch_market_by_epic("CS.D.USCGC.TODAY.IP") print(market.instrumentDetails.marketId) # dot-access with munch print(market.snapshot.bid) # Multiple epics at once details = ig.fetch_markets_by_epics("CS.D.EURUSD.MINI.IP,IX.D.ASX.IFM.IP", detailed=True) for d in details: print(d["instrument"]["epic"], d["snapshot"]["bid"]) ``` -------------------------------- ### IGService - Price Formatting Utilities Source: https://context7.com/ig-python/trading-ig/llms.txt Use the format_prices helper method on IGService to transform raw historical price JSON into DataFrames with hierarchical MultiIndex columns for bid, ask, spread, and last prices. This is passed as the 'format' parameter. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() # format_prices: hierarchical MultiIndex columns (bid/ask/spread/last) result = ig.fetch_historical_prices_by_epic( "CS.D.EURUSD.MINI.IP", resolution="1H", numpoints=20, format=ig.format_prices, ) df = result["prices"] print(df["bid"]["Close"].tail(5)) # bid close prices print(df["ask"]["Open"].tail(5)) # ask open prices ``` -------------------------------- ### Session Management and Switch Account Source: https://context7.com/ig-python/trading-ig/llms.txt Provides utilities for managing trading sessions, switching between accounts, and handling session tokens. ```APIDOC ## Session Management and Switch Account ### Description Advanced session utilities for managing trading sessions, including reading session state, switching accounts, and manually refreshing v3 session tokens. ### Methods - `ig.read_session(fetch_session_tokens: str)` - `ig.switch_account(account_id: str, default_account: bool)` - `ig.fetch_repeat_dealing_window(epic: str)` - `ig3.refresh_session()` - `ig.logout()` ### Parameters - **fetch_session_tokens** (str) - If 'true', fetches session tokens. - **account_id** (str) - The ID of the account to switch to. - **default_account** (bool) - Whether to set the switched account as the default. - **epic** (str) - The epic identifier for which to fetch the repeat dealing window. ### Request Example ```python from trading_ig import IGService from trading_ig.config import config ig = IGService( config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number, ) ig.create_session(version="2") # Read current session details session_info = ig.read_session(fetch_session_tokens="true") print(session_info["accountType"], session_info["currentAccountId"]) # Switch to a different account ig.switch_account(account_id="XYZ789", default_account=False) # Check repeat dealing window rdw = ig.fetch_repeat_dealing_window(epic="CS.D.USCGC.TODAY.IP") print(rdw) # v3 session refresh ig3 = IGService(config.username, config.password, config.api_key, acc_type="DEMO", acc_number=config.acc_number) ig3.create_session(version="3") status_code = ig3.refresh_session() # returns 200 on success ig.logout() # closes HTTP session and stops rate-limiter threads ``` ### Response - `read_session`: Returns session details including account type and ID. - `switch_account`: Switches the active account for the session. - `fetch_repeat_dealing_window`: Returns information about the repeat dealing window. - `refresh_session`: Returns a status code (200 on success) for v3 session refresh. - `logout`: Closes the HTTP session. ``` -------------------------------- ### Query Rate Limits Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Call IGService.get_client_apps() to query the rate limits associated with your API key. This method is used when a new IGService object is created with use_rate_limiter set to True. ```python IGService.get_client_apps() ``` -------------------------------- ### Search for Markets Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Use `search_markets` to find trading instruments by keyword. ```python >>> results = ig_service.search_markets("gold") >>> results ``` -------------------------------- ### Run unit tests with pytest Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/faq.md Execute unit tests using pytest, excluding integration tests. This is useful for quick feedback during development. ```bash $ uv run pytest --ignore=tests/test_integration.py ``` -------------------------------- ### IGService.fetch_account_activity Source: https://context7.com/ig-python/trading-ig/llms.txt Fetches paginated account activity history using the v3 endpoint. It automatically retrieves all pages and consolidates them into a single DataFrame. Supports filtering by date range, deal ID, and FIQL expressions. ```APIDOC ## IGService.fetch_account_activity Returns paginated account activity history (v3 endpoint). Automatically fetches all pages and returns a single combined DataFrame. Supports filtering by date range, deal ID, and FIQL filter expressions. ```python from datetime import datetime from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() activities = ig.fetch_account_activity( from_date=datetime(2024, 1, 1), to_date=datetime(2024, 3, 31), detailed=True, # include detailed action breakdown page_size=50, ) print(activities.head()) # Returns DataFrame with columns: date, epic, type, status, description, # marketName, size, direction, level, stopLevel, limitLevel, ... ``` ``` -------------------------------- ### IGService — Positions Source: https://context7.com/ig-python/trading-ig/llms.txt Manage open OTC (over-the-counter) positions: list all open positions, open a new position, update stop/limit levels, or close an existing position. ```APIDOC ## IGService — Positions Manage open OTC (over-the-counter) positions: list all open positions, open a new position, update stop/limit levels, or close an existing position. ### Methods * `list_open_positions()`: Lists all currently open positions. * `open_position(...)`: Opens a new position (details of parameters not provided in source). * `update_level(...)`: Updates stop or limit levels for an existing position (details of parameters not provided in source). * `close_position(...)`: Closes an existing position (details of parameters not provided in source). ``` -------------------------------- ### Initialize CachedSession for API Requests Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/rest.md Sets up a CachedSession from the requests_cache library to cache API responses. Configure expiration or disable caching as needed. ```python from datetime import datetime, timedelta import requests_cache session = requests_cache.CachedSession(cache_name='cache', backend='sqlite', expire_after=timedelta(hours=1)) # set expire_after=None if you don't want cache expiration # set expire_after=0 if you don't want to cache queries ``` -------------------------------- ### IGService — Market Navigation Source: https://context7.com/ig-python/trading-ig/llms.txt Traverse the full IG market hierarchy tree, from top-level categories down to individual epics. ```APIDOC ## IGService — Market Navigation Traverse the full IG market hierarchy tree, from top-level categories down to individual epics. ### Methods #### `fetch_top_level_navigation_nodes()` Retrieves the top-level categories in the market hierarchy. Returns a dictionary containing 'nodes' and 'markets' DataFrames. #### `fetch_sub_nodes_by_node(node_id: str)` Retrieves the sub-categories and markets for a given node ID. * **node_id** (str): The ID of the navigation node. Returns a dictionary containing 'nodes' and 'markets' DataFrames. #### `fetch_client_sentiment_by_instrument(instrument: Union[str, List[str]])` Retrieves client sentiment data for one or more instruments. * **instrument** (Union[str, List[str]]): The epic symbol or a list of epic symbols. Returns a dictionary containing client sentiment data. ``` -------------------------------- ### Save Prices to CSV Source: https://github.com/ig-python/trading-ig/blob/master/sample/rest.ipynb Saves the fetched historical prices to a CSV file in the user's home directory. The file path is printed to the console before saving. Ensure the 'prices' data is available. ```python from pathlib import Path save_path = Path("~").expanduser() / "prices.csv" print(f"saving historic prices to {save_path}") data["prices"].to_csv(save_path, date_format="%Y-%m-%dT%H:%M:%S%z") ``` -------------------------------- ### Fetch Account Activity Source: https://context7.com/ig-python/trading-ig/llms.txt Fetches account activity, with options to filter by deal ID or use a v2 variant with time span and page size. ```APIDOC ## Fetch Account Activity Fetches account activity, with options to filter by deal ID or use a v2 variant with time span and page size. ### Method ```python fetch_account_activity(deal_id: str = None, max_span_seconds: int = None, page_size: int = None) ``` ### Parameters * **deal_id** (str, optional): Filter activity by a specific deal ID. * **max_span_seconds** (int, optional): Maximum time span in seconds for fetching recent activity. * **page_size** (int, optional): Number of items to retrieve per page. ``` -------------------------------- ### Fetch Market Information Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/quickstart.md Retrieve detailed information about a specific market using its epic identifier. ```python >>> market = ig_service.fetch_market_by_epic('CS.D.USCGC.TODAY.IP') >>> market ``` -------------------------------- ### Watchlists Source: https://context7.com/ig-python/trading-ig/llms.txt Manage named watchlists, including creating, fetching, adding/removing markets, and deleting watchlists. ```APIDOC ## IGService — Watchlists Create, query, and manage named watchlists containing instrument epics. ```python from trading_ig import IGService from trading_ig.config import config ig = IGService(config.username, config.password, config.api_key, acc_type="DEMO") ig.create_session() # All watchlists wls = ig.fetch_all_watchlists() print(wls[["id", "name", "editable", "defaultSystemWatchlist"]]) # Create a new watchlist new = ig.create_watchlist( name="My Watchlist", epics=["CS.D.EURUSD.MINI.IP", "IX.D.FTSE.IFM.IP"], ) watchlist_id = new["watchlistId"] # Markets in a watchlist markets = ig.fetch_watchlist_markets(watchlist_id) print(markets[["epic", "instrumentName", "bid", "offer"]]) # Add/remove a market ig.add_market_to_watchlist(watchlist_id, "CS.D.GBPUSD.MINI.IP") ig.remove_market_from_watchlist(watchlist_id, "CS.D.GBPUSD.MINI.IP") # Delete watchlist ig.delete_watchlist(watchlist_id) ``` ``` -------------------------------- ### Fetch Historical Prices Source: https://github.com/ig-python/trading-ig/blob/master/sample/rest.ipynb Retrieves historical price data for a given epic, resolution, and date range. The 'flat_prices' format is used, and the resulting prices are accessed via the 'prices' key in the returned dictionary. ```python data = service.fetch_historical_prices_by_epic( epic="IX.D.FTSE.DAILY.IP", resolution="D", start_date="2024-01-01", end_date="2024-01-22", format=service.flat_prices, ) data["prices"] ``` -------------------------------- ### Apply CachedSession to IGService Globally Source: https://github.com/ig-python/trading-ig/blob/master/docs/source/rest.md Initializes IGService with a pre-configured CachedSession, applying caching to all subsequent API calls made through this service instance. ```python ig_service = IGService(config.username, config.password, config.api_key, config.acc_type, session) ig_service.create_session() ```