-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIBClient.py
More file actions
394 lines (326 loc) · 14.3 KB
/
IBClient.py
File metadata and controls
394 lines (326 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import requests
from typing import Dict
from typing import List
from pprint import pprint
class IBClient:
def __init__(self):
self.baseUrl = "https://localhost:5000/v1/portal/"
self.authenticated = False
self.authenticated = self._authenticate()
def _authenticate(self) -> bool:
max_retries = 4
retries = 0
while max_retries > retries or self.authenticated is False:
auth_response = self.authentication_status()
if 'statusCode' in auth_response.keys() and auth_response['statusCode'] == 401:
print("Server isn't connected. Authentication Failed")
self.authenticated = False
return False
elif 'authenticated' in auth_response.keys() and auth_response['authenticated'] is True:
self.authenticated = True
return True
elif 'authenticated' in auth_response.keys() and auth_response['authenticated'] is False:
self.validate_SSO()
self.reauthenticate()
self.brokerage_accounts()
# self.authentication_status()
retries += 1
return self.authenticated
def _build_url(self, endpoint):
return self.baseUrl + endpoint
def _make_request(self, endpoint: str, req_type: str, params: Dict = None) -> Dict:
"""Handles the request to the client.
Handles all the requests made by the client and correctly organizes
the information so it is sent correctly. Additionally it will also
build the URL.
Arguments:
----
endpoint {str} -- The endpoint we wish to request.
req_type {str} -- Defines the type of request to be made. Can be one of four
possible values ['GET','POST','DELETE','PUT']
params {dict} -- Any arguments that are to be sent along in the request. That
could be parameters of a 'GET' request, or a data payload of a
'POST' request.
Returns:
----
{Dict} -- A response dictionary.
"""
url = self._build_url(endpoint=endpoint)
headers = {'Content-Type': 'application/json'}
response = None
if req_type == 'POST' and params is not None:
response = requests.post(url, headers=headers, json=params, verify=False)
elif req_type == 'POST' and params is None:
response = requests.post(url, headers=headers, verify=False)
elif req_type == 'GET' and params is not None:
response = requests.get(url, headers=headers, params=params, verify=False)
elif req_type == 'GET' and params is None:
response = requests.get(url, headers=headers, verify=False)
elif req_type == 'DELETE':
response = requests.delete(url, headers=headers, verify=False)
if response.ok:
return response.json()
else: # elif not response.ok and url != 'https://localhost:5000/v1/portal/iserver/account':
print('')
print('-' * 80)
print("BAD REQUEST - STATUS CODE: {}".format(response.status_code))
print("RESPONSE URL: {}".format(response.url))
print("RESPONSE HEADERS: {}".format(response.headers))
print("RESPONSE TEXT: {}".format(response.text))
print('-' * 80)
print('')
"""
PORTFOLIO ACCOUNTS ENDPOINTS
"""
def portfolio_accounts(self):
"""
In non-tiered account structures, returns a list of accounts for which the
user can view position and account information. This endpoint must be called prior
to calling other /portfolio endpoints for those accounts. For querying a list of accounts
which the user can trade, see /iserver/accounts. For a list of subaccounts in tiered account
structures (e.g. financial advisor or ibroker accounts) see /portfolio/subaccounts.
"""
# define request components
endpoint = 'portfolio/accounts'
req_type = 'GET'
content = self._make_request(endpoint=endpoint, req_type=req_type)
return content
def brokerage_accounts(self):
"""
Returns a list of accounts the user has trading access to, their respective aliases
and the currently selected account. Note this endpoint must be called before
modifying an order or querying open orders.
"""
# define request components
endpoint = r'iserver/accounts'
req_type = 'GET'
content = self._make_request(endpoint=endpoint, req_type=req_type)
return content
def portfolio_account_positions(self, account_id: str, page_id: int = 0) -> Dict:
"""
Returns a list of positions for the given account. The endpoint supports paging,
page's default size is 30 positions. /portfolio/accounts or /portfolio/subaccounts
must be called prior to this endpoint.
NAME: account_id
DESC: The account ID you wish to return positions for.
TYPE: String
NAME: page_id
DESC: The page you wish to return if there are more than 1. The
default value is `0`.
TYPE: String
ADDITIONAL ARGUMENTS NEED TO BE ADDED!!!!!
"""
# define request components
endpoint = r'portfolio/{}/positions/{}'.format(account_id, page_id)
req_type = 'GET'
content = self._make_request(endpoint=endpoint, req_type=req_type)
return content
def market_data(self, conids: List[int], since: str = None, fields: List[str] = ['31']) -> Dict:
"""
Get Market Data for the given conid(s). The end-point will return by
default bid, ask, last, change, change pct, close, listing exchange.
See response fields for a list of available fields that can be request
via fields argument. The endpoint /iserver/accounts should be called
prior to /iserver/marketdata/snapshot. To receive all available fields
the /snapshot endpoint will need to be called several times.
NAME: conid
DESC: The list of contract IDs you wish to pull current quotes for.
TYPE: List<String>
NAME: since
DESC: Time period since which updates are required.
Uses epoch time with milliseconds.
TYPE: String
NAME: fields
DESC: List of fields you wish to retrieve for each quote.
TYPE: List<String>
"""
# define request components
endpoint = r'iserver/marketdata/snapshot'
req_type = 'GET'
# define the parameters
params ={}
conids_joined = ",".join(str(conid) for conid in conids)
params['conids'] = conids_joined
fields_joined = ",".join(str(field) for field in fields)
params['fields'] = fields_joined
if since is not None:
params['since'] = since
content = self._make_request(endpoint=endpoint, req_type=req_type, params=params)
# retry if the field is not there
retry = False
for field in fields:
if field not in content[0].keys():
retry = True
break
if retry:
content = self._make_request(endpoint=endpoint, req_type=req_type, params=params)
return content
def reauthenticate(self) -> Dict:
"""Reauthenticates an existing session.
Provides a way to reauthenticate to the Brokerage system as long as there
is a valid SSO session, see /sso/validate.
"""
# define request components
endpoint = r'iserver/reauthenticate'
req_type = 'POST'
content = self._make_request(endpoint=endpoint, req_type=req_type)
return content
def authentication_status(self) -> Dict:
"""Checks if session is authenticated.
Current Authentication status to the Brokerage system. Market Data and
Trading is not possible if not authenticated, e.g. authenticated
shows `False`.
"""
# define request components
endpoint = r'iserver/auth/status'
req_type = 'POST'
content = self._make_request(endpoint=endpoint, req_type=req_type)
return content
def validate_SSO(self) -> Dict:
"""Validates the current session for the SSO user."""
# define request components
endpoint = r'sso/validate'
req_type = 'GET'
content = self._make_request(endpoint=endpoint, req_type=req_type)
return content
def tickle(self) -> Dict:
"""Keeps the session open.
If the gateway has not received any requests for several minutes an open session will
automatically timeout. The tickle endpoint pings the server to prevent the
session from ending.
"""
# define request components
endpoint = r'tickle'
req_type = 'POST'
content = self._make_request(endpoint=endpoint, req_type=req_type)
return content
def contracts_definitions(self, conids: List[int]) -> List[Dict]:
"""
Returns a list of security definitions for the given conids.
NAME: conids
DESC: A list of contract IDs you wish to get details for.
TYPE: List<Integer>
RTYPE: List<Dictionary>
"""
# define the request components
endpoint = '/trsrv/secdef'
req_type = 'POST'
payload = {
'conids': conids
}
content = self._make_request(endpoint=endpoint, req_type=req_type, params=payload)
return content['secdef'] # return the list of contract definitions, instead of a dictionary
def place_order(self, account_id: str, order: Dict, confirm=True) -> Dict:
"""
Please note here, sometimes this end-point alone can't make sure you submit the order
successfully, you could receive some questions in the response, you have to to answer
them in order to submit the order successfully. You can use "/iserver/reply/{replyid}"
end-point to answer questions.
NAME: account_id
DESC: The account ID you wish to place an order for.
TYPE: String
NAME: order
DESC: Either an IBOrder object or a dictionary with the specified payload.
TYPE: IBOrder or Dict
"""
# define request components
endpoint = r'iserver/account/{}/order'.format(account_id)
req_type = 'POST'
content = self._make_request(
endpoint=endpoint,
req_type=req_type,
params=order
)
return content
def place_orders(self, account_id: str, orders: Dict[str, List[Dict]]) -> Dict:
"""
An extension of the `place_order` endpoint but allows for a list of orders. Those orders may be
either a list of dictionary objects or a list of IBOrder objects. SO FAR IT DOES NOT WORK
NAME: account_id
DESC: The account ID you wish to place an order for.
TYPE: String
NAME: orders
DESC: Either a list of IBOrder objects or a list of dictionaries with the specified payload.
TYPE: List<IBOrder Object> or List<Dictionary>
"""
# define request components
endpoint = r'iserver/account/{}/orders'.format(account_id)
req_type = 'POST'
content = self._make_request(
endpoint=endpoint,
req_type=req_type,
params=orders
)
return content
def place_order_reply(self, reply_id: str = None, reply: bool = True):
"""
Reply to questions when placing orders and submit orders
"""
# define request components
endpoint = r'iserver/reply/{}'.format(reply_id)
req_type = 'POST'
reply = {'confirmed': reply}
content = self._make_request(
endpoint=endpoint,
req_type=req_type,
params=reply
)
return content
def get_live_orders(self):
"""
The end-point is meant to be used in polling mode, e.g. requesting every
x seconds. The response will contain two objects, one is notification, the
other is orders. Orders is the list of orders (cancelled, filled, submitted)
with activity in the current day. Notifications contains information about
execute orders as they happen, see status field.
"""
# define request components
endpoint = r'iserver/account/orders'
req_type = 'GET'
content = self._make_request(
endpoint=endpoint,
req_type=req_type
)
return content
def delete_order(self, account_id: str, order_id: str) -> Dict:
"""Deletes the order specified by the customer order ID.
NOTICE: it should actually be order ID, not customer order id as specified in the doc
NAME: account_id
DESC: The account ID you wish to place an order for.
TYPE: String
NAME: order_id
DESC: The order ID for the order you wish to DELETE.
TYPE: String
"""
# define request components
endpoint = r'iserver/account/{}/order/{}'.format(
account_id, order_id)
req_type = 'DELETE'
content = self._make_request(
endpoint=endpoint,
req_type=req_type
)
return content
def modify_order(self, account_id: str, local_order_id: str, order: Dict) -> Dict:
"""
Modifies an open order. The /iserver/accounts endpoint must first
be called.
NAME: account_id
DESC: The account ID you wish to place an order for.
TYPE: String
NAME: local_order_id
DESC: The customer order ID for the order you wish to MODIFY.
TYPE: String
NAME: order
DESC: Either an IBOrder object or a dictionary with the specified payload.
TYPE: IBOrder or Dict
"""
# define request components
endpoint = r'iserver/account/{}/order/{}'.format(account_id, local_order_id)
req_type = 'POST'
content = self._make_request(
endpoint=endpoint,
req_type=req_type,
params=order
)
return content