axt-ig-trade 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: axt-ig-trade
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client library for the IG trading platform
|
|
5
|
+
Requires-Dist: httpx>=0.28.1
|
|
6
|
+
Requires-Dist: lightstreamer-client-lib>=2.2.3
|
|
7
|
+
Requires-Dist: pydantic>=2.13.1
|
|
8
|
+
Requires-Dist: pydantic-settings>=2.13.1
|
|
9
|
+
Requires-Dist: requests>=2.33.1
|
|
10
|
+
Requires-Python: >=3.13
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# axt-ig-trade
|
|
14
|
+
|
|
15
|
+
Python client library for the IG trading platform.
|
|
16
|
+
|
|
17
|
+
## Publishing
|
|
18
|
+
|
|
19
|
+
Releases published on GitHub are built and uploaded to PyPI by
|
|
20
|
+
[`.github/workflows/publish.yml`](.github/workflows/publish.yml). Before each
|
|
21
|
+
release, update the package version in `pyproject.toml` to match the release
|
|
22
|
+
version.
|
|
23
|
+
|
|
24
|
+
To enable publishing without a PyPI API token, configure a trusted publisher in
|
|
25
|
+
the PyPI project's **Publishing** settings:
|
|
26
|
+
|
|
27
|
+
- Owner and repository: this GitHub repository
|
|
28
|
+
- Workflow name: `publish.yml`
|
|
29
|
+
- Environment: leave blank (the workflow does not use a GitHub environment)
|
|
30
|
+
|
|
31
|
+
The workflow also builds the distributions on pull requests and pushes to
|
|
32
|
+
`main` and version tags; only a published GitHub release is uploaded to PyPI.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# axt-ig-trade
|
|
2
|
+
|
|
3
|
+
Python client library for the IG trading platform.
|
|
4
|
+
|
|
5
|
+
## Publishing
|
|
6
|
+
|
|
7
|
+
Releases published on GitHub are built and uploaded to PyPI by
|
|
8
|
+
[`.github/workflows/publish.yml`](.github/workflows/publish.yml). Before each
|
|
9
|
+
release, update the package version in `pyproject.toml` to match the release
|
|
10
|
+
version.
|
|
11
|
+
|
|
12
|
+
To enable publishing without a PyPI API token, configure a trusted publisher in
|
|
13
|
+
the PyPI project's **Publishing** settings:
|
|
14
|
+
|
|
15
|
+
- Owner and repository: this GitHub repository
|
|
16
|
+
- Workflow name: `publish.yml`
|
|
17
|
+
- Environment: leave blank (the workflow does not use a GitHub environment)
|
|
18
|
+
|
|
19
|
+
The workflow also builds the distributions on pull requests and pushes to
|
|
20
|
+
`main` and version tags; only a published GitHub release is uploaded to PyPI.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "axt-ig-trade"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Python client library for the IG trading platform"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.13"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"httpx>=0.28.1",
|
|
9
|
+
"lightstreamer-client-lib>=2.2.3",
|
|
10
|
+
"pydantic>=2.13.1",
|
|
11
|
+
"pydantic-settings>=2.13.1",
|
|
12
|
+
"requests>=2.33.1",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[build-system]
|
|
16
|
+
requires = ["uv_build>=0.8.9,<0.9.0"]
|
|
17
|
+
build-backend = "uv_build"
|
|
18
|
+
|
|
19
|
+
[tool.uv.build-backend]
|
|
20
|
+
module-name = "axt_ig_trade"
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import logging
|
|
3
|
+
from datetime import UTC, date, datetime, time, timedelta
|
|
4
|
+
from enum import StrEnum
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import requests
|
|
10
|
+
from lightstreamer.client import (
|
|
11
|
+
ClientListener,
|
|
12
|
+
LightstreamerClient,
|
|
13
|
+
Subscription,
|
|
14
|
+
SubscriptionListener,
|
|
15
|
+
)
|
|
16
|
+
from pydantic import SecretStr
|
|
17
|
+
|
|
18
|
+
from axt_ig_trade.config import IGBaseConfig
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger("axt_ig_trade")
|
|
21
|
+
|
|
22
|
+
_CONNECTED_STATUS = "CONNECTED:WS-STREAMING"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class InstrumentType(StrEnum):
|
|
26
|
+
BONDS_RATES = "BONDS_RATES"
|
|
27
|
+
COMMODITIES = "COMMODITIES"
|
|
28
|
+
CRYPTOCURRENCY = "CRYPTOCURRENCY"
|
|
29
|
+
EQUITIES = "EQUITIES"
|
|
30
|
+
ETF = "ETF"
|
|
31
|
+
FX = "FX"
|
|
32
|
+
INDICES = "INDICES"
|
|
33
|
+
IPOS = "IPOS"
|
|
34
|
+
KNOCKOUTS = "KNOCKOUTS"
|
|
35
|
+
OPTIONS = "OPTIONS"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Resolution(StrEnum):
|
|
39
|
+
DAY = "DAY"
|
|
40
|
+
MINUTE = "MINUTE"
|
|
41
|
+
MINUTE_15 = "MINUTE_15"
|
|
42
|
+
MINUTE_30 = "MINUTE_30"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _IGBaseClient:
|
|
46
|
+
"""Client for interacting with the IG trading APIs."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, api_key: SecretStr, username: str, password: SecretStr) -> None:
|
|
49
|
+
"""Initializes the IGClient."""
|
|
50
|
+
self._config = IGBaseConfig()
|
|
51
|
+
self._api_key = api_key
|
|
52
|
+
self._username = username
|
|
53
|
+
self._password = password
|
|
54
|
+
self._client_token: SecretStr | None = None
|
|
55
|
+
self._security_token: SecretStr | None = None
|
|
56
|
+
|
|
57
|
+
def _auth_payload(self) -> dict[str, str]:
|
|
58
|
+
"""Constructs the authentication payload."""
|
|
59
|
+
return {
|
|
60
|
+
"identifier": self._username,
|
|
61
|
+
"password": self._password.get_secret_value(),
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
def _auth_headers(self) -> dict[str, str]:
|
|
65
|
+
"""Constructs the authentication headers."""
|
|
66
|
+
return {
|
|
67
|
+
"X-IG-API-KEY": self._api_key.get_secret_value(),
|
|
68
|
+
"Version": "2",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
def _authenticate(self) -> None:
|
|
72
|
+
"""Performs authentication and retrieves the necessary tokens."""
|
|
73
|
+
|
|
74
|
+
auth_url = f"{self._config.base_url}/session"
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
response = requests.post(
|
|
78
|
+
auth_url,
|
|
79
|
+
json=self._auth_payload(),
|
|
80
|
+
headers=self._auth_headers(),
|
|
81
|
+
timeout=30,
|
|
82
|
+
)
|
|
83
|
+
response.raise_for_status()
|
|
84
|
+
|
|
85
|
+
if not (client_token := response.headers.get("CST")):
|
|
86
|
+
raise ValueError(
|
|
87
|
+
f"Failed to authenticate to {auth_url}: CST token not found in response headers"
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
if not (security_token := response.headers.get("X-SECURITY-TOKEN")):
|
|
91
|
+
raise ValueError(
|
|
92
|
+
f"Failed to authenticate to {auth_url}: X-SECURITY-TOKEN not found in response headers"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
self._client_token = SecretStr(client_token)
|
|
96
|
+
self._security_token = SecretStr(security_token)
|
|
97
|
+
|
|
98
|
+
except requests.exceptions.HTTPError as e:
|
|
99
|
+
logger.error(f"Error authenticating to {auth_url}: {e}")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class IGRestClient(_IGBaseClient):
|
|
103
|
+
"""Client for interacting with the IG trading REST API."""
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
api_key: SecretStr,
|
|
108
|
+
username: str,
|
|
109
|
+
password: SecretStr,
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Initializes the IGRestClient."""
|
|
112
|
+
self._client: LightstreamerClient | None = None
|
|
113
|
+
super().__init__(api_key, username, password)
|
|
114
|
+
|
|
115
|
+
def _create_client(self) -> httpx.Client:
|
|
116
|
+
"""Creates an authenticated http client."""
|
|
117
|
+
if not self._client_token or not self._security_token:
|
|
118
|
+
self._authenticate()
|
|
119
|
+
|
|
120
|
+
return httpx.Client(
|
|
121
|
+
base_url=self._config.base_url,
|
|
122
|
+
headers={
|
|
123
|
+
"CST": self._client_token.get_secret_value(),
|
|
124
|
+
"X-IG-API-KEY": self._api_key.get_secret_value(),
|
|
125
|
+
"X-SECURITY-TOKEN": self._security_token.get_secret_value(),
|
|
126
|
+
"Version": "3",
|
|
127
|
+
},
|
|
128
|
+
timeout=30,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
@lru_cache(maxsize=24)
|
|
133
|
+
def _substract_days(cls, from_date: datetime, days: int) -> datetime:
|
|
134
|
+
"""Returns a date that is a specified number of days before the given date."""
|
|
135
|
+
return from_date - timedelta(days=days)
|
|
136
|
+
|
|
137
|
+
@classmethod
|
|
138
|
+
@lru_cache(maxsize=24)
|
|
139
|
+
def _format_datetime(cls, dt: datetime) -> str:
|
|
140
|
+
"""Formats a datetime object as an ISO 8601 string."""
|
|
141
|
+
return dt.strftime("%Y-%m-%dT%H:%M:%S")
|
|
142
|
+
|
|
143
|
+
def fetch_historic_prices(
|
|
144
|
+
self,
|
|
145
|
+
epic: str,
|
|
146
|
+
resolution: Resolution,
|
|
147
|
+
from_date: date | datetime | None = None,
|
|
148
|
+
to_date: date | datetime | None = None,
|
|
149
|
+
export_path: Path | None = None,
|
|
150
|
+
) -> list[dict]:
|
|
151
|
+
"""Fetches historical data for a given market and resolution.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
epic: The epic to fetch data for.
|
|
155
|
+
resolution: The resolution of the data (e.g., DAY, MINUTE).
|
|
156
|
+
from_date: The start date for the data (inclusive). Defaults to 1 year ago.
|
|
157
|
+
to_date: The end date for the data (inclusive). Defaults to today.
|
|
158
|
+
export_path: Optional path to export the data as a CSV file.
|
|
159
|
+
Returns:
|
|
160
|
+
A list of dictionaries containing the historical data.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
if not from_date:
|
|
164
|
+
from_date = self._substract_days(datetime.now(UTC), 365)
|
|
165
|
+
if not to_date:
|
|
166
|
+
to_date = datetime.now(UTC)
|
|
167
|
+
|
|
168
|
+
# if provided dates do not include timestamp, convert them to datetimes at the start and end of the day respectively
|
|
169
|
+
if isinstance(from_date, date) and not isinstance(from_date, datetime):
|
|
170
|
+
from_date = datetime.combine(from_date, datetime.min.time())
|
|
171
|
+
if isinstance(to_date, date) and not isinstance(to_date, datetime):
|
|
172
|
+
to_date = datetime.combine(to_date, datetime.max.time())
|
|
173
|
+
|
|
174
|
+
endpoint = f"/prices/{epic}"
|
|
175
|
+
|
|
176
|
+
params = {
|
|
177
|
+
"resolution": resolution.value,
|
|
178
|
+
"from": IGRestClient._format_datetime(from_date),
|
|
179
|
+
"to": IGRestClient._format_datetime(to_date),
|
|
180
|
+
"pageSize": 0, # TODO handle paging as this will return all in one page,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
with self._create_client() as client:
|
|
185
|
+
response = client.get(endpoint, params=params)
|
|
186
|
+
response.raise_for_status()
|
|
187
|
+
except httpx.HTTPStatusError as e:
|
|
188
|
+
logger.error(f"Error fetching historical data for {epic}: {e}")
|
|
189
|
+
return []
|
|
190
|
+
|
|
191
|
+
data = response.json()
|
|
192
|
+
|
|
193
|
+
if not (prices := data.get("prices")):
|
|
194
|
+
logger.warning(f"No historic price data found for market {epic}")
|
|
195
|
+
return []
|
|
196
|
+
|
|
197
|
+
if export_path:
|
|
198
|
+
writer = csv.DictWriter(
|
|
199
|
+
export_path.open("w", newline="\n", encoding="utf-8"),
|
|
200
|
+
fieldnames=prices[0].keys(),
|
|
201
|
+
)
|
|
202
|
+
writer.writeheader()
|
|
203
|
+
writer.writerows(prices)
|
|
204
|
+
|
|
205
|
+
return prices
|
|
206
|
+
|
|
207
|
+
def fetch_latest_price(
|
|
208
|
+
self,
|
|
209
|
+
epic: str,
|
|
210
|
+
) -> dict:
|
|
211
|
+
"""Fetches most recent data point for a given market and resolution.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
epic: The epic to fetch data for.
|
|
215
|
+
Returns:
|
|
216
|
+
A dictionary containing `offer` and `updateTime`.
|
|
217
|
+
"""
|
|
218
|
+
|
|
219
|
+
endpoint = f"/markets/{epic}"
|
|
220
|
+
|
|
221
|
+
try:
|
|
222
|
+
with self._create_client() as client:
|
|
223
|
+
response = client.get(endpoint)
|
|
224
|
+
response.raise_for_status()
|
|
225
|
+
except httpx.HTTPStatusError as e:
|
|
226
|
+
logger.error(f"Error fetching latest price for {epic}: {e}")
|
|
227
|
+
return {}
|
|
228
|
+
|
|
229
|
+
data = response.json()
|
|
230
|
+
|
|
231
|
+
if not data.get("snapshot", {}).get("offer"):
|
|
232
|
+
logger.warning(f"Latest price not found for market {epic}")
|
|
233
|
+
return {}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
"offer": data["snapshot"]["offer"],
|
|
237
|
+
"updateTime": data["snapshot"]["updateTime"],
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
def search_markets(
|
|
241
|
+
self,
|
|
242
|
+
search_term: str,
|
|
243
|
+
instrument_type: InstrumentType | None = None,
|
|
244
|
+
) -> list[dict]:
|
|
245
|
+
"""Searches for markets matching the given query.
|
|
246
|
+
|
|
247
|
+
Args:
|
|
248
|
+
search_term: The search term for market symbols.
|
|
249
|
+
instrument_type: The type of instrument to filter markets by (optional).
|
|
250
|
+
Returns:
|
|
251
|
+
A list of dictionaries containing `epic`, `instrumentName`, and `instrumentType`.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
endpoint = "/markets"
|
|
255
|
+
params = {"searchTerm": search_term}
|
|
256
|
+
|
|
257
|
+
try:
|
|
258
|
+
with self._create_client() as client:
|
|
259
|
+
response = client.get(endpoint, params=params, headers={"Version": "1"})
|
|
260
|
+
response.raise_for_status()
|
|
261
|
+
except httpx.HTTPStatusError as e:
|
|
262
|
+
logger.error(f"Error searching markets with query '{search_term}': {e}")
|
|
263
|
+
return []
|
|
264
|
+
|
|
265
|
+
data = response.json()
|
|
266
|
+
|
|
267
|
+
if not (markets := data.get("markets")):
|
|
268
|
+
logger.warning(f"No markets found for query '{search_term}'")
|
|
269
|
+
return []
|
|
270
|
+
|
|
271
|
+
return [
|
|
272
|
+
{
|
|
273
|
+
k: v
|
|
274
|
+
for k, v in market.items()
|
|
275
|
+
if k in ("epic", "instrumentName", "instrumentType")
|
|
276
|
+
}
|
|
277
|
+
for market in markets
|
|
278
|
+
if not instrument_type
|
|
279
|
+
or market.get("instrumentType") == instrument_type.value
|
|
280
|
+
]
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
class IGStreamingClient(_IGBaseClient):
|
|
284
|
+
"""Client for interacting with the IG trading streaming API."""
|
|
285
|
+
|
|
286
|
+
def __init__(
|
|
287
|
+
self,
|
|
288
|
+
api_key: SecretStr,
|
|
289
|
+
username: str,
|
|
290
|
+
password: SecretStr,
|
|
291
|
+
account_id: str,
|
|
292
|
+
client_listener: ClientListener | None = None,
|
|
293
|
+
) -> None:
|
|
294
|
+
"""Initializes the IGStreamingClient."""
|
|
295
|
+
super().__init__(api_key, username, password)
|
|
296
|
+
self._client = LightstreamerClient(
|
|
297
|
+
self._config.lightstreamer_url, adapterSet="DEFAULT"
|
|
298
|
+
)
|
|
299
|
+
self._client_listener = client_listener
|
|
300
|
+
self._account_id = account_id
|
|
301
|
+
|
|
302
|
+
@property
|
|
303
|
+
def _streaming_password(self) -> str:
|
|
304
|
+
"""Constructs the streaming password using the authentication tokens."""
|
|
305
|
+
|
|
306
|
+
if not self._client_token or not self._security_token:
|
|
307
|
+
raise ValueError("Authentication tokens are missing")
|
|
308
|
+
|
|
309
|
+
return f"CST-{self._client_token.get_secret_value()}|XST-{self._security_token.get_secret_value()}"
|
|
310
|
+
|
|
311
|
+
def _connect(self) -> None:
|
|
312
|
+
"""Connects to Lightstreamer."""
|
|
313
|
+
|
|
314
|
+
if not self._client:
|
|
315
|
+
raise ValueError("Client is not initialized")
|
|
316
|
+
|
|
317
|
+
self._authenticate()
|
|
318
|
+
|
|
319
|
+
self._client.connectionDetails.setUser(self._account_id)
|
|
320
|
+
self._client.connectionDetails.setPassword(self._streaming_password)
|
|
321
|
+
|
|
322
|
+
if self._client_listener:
|
|
323
|
+
self._client.addListener(self._client_listener)
|
|
324
|
+
|
|
325
|
+
self._client.connect()
|
|
326
|
+
|
|
327
|
+
logging.info(f"Connected to {self._config.lightstreamer_url}")
|
|
328
|
+
|
|
329
|
+
def disconnect(self) -> None:
|
|
330
|
+
"""Disconnects from Lightstreamer."""
|
|
331
|
+
self._client.disconnect()
|
|
332
|
+
logging.info(f"Disconnected from {self._config.lightstreamer_url}")
|
|
333
|
+
|
|
334
|
+
def subscribe(
|
|
335
|
+
self,
|
|
336
|
+
epics: list[str],
|
|
337
|
+
listener: SubscriptionListener,
|
|
338
|
+
fields: list[str] | None = None,
|
|
339
|
+
) -> None:
|
|
340
|
+
"""Subscribes to prices feeds.
|
|
341
|
+
|
|
342
|
+
Args:
|
|
343
|
+
epics: List of epics to subscribe to.
|
|
344
|
+
listener: Subscription listener to handle incoming data.
|
|
345
|
+
fields: Optional list of fields to subscribe to.
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
if self._client.getStatus() == "DISCONNECTED":
|
|
349
|
+
self._connect()
|
|
350
|
+
|
|
351
|
+
fields = fields or [
|
|
352
|
+
"BID",
|
|
353
|
+
"OFFER",
|
|
354
|
+
"HIGH",
|
|
355
|
+
"LOW",
|
|
356
|
+
"CHANGE",
|
|
357
|
+
"CHANGE_PCT",
|
|
358
|
+
"UPDATE_TIME",
|
|
359
|
+
]
|
|
360
|
+
|
|
361
|
+
retries = 0
|
|
362
|
+
|
|
363
|
+
while self._client.getStatus() != _CONNECTED_STATUS:
|
|
364
|
+
if retries < 4:
|
|
365
|
+
logging.warning(
|
|
366
|
+
f"Client not connected yet. Current status: {self._client.getStatus()}. Retrying"
|
|
367
|
+
)
|
|
368
|
+
time.sleep(0.5)
|
|
369
|
+
retries += 1
|
|
370
|
+
else:
|
|
371
|
+
raise ValueError(
|
|
372
|
+
"Client is not connected, current status: "
|
|
373
|
+
+ self._client.getStatus()
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
sub = Subscription(
|
|
377
|
+
mode="MERGE",
|
|
378
|
+
items=[f"MARKET:{market}" for market in epics],
|
|
379
|
+
fields=fields,
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
sub.setRequestedSnapshot("yes")
|
|
383
|
+
|
|
384
|
+
sub.addListener(listener)
|
|
385
|
+
|
|
386
|
+
self._client.subscribe(sub)
|
|
387
|
+
|
|
388
|
+
logging.info("Subscribed to markets: " + ", ".join(epics))
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class IGBaseConfig(BaseSettings):
|
|
5
|
+
"""IG Client Config"""
|
|
6
|
+
|
|
7
|
+
model_config = SettingsConfigDict(env_prefix="IG_")
|
|
8
|
+
base_url: str = "https://api.ig.com/gateway/deal"
|
|
9
|
+
lightstreamer_url: str = "https://apd.marketdatasystems.com/"
|