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)