Skip to content

Instantly share code, notes, and snippets.

@mac133k
Last active May 16, 2024 11:31
Show Gist options
  • Save mac133k/f15d9a998ac3b25f34886c0029775612 to your computer and use it in GitHub Desktop.
Save mac133k/f15d9a998ac3b25f34886c0029775612 to your computer and use it in GitHub Desktop.
Basic IG API client with instrument tree traversal methods
import requests
import time
class IG:
def __init__(self, username, password, api_key, base_url='https://api.ig.com/gateway/deal'):
self.session_init(username, password, api_key, base_url, currency)
def session_init(self, username, password, api_key, base_url):
self.base_url = base_url
self.headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json; charset=UTF-8',
'VERSION': '2'}
self.headers['X-IG-API-KEY'] = api_key
self.session = requests.post(f'{self.base_url}/session',
json={'identifier': username, 'password': password, 'encryptedPassword': False},
headers=self.headers)
self.headers['CST'] = self.session.headers['CST']
self.headers['X-SECURITY-TOKEN'] = self.session.headers['X-SECURITY-TOKEN']
self.headers_v1 = dict(self.headers)
self.headers_v1['VERSION'] = '1'
def navigation(self, node_id):
return requests.get(f'{self.base_url}/marketnavigation/{node_id}',
headers=self.headers_v1).json()
def traverse(self, node_id, markets=[], delay=2):
level = self.navigation(node_id)
print('.', end='', flush=True)
time.sleep(delay)
if 'nodes' in level and type(level['nodes']) == list:
for node in level['nodes']:
self.traverse(node['id'], markets)
if 'markets' in level and type(level['markets']) == list:
for market in level['markets']:
markets.append(market)
return markets
def get_instruments(self, epics=[], filt='ALL'):
return requests.get(f'{self.base_url}/markets',
params={'epics': ','.join(epics), 'filter': filt},
headers=self.headers).json()
@mac133k
Copy link
Author

mac133k commented Mar 5, 2024

Did it work for you as expected?

@icarus7776
Copy link

Unfortunately not - I let it run without touching it for the past few days and nothing happened. And I'm not sure if there was any progress. For my purposes as a start I'm just trying to get the stocks within ASX200 and S&P500. Didn't know it would be this hard!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment