-
Notifications
You must be signed in to change notification settings - Fork 59
/
igclient.py
302 lines (253 loc) · 10.6 KB
/
igclient.py
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
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''
# Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk
# Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB
# Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu
# Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd
# contact :- github@jamessawyer.co.uk
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''
# Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk
# Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB
# Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu
# Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import configparser
import requests
import json
import time
def trackcall(f):
# tracks number of recent api calls (in last 60s) and sleeps accordingly
def wrap(*args, **kwargs):
while len(args[0].recent_calls) >= 30 - 1:
time.sleep(1)
args[0].recent_calls = [
x for x in args[0].recent_calls if x > int(time.time() - 60)
]
# args[0].recent_calls = filter(lambda x: x > int(time.time())-60, args[0].recent_calls)
args[0].recent_calls.append(int(time.time()))
return f(*args, **kwargs)
return wrap
class IGClient:
def __init__(self, config=None):
self.loggedin = False
self.json = True # return json or obj
if config is None:
config = configparser.ConfigParser()
config.read("default.conf")
config.read("config.conf")
self.config = config
self.auth = {}
self.debug = False
self.allowance = {}
self.recent_calls = []
self.API_ENDPOINT = self.config["Config"]["API_ENDPOINT"]
self.API_KEY = self.config["Config"]["API_KEY"]
def setdebug(self, value=True):
self.debug = value
try:
import http.client as http_client
except ImportError:
import httplib as http_client
http_client.HTTPConnection.debuglevel = (0, 1)[self.debug]
@trackcall
def session(self, set_default=True):
data = {
"identifier": self.config["Auth"]["USERNAME"],
"password": self.config["Auth"]["PASSWORD"],
}
self.headers = {
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json; charset=utf-8",
}
self.headers.update({"X-IG-API-KEY": self.API_KEY})
self.session_headers = self.headers.copy()
self.session_headers.update({"Version": "2"})
curr_json = self.json
self.json = False # force off to let us use handlereq
r = self._handlereq(
requests.post(
self.API_ENDPOINT + "/session",
data=json.dumps(data),
headers=self.session_headers,
))
self.json = curr_json # set it back
headers_json = dict(r.headers)
for h in ["CST", "X-SECURITY-TOKEN"]:
self.auth[h] = headers_json[h]
self.headers.update(self.auth)
self.authenticated_headers = self.headers
self.loggedin = True
# GET ACCOUNTS
d = self.accounts()
for i in d["accounts"]:
if str(i["accountType"]) == self.config["Config"]["ACCOUNT_TYPE"]:
# print ("Spreadbet Account ID is : " + str(i['accountId']))
self.accountId = str(i["accountId"])
break
if set_default:
# SET SPREAD BET ACCOUNT AS DEFAULT
self.update_session({
"accountId": self.accountId,
"defaultAccount": "True"
})
# ERROR about account ID been the same, Ignore!
return (r, json.loads(r.text))[self.json]
def _handlereq(self, r):
if self.debug:
try:
print(r.text)
except Exception:
pass
return (r, json.loads(r.text))[self.json]
def _authheadersfordelete(self):
# WORKAROUND AS PER .... https://labs.ig.com/node/36
delete_headers = self.authenticated_headers.copy()
delete_headers.update({"_method": "DELETE"})
return delete_headers
@trackcall
def accounts(self):
return self._handlereq(
requests.get(self.API_ENDPOINT + "/accounts",
headers=self.authenticated_headers))
@trackcall
def update_session(self, data):
return self._handlereq(
requests.put(
self.API_ENDPOINT + "/session",
data=data,
headers=self.authenticated_headers,
))
def markets(self, epic_id):
return self._handlereq(
requests.get(
self.API_ENDPOINT + "/markets/" + epic_id,
headers=self.authenticated_headers,
))
@trackcall
def clientsentiment(self, market_id):
return self._handlereq(
requests.get(
self.API_ENDPOINT + "/clientsentiment/" + market_id,
headers=self.authenticated_headers,
))
@trackcall
def prices(self, epic_id, resolution):
r = self._handlereq(
requests.get(
self.API_ENDPOINT + "/prices/" + epic_id + "/" + resolution,
headers=self.authenticated_headers,
))
try:
self.allowance = r["allowance"]
except Exception:
pass
return r
@trackcall
def positions(self, deal_id=None):
if deal_id is None:
url = "/positions"
else:
url = "/positions/" + deal_id
return self._handlereq(
requests.get(self.API_ENDPOINT + url,
headers=self.authenticated_headers))
@trackcall
def positions_otc(self, data):
if eval(self.config["Trade"]["always_guarantee_stops"]):
data["guaranteedStop"] = True
if eval(self.config["Trade"]["never_guarantee_stops"]):
data["guaranteedStop"] = False
return self._handlereq(
requests.post(
self.API_ENDPOINT + "/positions/otc",
data=json.dumps(data),
headers=self.authenticated_headers,
))
@trackcall
def positions_otc_close(self, data):
return self._handlereq(
requests.post(
self.API_ENDPOINT + "/positions/otc",
data=json.dumps(data),
headers=self._authheadersfordelete(),
))
@trackcall
def confirms(self, deal_ref):
return self._handlereq(
requests.get(
self.API_ENDPOINT + "/confirms/" + deal_ref,
headers=self.authenticated_headers,
))
def handleDealingRules(self, data):
market = self.markets(data["epic"])
dealingRules = market["dealingRules"]
current_price = float(market["snapshot"]["bid"])
r = "marketOrderPreference"
if dealingRules[r] == "NOT_AVAILABLE":
print(
"!!ERROR!! This market is not available for this dealing account"
)
r = "maxStopOrLimitDistance"
if dealingRules[r]["unit"] == "PERCENTAGE":
if current_price / 100 * float(dealingRules[r]["value"]) < float(
data["limitDistance"]):
data["limitDistance"] = str(
format(
current_price / 100 * float(dealingRules[r]["value"]),
".2f"))
elif dealingRules[r]["unit"] == "POINTS":
if float(dealingRules[r]["value"]) < float(data["limitDistance"]):
data["limitDistance"] = str(dealingRules[r]["value"])
if ("guaranteedStop" in data and data["guaranteedStop"]
) or self.config["Trade"]["always_guarantee_stops"]:
r = "minControlledRiskStopDistance"
else: # data['guaranteedStop'] == False
r = "minNormalStopOrLimitDistance"
if dealingRules[r]["unit"] == "PERCENTAGE":
if current_price / 100 * float(dealingRules[r]["value"]) > float(
data["stopDistance"]):
data["stopDistance"] = str(
format(
current_price / 100 * float(dealingRules[r]["value"]),
".2f"))
elif dealingRules[r]["unit"] == "POINTS":
if float(dealingRules[r]["value"]) > float(data["stopDistance"]):
data["stopDistance"] = str(dealingRules[r]["value"])
r = "minDealSize"
if dealingRules[r]["unit"] == "POINTS":
if float(dealingRules[r]["value"]) > float(data["size"]):
data["size"] = str(dealingRules[r]["value"])
elif dealingRules[r]["unit"] == "PERCENTAGE":
pass # err...what? we have to buy sell a percentage of everything?
# minStepDistance
# hmmm...i'm not doing this one :D
# if our bid is smaller than the permitted amount, that's because:
# we have no faith in the step being big enough;
# or we don't have permission to make a step that big
# either way, we shouldn't change it just to let the trade go through
# it should fail
# trailingStopsPreference # TODO
return data