]>
Commit | Line | Data |
---|---|---|
dd359bc0 | 1 | import time |
9f54fd9a | 2 | from datetime import datetime, timedelta |
350ed24d | 3 | from decimal import Decimal as D, ROUND_DOWN |
dd359bc0 | 4 | # Put your poloniex api key in market.py |
80cdd672 | 5 | from json import JSONDecodeError |
df9e4e7f | 6 | from ccxt import ExchangeError, ExchangeNotAvailable |
80cdd672 | 7 | import requests |
6ca5a1ec IB |
8 | import helper as h |
9 | from store import * | |
80cdd672 IB |
10 | |
11 | # FIXME: correctly handle web call timeouts | |
12 | ||
dd359bc0 IB |
13 | class Portfolio: |
14 | URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json" | |
15 | liquidities = {} | |
16 | data = None | |
9f54fd9a | 17 | last_date = None |
dd359bc0 IB |
18 | |
19 | @classmethod | |
9f54fd9a IB |
20 | def wait_for_recent(cls, delta=4): |
21 | cls.repartition(refetch=True) | |
22 | while cls.last_date is None or datetime.now() - cls.last_date > timedelta(delta): | |
23 | time.sleep(30) | |
24 | cls.repartition(refetch=True) | |
25 | ||
26 | @classmethod | |
27 | def repartition(cls, liquidity="medium", refetch=False): | |
28 | cls.parse_cryptoportfolio(refetch=refetch) | |
dd359bc0 | 29 | liquidities = cls.liquidities[liquidity] |
c11e4274 | 30 | return liquidities[cls.last_date] |
dd359bc0 IB |
31 | |
32 | @classmethod | |
33 | def get_cryptoportfolio(cls): | |
183a53e3 | 34 | try: |
80cdd672 | 35 | r = requests.get(cls.URL) |
183a53e3 | 36 | except Exception: |
80cdd672 | 37 | return |
183a53e3 | 38 | try: |
80cdd672 IB |
39 | cls.data = r.json(parse_int=D, parse_float=D) |
40 | except JSONDecodeError: | |
183a53e3 | 41 | cls.data = None |
dd359bc0 IB |
42 | |
43 | @classmethod | |
9f54fd9a IB |
44 | def parse_cryptoportfolio(cls, refetch=False): |
45 | if refetch or cls.data is None: | |
dd359bc0 IB |
46 | cls.get_cryptoportfolio() |
47 | ||
48 | def filter_weights(weight_hash): | |
350ed24d | 49 | if weight_hash[1][0] == 0: |
dd359bc0 IB |
50 | return False |
51 | if weight_hash[0] == "_row": | |
52 | return False | |
53 | return True | |
54 | ||
55 | def clean_weights(i): | |
56 | def clean_weights_(h): | |
350ed24d IB |
57 | if h[0].endswith("s"): |
58 | return [h[0][0:-1], (h[1][i], "short")] | |
dd359bc0 | 59 | else: |
350ed24d | 60 | return [h[0], (h[1][i], "long")] |
dd359bc0 IB |
61 | return clean_weights_ |
62 | ||
63 | def parse_weights(portfolio_hash): | |
dd359bc0 IB |
64 | weights_hash = portfolio_hash["weights"] |
65 | weights = {} | |
66 | for i in range(len(weights_hash["_row"])): | |
9f54fd9a IB |
67 | date = datetime.strptime(weights_hash["_row"][i], "%Y-%m-%d") |
68 | weights[date] = dict(filter( | |
dd359bc0 IB |
69 | filter_weights, |
70 | map(clean_weights(i), weights_hash.items()))) | |
71 | return weights | |
72 | ||
73 | high_liquidity = parse_weights(cls.data["portfolio_1"]) | |
74 | medium_liquidity = parse_weights(cls.data["portfolio_2"]) | |
75 | ||
76 | cls.liquidities = { | |
77 | "medium": medium_liquidity, | |
78 | "high": high_liquidity, | |
79 | } | |
9f54fd9a | 80 | cls.last_date = max(max(medium_liquidity.keys()), max(high_liquidity.keys())) |
dd359bc0 | 81 | |
6ca5a1ec IB |
82 | class Computation: |
83 | computations = { | |
84 | "default": lambda x, y: x[y], | |
85 | "average": lambda x, y: x["average"], | |
86 | "bid": lambda x, y: x["bid"], | |
87 | "ask": lambda x, y: x["ask"], | |
88 | } | |
89 | ||
90 | @classmethod | |
91 | def compute_value(cls, ticker, action, compute_value="default"): | |
92 | if action == "buy": | |
93 | action = "ask" | |
94 | if action == "sell": | |
95 | action = "bid" | |
96 | if isinstance(compute_value, str): | |
97 | compute_value = cls.computations[compute_value] | |
98 | return compute_value(ticker, action) | |
99 | ||
dd359bc0 | 100 | class Amount: |
c2644ba8 | 101 | def __init__(self, currency, value, linked_to=None, ticker=None, rate=None): |
dd359bc0 | 102 | self.currency = currency |
5ab23e1c | 103 | self.value = D(value) |
dd359bc0 IB |
104 | self.linked_to = linked_to |
105 | self.ticker = ticker | |
c2644ba8 | 106 | self.rate = rate |
dd359bc0 | 107 | |
c2644ba8 | 108 | def in_currency(self, other_currency, market, rate=None, action=None, compute_value="average"): |
dd359bc0 IB |
109 | if other_currency == self.currency: |
110 | return self | |
c2644ba8 IB |
111 | if rate is not None: |
112 | return Amount( | |
113 | other_currency, | |
114 | self.value * rate, | |
115 | linked_to=self, | |
116 | rate=rate) | |
6ca5a1ec | 117 | asset_ticker = h.get_ticker(self.currency, other_currency, market) |
dd359bc0 | 118 | if asset_ticker is not None: |
6ca5a1ec | 119 | rate = Computation.compute_value(asset_ticker, action, compute_value=compute_value) |
dd359bc0 IB |
120 | return Amount( |
121 | other_currency, | |
c2644ba8 | 122 | self.value * rate, |
dd359bc0 | 123 | linked_to=self, |
c2644ba8 IB |
124 | ticker=asset_ticker, |
125 | rate=rate) | |
dd359bc0 IB |
126 | else: |
127 | raise Exception("This asset is not available in the chosen market") | |
128 | ||
350ed24d IB |
129 | def __round__(self, n=8): |
130 | return Amount(self.currency, self.value.quantize(D(1)/D(10**n), rounding=ROUND_DOWN)) | |
131 | ||
dd359bc0 | 132 | def __abs__(self): |
5ab23e1c | 133 | return Amount(self.currency, abs(self.value)) |
dd359bc0 IB |
134 | |
135 | def __add__(self, other): | |
f320eb8a IB |
136 | if other == 0: |
137 | return self | |
5ab23e1c | 138 | if other.currency != self.currency and other.value * self.value != 0: |
dd359bc0 | 139 | raise Exception("Summing amounts must be done with same currencies") |
5ab23e1c | 140 | return Amount(self.currency, self.value + other.value) |
dd359bc0 IB |
141 | |
142 | def __radd__(self, other): | |
143 | if other == 0: | |
144 | return self | |
145 | else: | |
146 | return self.__add__(other) | |
147 | ||
148 | def __sub__(self, other): | |
c51687d2 IB |
149 | if other == 0: |
150 | return self | |
5ab23e1c | 151 | if other.currency != self.currency and other.value * self.value != 0: |
dd359bc0 | 152 | raise Exception("Summing amounts must be done with same currencies") |
5ab23e1c | 153 | return Amount(self.currency, self.value - other.value) |
dd359bc0 | 154 | |
f320eb8a IB |
155 | def __rsub__(self, other): |
156 | if other == 0: | |
157 | return -self | |
158 | else: | |
159 | return -self.__sub__(other) | |
160 | ||
dd359bc0 | 161 | def __mul__(self, value): |
77f8a378 | 162 | if not isinstance(value, (int, float, D)): |
dd359bc0 | 163 | raise TypeError("Amount may only be multiplied by numbers") |
5ab23e1c | 164 | return Amount(self.currency, self.value * value) |
dd359bc0 IB |
165 | |
166 | def __rmul__(self, value): | |
167 | return self.__mul__(value) | |
168 | ||
169 | def __floordiv__(self, value): | |
77f8a378 | 170 | if not isinstance(value, (int, float, D)): |
1aa7d4fa | 171 | raise TypeError("Amount may only be divided by numbers") |
5ab23e1c | 172 | return Amount(self.currency, self.value / value) |
dd359bc0 IB |
173 | |
174 | def __truediv__(self, value): | |
175 | return self.__floordiv__(value) | |
176 | ||
177 | def __lt__(self, other): | |
006a2084 IB |
178 | if other == 0: |
179 | return self.value < 0 | |
dd359bc0 IB |
180 | if self.currency != other.currency: |
181 | raise Exception("Comparing amounts must be done with same currencies") | |
5ab23e1c | 182 | return self.value < other.value |
dd359bc0 | 183 | |
80cdd672 IB |
184 | def __le__(self, other): |
185 | return self == other or self < other | |
186 | ||
006a2084 IB |
187 | def __gt__(self, other): |
188 | return not self <= other | |
189 | ||
190 | def __ge__(self, other): | |
191 | return not self < other | |
192 | ||
dd359bc0 IB |
193 | def __eq__(self, other): |
194 | if other == 0: | |
5ab23e1c | 195 | return self.value == 0 |
dd359bc0 IB |
196 | if self.currency != other.currency: |
197 | raise Exception("Comparing amounts must be done with same currencies") | |
5ab23e1c | 198 | return self.value == other.value |
dd359bc0 | 199 | |
006a2084 IB |
200 | def __ne__(self, other): |
201 | return not self == other | |
202 | ||
203 | def __neg__(self): | |
204 | return Amount(self.currency, - self.value) | |
205 | ||
dd359bc0 IB |
206 | def __str__(self): |
207 | if self.linked_to is None: | |
208 | return "{:.8f} {}".format(self.value, self.currency) | |
209 | else: | |
210 | return "{:.8f} {} [{}]".format(self.value, self.currency, self.linked_to) | |
211 | ||
212 | def __repr__(self): | |
213 | if self.linked_to is None: | |
214 | return "Amount({:.8f} {})".format(self.value, self.currency) | |
215 | else: | |
216 | return "Amount({:.8f} {} -> {})".format(self.value, self.currency, repr(self.linked_to)) | |
217 | ||
218 | class Balance: | |
dd359bc0 | 219 | |
006a2084 | 220 | def __init__(self, currency, hash_): |
dd359bc0 | 221 | self.currency = currency |
006a2084 IB |
222 | for key in ["total", |
223 | "exchange_total", "exchange_used", "exchange_free", | |
224 | "margin_total", "margin_borrowed", "margin_free"]: | |
225 | setattr(self, key, Amount(currency, hash_.get(key, 0))) | |
226 | ||
80cdd672 | 227 | self.margin_position_type = hash_.get("margin_position_type") |
006a2084 | 228 | |
80cdd672 | 229 | if hash_.get("margin_borrowed_base_currency") is not None: |
006a2084 IB |
230 | base_currency = hash_["margin_borrowed_base_currency"] |
231 | for key in [ | |
232 | "margin_liquidation_price", | |
233 | "margin_pending_gain", | |
234 | "margin_lending_fees", | |
235 | "margin_borrowed_base_price" | |
236 | ]: | |
c51687d2 | 237 | setattr(self, key, Amount(base_currency, hash_.get(key, 0))) |
f2da6589 | 238 | |
dd359bc0 | 239 | def __repr__(self): |
006a2084 IB |
240 | if self.exchange_total > 0: |
241 | if self.exchange_free > 0 and self.exchange_used > 0: | |
242 | exchange = " Exch: [✔{} + ❌{} = {}]".format(str(self.exchange_free), str(self.exchange_used), str(self.exchange_total)) | |
243 | elif self.exchange_free > 0: | |
244 | exchange = " Exch: [✔{}]".format(str(self.exchange_free)) | |
245 | else: | |
246 | exchange = " Exch: [❌{}]".format(str(self.exchange_used)) | |
247 | else: | |
248 | exchange = "" | |
249 | ||
250 | if self.margin_total > 0: | |
251 | if self.margin_free != 0 and self.margin_borrowed != 0: | |
252 | margin = " Margin: [✔{} + borrowed {} = {}]".format(str(self.margin_free), str(self.margin_borrowed), str(self.margin_total)) | |
253 | elif self.margin_free != 0: | |
254 | margin = " Margin: [✔{}]".format(str(self.margin_free)) | |
255 | else: | |
256 | margin = " Margin: [borrowed {}]".format(str(self.margin_borrowed)) | |
257 | elif self.margin_total < 0: | |
258 | margin = " Margin: [{} @@ {}/{}]".format(str(self.margin_total), | |
259 | str(self.margin_borrowed_base_price), | |
260 | str(self.margin_lending_fees)) | |
261 | else: | |
262 | margin = "" | |
263 | ||
264 | if self.margin_total != 0 and self.exchange_total != 0: | |
265 | total = " Total: [{}]".format(str(self.total)) | |
266 | else: | |
267 | total = "" | |
268 | ||
269 | return "Balance({}".format(self.currency) + "".join([exchange, margin, total]) + ")" | |
dd359bc0 IB |
270 | |
271 | class Trade: | |
006a2084 | 272 | def __init__(self, value_from, value_to, currency, market=None): |
dd359bc0 IB |
273 | # We have value_from of currency, and want to finish with value_to of |
274 | # that currency. value_* may not be in currency's terms | |
275 | self.currency = currency | |
276 | self.value_from = value_from | |
277 | self.value_to = value_to | |
278 | self.orders = [] | |
089d5d9d | 279 | self.market = market |
dd359bc0 | 280 | assert self.value_from.currency == self.value_to.currency |
006a2084 IB |
281 | if self.value_from != 0: |
282 | assert self.value_from.linked_to is not None and self.value_from.linked_to.currency == self.currency | |
283 | elif self.value_from.linked_to is None: | |
284 | self.value_from.linked_to = Amount(self.currency, 0) | |
dd359bc0 IB |
285 | self.base_currency = self.value_from.currency |
286 | ||
dd359bc0 IB |
287 | @property |
288 | def action(self): | |
289 | if self.value_from == self.value_to: | |
290 | return None | |
291 | if self.base_currency == self.currency: | |
292 | return None | |
293 | ||
5a72ded7 | 294 | if abs(self.value_from) < abs(self.value_to): |
006a2084 | 295 | return "acquire" |
dd359bc0 | 296 | else: |
006a2084 | 297 | return "dispose" |
dd359bc0 | 298 | |
cfab619d | 299 | def order_action(self, inverted): |
006a2084 | 300 | if (self.value_from < self.value_to) != inverted: |
350ed24d | 301 | return "buy" |
dd359bc0 | 302 | else: |
350ed24d | 303 | return "sell" |
dd359bc0 | 304 | |
006a2084 IB |
305 | @property |
306 | def trade_type(self): | |
307 | if self.value_from + self.value_to < 0: | |
308 | return "short" | |
309 | else: | |
310 | return "long" | |
311 | ||
1aa7d4fa | 312 | def filled_amount(self, in_base_currency=False): |
80cdd672 IB |
313 | filled_amount = 0 |
314 | for order in self.orders: | |
1aa7d4fa | 315 | filled_amount += order.filled_amount(in_base_currency=in_base_currency) |
80cdd672 IB |
316 | return filled_amount |
317 | ||
318 | def update_order(self, order, tick): | |
319 | new_order = None | |
320 | if tick in [0, 1, 3, 4, 6]: | |
321 | print("{}, tick {}, waiting".format(order, tick)) | |
322 | elif tick == 2: | |
5a72ded7 | 323 | new_order = self.prepare_order(compute_value=lambda x, y: (x[y] + x["average"]) / 2) |
80cdd672 IB |
324 | print("{}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) |
325 | elif tick ==5: | |
5a72ded7 | 326 | new_order = self.prepare_order(compute_value=lambda x, y: (x[y]*2 + x["average"]) / 3) |
80cdd672 IB |
327 | print("{}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) |
328 | elif tick >= 7: | |
329 | if tick == 7: | |
330 | print("{}, tick {}, fallbacking to market value".format(order, tick)) | |
331 | if (tick - 7) % 3 == 0: | |
5a72ded7 | 332 | new_order = self.prepare_order(compute_value="default") |
80cdd672 IB |
333 | print("{}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) |
334 | ||
335 | if new_order is not None: | |
336 | order.cancel() | |
337 | new_order.run() | |
338 | ||
deb8924c | 339 | def prepare_order(self, compute_value="default"): |
dd359bc0 | 340 | if self.action is None: |
5a72ded7 | 341 | return None |
6ca5a1ec | 342 | ticker = h.get_ticker(self.currency, self.base_currency, self.market) |
dd359bc0 | 343 | inverted = ticker["inverted"] |
f2097d71 IB |
344 | if inverted: |
345 | ticker = ticker["original"] | |
6ca5a1ec | 346 | rate = Computation.compute_value(ticker, self.order_action(inverted), compute_value=compute_value) |
f2097d71 | 347 | |
97922ff1 IB |
348 | # FIXME: Dust amount should be removed from there if they werent |
349 | # honored in other sales | |
f2097d71 | 350 | delta_in_base = abs(self.value_from - self.value_to) |
c11e4274 | 351 | # 9 BTC's worth of move (10 - 1 or 1 - 10 depending on case) |
dd359bc0 IB |
352 | |
353 | if not inverted: | |
1aa7d4fa | 354 | base_currency = self.base_currency |
350ed24d | 355 | # BTC |
006a2084 | 356 | if self.action == "dispose": |
1aa7d4fa IB |
357 | filled = self.filled_amount(in_base_currency=False) |
358 | delta = delta_in_base.in_currency(self.currency, self.market, rate=1/self.value_from.rate) | |
359 | # I have 10 BTC worth of FOO, and I want to sell 9 BTC | |
360 | # worth of it, computed first with rate 10 FOO = 1 BTC. | |
361 | # -> I "sell" "90" FOO at proposed rate "rate". | |
362 | ||
363 | delta = delta - filled | |
364 | # I already sold 60 FOO, 30 left | |
f2097d71 | 365 | else: |
1aa7d4fa IB |
366 | filled = self.filled_amount(in_base_currency=True) |
367 | delta = (delta_in_base - filled).in_currency(self.currency, self.market, rate=1/rate) | |
368 | # I want to buy 9 BTC worth of FOO, computed with rate | |
369 | # 10 FOO = 1 BTC | |
370 | # -> I "buy" "9 / rate" FOO at proposed rate "rate" | |
371 | ||
372 | # I already bought 3 / rate FOO, 6 / rate left | |
dd359bc0 | 373 | else: |
1aa7d4fa | 374 | base_currency = self.currency |
c11e4274 | 375 | # FOO |
1aa7d4fa IB |
376 | if self.action == "dispose": |
377 | filled = self.filled_amount(in_base_currency=True) | |
378 | # Base is FOO | |
379 | ||
380 | delta = (delta_in_base.in_currency(self.currency, self.market, rate=1/self.value_from.rate) | |
381 | - filled).in_currency(self.base_currency, self.market, rate=1/rate) | |
382 | # I have 10 BTC worth of FOO, and I want to sell 9 BTC worth of it | |
383 | # computed at rate 1 Foo = 0.01 BTC | |
384 | # Computation says I should sell it at 125 FOO / BTC | |
385 | # -> delta_in_base = 9 BTC | |
386 | # -> delta = (9 * 1/0.01 FOO) * 1/125 = 7.2 BTC | |
387 | # Action: "buy" "7.2 BTC" at rate "125" "FOO" on market | |
388 | ||
389 | # I already bought 300/125 BTC, only 600/125 left | |
390 | else: | |
391 | filled = self.filled_amount(in_base_currency=False) | |
392 | # Base is FOO | |
393 | ||
394 | delta = delta_in_base | |
395 | # I have 1 BTC worth of FOO, and I want to buy 9 BTC worth of it | |
396 | # At rate 100 Foo / BTC | |
397 | # Computation says I should buy it at 125 FOO / BTC | |
398 | # -> delta_in_base = 9 BTC | |
399 | # Action: "sell" "9 BTC" at rate "125" "FOO" on market | |
400 | ||
401 | delta = delta - filled | |
402 | # I already sold 4 BTC, only 5 left | |
dd359bc0 | 403 | |
006a2084 IB |
404 | close_if_possible = (self.value_to == 0) |
405 | ||
1aa7d4fa IB |
406 | if delta <= 0: |
407 | print("Less to do than already filled: {}".format(delta)) | |
5a72ded7 | 408 | return None |
80cdd672 | 409 | |
5a72ded7 | 410 | order = Order(self.order_action(inverted), |
1aa7d4fa | 411 | delta, rate, base_currency, self.trade_type, |
5a72ded7 IB |
412 | self.market, self, close_if_possible=close_if_possible) |
413 | self.orders.append(order) | |
414 | return order | |
dd359bc0 | 415 | |
dd359bc0 | 416 | def __repr__(self): |
006a2084 | 417 | return "Trade({} -> {} in {}, {})".format( |
dd359bc0 IB |
418 | self.value_from, |
419 | self.value_to, | |
420 | self.currency, | |
006a2084 | 421 | self.action) |
dd359bc0 | 422 | |
272b3cfb IB |
423 | def print_with_order(self): |
424 | print(self) | |
425 | for order in self.orders: | |
426 | print("\t", order, sep="") | |
dd359bc0 | 427 | |
272b3cfb | 428 | class Order: |
006a2084 | 429 | def __init__(self, action, amount, rate, base_currency, trade_type, market, |
80cdd672 | 430 | trade, close_if_possible=False): |
dd359bc0 IB |
431 | self.action = action |
432 | self.amount = amount | |
433 | self.rate = rate | |
434 | self.base_currency = base_currency | |
a9950fd0 | 435 | self.market = market |
350ed24d | 436 | self.trade_type = trade_type |
80cdd672 IB |
437 | self.results = [] |
438 | self.mouvements = [] | |
a9950fd0 | 439 | self.status = "pending" |
80cdd672 | 440 | self.trade = trade |
006a2084 | 441 | self.close_if_possible = close_if_possible |
5a72ded7 IB |
442 | self.id = None |
443 | self.fetch_cache_timestamp = None | |
dd359bc0 IB |
444 | |
445 | def __repr__(self): | |
006a2084 | 446 | return "Order({} {} {} at {} {} [{}]{})".format( |
dd359bc0 | 447 | self.action, |
350ed24d | 448 | self.trade_type, |
dd359bc0 IB |
449 | self.amount, |
450 | self.rate, | |
451 | self.base_currency, | |
006a2084 IB |
452 | self.status, |
453 | " ✂" if self.close_if_possible else "", | |
dd359bc0 IB |
454 | ) |
455 | ||
350ed24d IB |
456 | @property |
457 | def account(self): | |
458 | if self.trade_type == "long": | |
459 | return "exchange" | |
460 | else: | |
461 | return "margin" | |
462 | ||
5a72ded7 IB |
463 | @property |
464 | def open(self): | |
465 | return self.status == "open" | |
466 | ||
a9950fd0 IB |
467 | @property |
468 | def pending(self): | |
469 | return self.status == "pending" | |
470 | ||
471 | @property | |
472 | def finished(self): | |
fd8afa51 | 473 | return self.status == "closed" or self.status == "canceled" or self.status == "error" |
a9950fd0 | 474 | |
80cdd672 | 475 | def run(self): |
dd359bc0 | 476 | symbol = "{}/{}".format(self.amount.currency, self.base_currency) |
350ed24d | 477 | amount = round(self.amount, self.market.order_precision(symbol)).value |
dd359bc0 | 478 | |
6ca5a1ec | 479 | if TradeStore.debug: |
ecba1113 IB |
480 | print("market.create_order('{}', 'limit', '{}', {}, price={}, account={})".format( |
481 | symbol, self.action, amount, self.rate, self.account)) | |
80cdd672 | 482 | self.results.append({"debug": True, "id": -1}) |
dd359bc0 IB |
483 | else: |
484 | try: | |
80cdd672 | 485 | self.results.append(self.market.create_order(symbol, 'limit', self.action, amount, price=self.rate, account=self.account)) |
df9e4e7f IB |
486 | except ExchangeNotAvailable: |
487 | # Impossible to honor the order (dust amount) | |
488 | self.status = "closed" | |
489 | self.mark_finished_order() | |
490 | return | |
fd8afa51 IB |
491 | except Exception as e: |
492 | self.status = "error" | |
ecba1113 IB |
493 | print("error when running market.create_order('{}', 'limit', '{}', {}, price={}, account={})".format( |
494 | symbol, self.action, amount, self.rate, self.account)) | |
fd8afa51 IB |
495 | self.error_message = str("{}: {}".format(e.__class__.__name__, e)) |
496 | print(self.error_message) | |
5a72ded7 IB |
497 | return |
498 | self.id = self.results[0]["id"] | |
499 | self.status = "open" | |
dd359bc0 | 500 | |
a9950fd0 | 501 | def get_status(self): |
6ca5a1ec | 502 | if TradeStore.debug: |
80cdd672 | 503 | return self.status |
dd359bc0 | 504 | # other states are "closed" and "canceled" |
5a72ded7 | 505 | if not self.finished: |
80cdd672 | 506 | self.fetch() |
5a72ded7 | 507 | if self.finished: |
80cdd672 | 508 | self.mark_finished_order() |
dd359bc0 IB |
509 | return self.status |
510 | ||
80cdd672 | 511 | def mark_finished_order(self): |
6ca5a1ec | 512 | if TradeStore.debug: |
80cdd672 IB |
513 | return |
514 | if self.status == "closed": | |
006a2084 IB |
515 | if self.trade_type == "short" and self.action == "buy" and self.close_if_possible: |
516 | self.market.close_margin_position(self.amount.currency, self.base_currency) | |
517 | ||
80cdd672 | 518 | def fetch(self, force=False): |
6ca5a1ec | 519 | if TradeStore.debug or (not force and self.fetch_cache_timestamp is not None |
80cdd672 IB |
520 | and time.time() - self.fetch_cache_timestamp < 10): |
521 | return | |
522 | self.fetch_cache_timestamp = time.time() | |
523 | ||
5a72ded7 IB |
524 | result = self.market.fetch_order(self.id) |
525 | self.results.append(result) | |
526 | ||
006a2084 | 527 | self.status = result["status"] |
80cdd672 IB |
528 | # Time at which the order started |
529 | self.timestamp = result["datetime"] | |
530 | self.fetch_mouvements() | |
531 | ||
532 | # FIXME: consider open order with dust remaining as closed | |
533 | ||
80cdd672 | 534 | def dust_amount_remaining(self): |
5a72ded7 | 535 | return self.remaining_amount() < Amount(self.amount.currency, D("0.001")) |
80cdd672 | 536 | |
80cdd672 IB |
537 | def remaining_amount(self): |
538 | if self.status == "open": | |
539 | self.fetch() | |
1aa7d4fa | 540 | return self.amount - self.filled_amount() |
80cdd672 | 541 | |
1aa7d4fa | 542 | def filled_amount(self, in_base_currency=False): |
80cdd672 IB |
543 | if self.status == "open": |
544 | self.fetch() | |
1aa7d4fa | 545 | filled_amount = 0 |
80cdd672 | 546 | for mouvement in self.mouvements: |
1aa7d4fa IB |
547 | if in_base_currency: |
548 | filled_amount += mouvement.total_in_base | |
549 | else: | |
550 | filled_amount += mouvement.total | |
80cdd672 IB |
551 | return filled_amount |
552 | ||
553 | def fetch_mouvements(self): | |
df9e4e7f IB |
554 | try: |
555 | mouvements = self.market.privatePostReturnOrderTrades({"orderNumber": self.id}) | |
556 | except ExchangeError: | |
557 | mouvements = [] | |
80cdd672 IB |
558 | self.mouvements = [] |
559 | ||
560 | for mouvement_hash in mouvements: | |
561 | self.mouvements.append(Mouvement(self.amount.currency, | |
562 | self.base_currency, mouvement_hash)) | |
006a2084 | 563 | |
272b3cfb | 564 | def cancel(self): |
6ca5a1ec | 565 | if TradeStore.debug: |
80cdd672 IB |
566 | self.status = "canceled" |
567 | return | |
5a72ded7 | 568 | self.market.cancel_order(self.id) |
80cdd672 IB |
569 | self.fetch() |
570 | ||
571 | class Mouvement: | |
572 | def __init__(self, currency, base_currency, hash_): | |
573 | self.currency = currency | |
574 | self.base_currency = base_currency | |
df9e4e7f IB |
575 | self.id = hash_.get("tradeID") |
576 | self.action = hash_.get("type") | |
577 | self.fee_rate = D(hash_.get("fee", -1)) | |
578 | try: | |
579 | self.date = datetime.strptime(hash_.get("date", ""), '%Y-%m-%d %H:%M:%S') | |
580 | except ValueError: | |
581 | self.date = None | |
582 | self.rate = D(hash_.get("rate", 0)) | |
583 | self.total = Amount(currency, hash_.get("amount", 0)) | |
80cdd672 | 584 | # rate * total = total_in_base |
df9e4e7f | 585 | self.total_in_base = Amount(base_currency, hash_.get("total", 0)) |
272b3cfb | 586 | |
5a72ded7 | 587 | if __name__ == '__main__': # pragma: no cover |
6ca5a1ec IB |
588 | from market import market |
589 | h.print_orders(market) |