]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - market.py
Merge branch 'dev'
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / market.py
CommitLineData
5321200c 1from ccxt import AuthenticationError, ExchangeError, NotSupported, RequestTimeout, InvalidNonce
774c099c 2import ccxt_wrapper as ccxt
f86ee140 3import time
30700830 4import dbs
f86ee140 5from store import *
aca4d437 6from cachetools.func import ttl_cache
1f117ac7 7from datetime import datetime
e7d7c0e5 8import datetime
337c8286 9from retry import retry
1f117ac7 10import portfolio
4c51aa71 11
f86ee140
IB
12class Market:
13 debug = False
14 ccxt = None
15 report = None
16 trades = None
17 balances = None
ef8fa5e5 18 options = None
ecba1113 19
35667b31 20 def __init__(self, ccxt_instance, args, **kwargs):
07fa7a4b
IB
21 self.args = args
22 self.debug = args.debug
f86ee140
IB
23 self.ccxt = ccxt_instance
24 self.ccxt._market = self
07fa7a4b 25 self.report = ReportStore(self, verbose_print=(not args.quiet))
f86ee140
IB
26 self.trades = TradeStore(self)
27 self.balances = BalanceStore(self)
1f117ac7
IB
28 self.processor = Processor(self)
29
ef8fa5e5 30 self.options = kwargs.get("options", {})
30700830 31 for key in ["user_id", "market_id"]:
35667b31 32 setattr(self, key, kwargs.get(key, None))
f86ee140 33
e7d7c0e5 34 self.report.log_market(self.args)
90d7423e 35
f86ee140 36 @classmethod
35667b31 37 def from_config(cls, config, args, **kwargs):
1f117ac7 38 config["apiKey"] = config.pop("key", None)
d24bb10c 39
f86ee140
IB
40 ccxt_instance = ccxt.poloniexE(config)
41
35667b31 42 return cls(ccxt_instance, args, **kwargs)
1f117ac7
IB
43
44 def store_report(self):
9bde69bf 45 self.report.merge(Portfolio.report)
e7d7c0e5 46 date = datetime.datetime.now()
a42d6cc8 47 if self.args.report_path is not None:
b4e0ba0b 48 self.store_file_report(date)
30700830 49 if dbs.psql_connected() and self.args.report_db:
b4e0ba0b 50 self.store_database_report(date)
30700830 51 if dbs.redis_connected() and self.args.report_redis:
1593c7a9 52 self.store_redis_report(date)
b4e0ba0b
IB
53
54 def store_file_report(self, date):
1f117ac7 55 try:
a42d6cc8 56 report_file = "{}/{}_{}".format(self.args.report_path, date.isoformat(), self.user_id)
b4e0ba0b
IB
57 with open(report_file + ".json", "w") as f:
58 f.write(self.report.to_json())
59 with open(report_file + ".log", "w") as f:
60 f.write("\n".join(map(lambda x: x[1], self.report.print_logs)))
1f117ac7
IB
61 except Exception as e:
62 print("impossible to store report file: {}; {}".format(e.__class__.__name__, e))
63
b4e0ba0b
IB
64 def store_database_report(self, date):
65 try:
66 report_query = 'INSERT INTO reports("date", "market_config_id", "debug") VALUES (%s, %s, %s) RETURNING id;'
67 line_query = 'INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);'
30700830 68 cursor = dbs.psql.cursor()
b4e0ba0b
IB
69 cursor.execute(report_query, (date, self.market_id, self.debug))
70 report_id = cursor.fetchone()[0]
71 for date, type_, payload in self.report.to_json_array():
72 cursor.execute(line_query, (date, report_id, type_, payload))
73
30700830 74 dbs.psql.commit()
b4e0ba0b 75 cursor.close()
b4e0ba0b
IB
76 except Exception as e:
77 print("impossible to store report to database: {}; {}".format(e.__class__.__name__, e))
78
1593c7a9
IB
79 def store_redis_report(self, date):
80 try:
1593c7a9
IB
81 for type_, log in self.report.to_json_redis():
82 key = "/cryptoportfolio/{}/{}/{}".format(self.market_id, date.isoformat(), type_)
30700830 83 dbs.redis.set(key, log, ex=31*24*60*60)
1593c7a9 84 key = "/cryptoportfolio/{}/latest/{}".format(self.market_id, type_)
30700830 85 dbs.redis.set(key, log)
17fd3f75 86 key = "/cryptoportfolio/{}/latest/date".format(self.market_id)
30700830 87 dbs.redis.set(key, date.isoformat())
1593c7a9
IB
88 except Exception as e:
89 print("impossible to store report to redis: {}; {}".format(e.__class__.__name__, e))
90
1f117ac7
IB
91 def process(self, actions, before=False, after=False):
92 try:
5321200c 93 self.ccxt.check_required_credentials()
ceb7fc4c
IB
94 for action in actions:
95 if bool(before) is bool(after):
44518535 96 self.processor.process(action, steps="all", options=self.options)
ceb7fc4c 97 elif before:
44518535 98 self.processor.process(action, steps="before", options=self.options)
ceb7fc4c 99 elif after:
44518535 100 self.processor.process(action, steps="after", options=self.options)
5321200c
IB
101 except AuthenticationError:
102 self.report.log_error("market_authentication", message="Impossible to authenticate to market")
1f117ac7 103 except Exception as e:
4ae84fb7
IB
104 import traceback
105 self.report.log_error("market_process", exception=e, message=traceback.format_exc())
1f117ac7
IB
106 finally:
107 self.store_report()
f86ee140 108
b47d7b54 109 @retry((RequestTimeout, InvalidNonce), tries=5)
f86ee140
IB
110 def move_balances(self):
111 needed_in_margin = {}
112 moving_to_margin = {}
113
aca4d437
IB
114 for currency, balance in self.balances.all.items():
115 needed_in_margin[currency] = balance.margin_in_position - balance.margin_pending_gain
116 for trade in self.trades.pending:
117 needed_in_margin.setdefault(trade.base_currency, 0)
f86ee140 118 if trade.trade_type == "short":
aca4d437 119 needed_in_margin[trade.base_currency] -= trade.delta
f86ee140 120 for currency, needed in needed_in_margin.items():
aca4d437 121 current_balance = self.balances.all[currency].margin_available
f86ee140
IB
122 moving_to_margin[currency] = (needed - current_balance)
123 delta = moving_to_margin[currency].value
337c8286
IB
124 action = "Moving {} from exchange to margin".format(moving_to_margin[currency])
125
aca4d437 126 if self.debug and delta != 0:
337c8286 127 self.report.log_debug_action(action)
f86ee140 128 continue
337c8286
IB
129 try:
130 if delta > 0:
131 self.ccxt.transfer_balance(currency, delta, "exchange", "margin")
132 elif delta < 0:
133 self.ccxt.transfer_balance(currency, -delta, "margin", "exchange")
b47d7b54 134 except (RequestTimeout, InvalidNonce) as e:
337c8286
IB
135 self.report.log_error(action, message="Retrying", exception=e)
136 self.report.log_move_balances(needed_in_margin, moving_to_margin)
137 self.balances.fetch_balances()
138 raise e
f86ee140
IB
139 self.report.log_move_balances(needed_in_margin, moving_to_margin)
140
141 self.balances.fetch_balances()
142
aca4d437 143 @ttl_cache(ttl=3600)
f86ee140 144 def fetch_fees(self):
aca4d437
IB
145 return self.ccxt.fetch_fees()
146
147 @ttl_cache(maxsize=20, ttl=5)
148 def get_tickers(self, refresh=False):
149 try:
150 return self.ccxt.fetch_tickers()
151 except NotSupported:
152 return None
f86ee140 153
aca4d437 154 @ttl_cache(maxsize=20, ttl=5)
f86ee140
IB
155 def get_ticker(self, c1, c2, refresh=False):
156 def invert(ticker):
157 return {
158 "inverted": True,
159 "average": (1/ticker["bid"] + 1/ticker["ask"]) / 2,
160 "original": ticker,
161 }
162 def augment_ticker(ticker):
163 ticker.update({
164 "inverted": False,
165 "average": (ticker["bid"] + ticker["ask"] ) / 2,
166 })
7192b2e1 167 return ticker
f86ee140 168
aca4d437
IB
169 tickers = self.get_tickers()
170 if tickers is None:
f86ee140 171 try:
7192b2e1 172 ticker = augment_ticker(self.ccxt.fetch_ticker("{}/{}".format(c1, c2)))
f86ee140 173 except ExchangeError:
aca4d437 174 try:
7192b2e1 175 ticker = invert(augment_ticker(self.ccxt.fetch_ticker("{}/{}".format(c2, c1))))
aca4d437
IB
176 except ExchangeError:
177 ticker = None
178 else:
179 if "{}/{}".format(c1, c2) in tickers:
7192b2e1 180 ticker = augment_ticker(tickers["{}/{}".format(c1, c2)])
aca4d437 181 elif "{}/{}".format(c2, c1) in tickers:
7192b2e1 182 ticker = invert(augment_ticker(tickers["{}/{}".format(c2, c1)]))
aca4d437
IB
183 else:
184 ticker = None
185 return ticker
f86ee140
IB
186
187 def follow_orders(self, sleep=None):
188 if sleep is None:
189 sleep = 7 if self.debug else 30
190 if self.debug:
191 self.report.log_debug_action("Set follow_orders tick to {}s".format(sleep))
192 tick = 0
193 self.report.log_stage("follow_orders_begin")
194 while len(self.trades.all_orders(state="open")) > 0:
195 time.sleep(sleep)
196 tick += 1
197 open_orders = self.trades.all_orders(state="open")
198 self.report.log_stage("follow_orders_tick_{}".format(tick))
199 self.report.log_orders(open_orders, tick=tick)
200 for order in open_orders:
7ba831c5
IB
201 status = order.get_status()
202 if status != "open":
f86ee140
IB
203 self.report.log_order(order, tick, finished=True)
204 else:
205 order.trade.update_order(order, tick)
7ba831c5
IB
206 if status == "error_disappeared":
207 self.report.log_error("follow_orders",
208 message="{} disappeared, recreating it".format(order))
af928d32 209 new_order = order.trade.prepare_order(
7ba831c5 210 compute_value=order.trade.tick_actions_recreate(tick))
84c9fe33
IB
211 if new_order is not None:
212 new_order.run()
213 self.report.log_order(order, tick, new_order=new_order)
7ba831c5 214
f86ee140
IB
215 self.report.log_stage("follow_orders_end")
216
9db7d156 217 def prepare_trades(self, base_currency="BTC", liquidity="medium",
96959cea
IB
218 compute_value="average", repartition=None, only=None,
219 available_balance_only=False):
9db7d156 220
7bd830a8
IB
221 self.report.log_stage("prepare_trades",
222 base_currency=base_currency, liquidity=liquidity,
9db7d156 223 compute_value=compute_value, only=only,
96959cea 224 repartition=repartition, available_balance_only=available_balance_only)
f86ee140 225
96959cea 226 if available_balance_only:
3d6f74ee
IB
227 repartition, total_base_value, values_in_base = self.balances.available_balances_for_repartition(
228 base_currency=base_currency, liquidity=liquidity,
229 repartition=repartition, compute_value=compute_value)
96959cea 230 else:
3d6f74ee
IB
231 values_in_base = self.balances.in_currency(base_currency,
232 compute_value=compute_value)
96959cea 233 total_base_value = sum(values_in_base.values())
9db7d156
IB
234 new_repartition = self.balances.dispatch_assets(total_base_value,
235 liquidity=liquidity, repartition=repartition)
96959cea
IB
236 if available_balance_only:
237 for currency, amount in values_in_base.items():
3d6f74ee
IB
238 if currency != base_currency and currency not in new_repartition:
239 new_repartition[currency] = amount
96959cea 240
9db7d156 241 self.trades.compute_trades(values_in_base, new_repartition, only=only)
2308a1c4 242
ceb7fc4c 243 def print_tickers(self, base_currency="BTC"):
1f117ac7
IB
244 if base_currency is not None:
245 self.report.print_log("total:")
246 self.report.print_log(sum(self.balances.in_currency(base_currency).values()))
247
248class Processor:
249 scenarios = {
81d1db51
IB
250 "wait_for_cryptoportfolio": [
251 {
252 "name": "wait",
253 "number": 1,
254 "before": False,
255 "after": True,
256 "wait_for_recent": {},
257 },
258 ],
ceb7fc4c
IB
259 "print_balances": [
260 {
261 "name": "print_balances",
262 "number": 1,
3a15ffc7
IB
263 "fetch_balances_begin": {
264 "log_tickers": True,
265 "add_usdt": True,
266 "add_portfolio": True
267 },
ceb7fc4c
IB
268 "print_tickers": { "base_currency": "BTC" },
269 }
270 ],
81d1db51
IB
271 "print_orders": [
272 {
273 "name": "wait",
274 "number": 1,
ceb7fc4c
IB
275 "before": True,
276 "after": False,
81d1db51
IB
277 "wait_for_recent": {},
278 },
279 {
280 "name": "make_orders",
281 "number": 2,
282 "before": False,
283 "after": True,
bb127bc8 284 "fetch_balances_begin": {},
81d1db51
IB
285 "prepare_trades": { "compute_value": "average" },
286 "prepare_orders": { "compute_value": "average" },
287 },
288 ],
1f117ac7
IB
289 "sell_needed": [
290 {
bb127bc8 291 "name": "print_balances",
1f117ac7 292 "number": 0,
bb127bc8
IB
293 "before": True,
294 "after": False,
295 "fetch_balances_begin": {
296 "checkpoint": "end",
297 "log_tickers": True,
3a15ffc7 298 "add_usdt": True,
bb127bc8
IB
299 "add_portfolio": True
300 },
301 },
302 {
303 "name": "wait",
304 "number": 1,
1f117ac7
IB
305 "before": False,
306 "after": True,
307 "wait_for_recent": {},
308 },
309 {
310 "name": "sell",
bb127bc8 311 "number": 2,
1f117ac7
IB
312 "before": False,
313 "after": True,
bb127bc8
IB
314 "fetch_balances_begin": {},
315 "fetch_balances_end": {},
1f117ac7
IB
316 "prepare_trades": {},
317 "prepare_orders": { "only": "dispose", "compute_value": "average" },
318 "run_orders": {},
319 "follow_orders": {},
320 "close_trades": {},
321 },
322 {
323 "name": "buy",
bb127bc8 324 "number": 3,
1f117ac7
IB
325 "before": False,
326 "after": True,
bb127bc8
IB
327 "fetch_balances_begin": {},
328 "fetch_balances_end": {
329 "checkpoint": "begin",
3a15ffc7 330 "add_usdt": True,
bb127bc8
IB
331 "log_tickers": True
332 },
96959cea 333 "prepare_trades": { "only": "acquire", "available_balance_only": True },
1f117ac7
IB
334 "prepare_orders": { "only": "acquire", "compute_value": "average" },
335 "move_balances": {},
336 "run_orders": {},
337 "follow_orders": {},
338 "close_trades": {},
339 },
340 ],
341 "sell_all": [
342 {
343 "name": "all_sell",
344 "number": 1,
345 "before": True,
346 "after": False,
bb127bc8
IB
347 "fetch_balances_begin": {
348 "checkpoint": "end",
349 "log_tickers": True,
3a15ffc7 350 "add_usdt": True,
bb127bc8
IB
351 "add_portfolio": True
352 },
353 "fetch_balances_end": {},
1f117ac7
IB
354 "prepare_trades": { "repartition": { "base_currency": (1, "long") } },
355 "prepare_orders": { "compute_value": "average" },
356 "run_orders": {},
357 "follow_orders": {},
358 "close_trades": {},
359 },
360 {
361 "name": "wait",
362 "number": 2,
363 "before": False,
364 "after": True,
365 "wait_for_recent": {},
366 },
367 {
368 "name": "all_buy",
369 "number": 3,
370 "before": False,
371 "after": True,
bb127bc8
IB
372 "fetch_balances_begin": {},
373 "fetch_balances_end": {
374 "checkpoint": "begin",
3a15ffc7 375 "add_usdt": True,
bb127bc8
IB
376 "log_tickers": True
377 },
96959cea 378 "prepare_trades": { "available_balance_only": True },
1f117ac7
IB
379 "prepare_orders": { "compute_value": "average" },
380 "move_balances": {},
381 "run_orders": {},
382 "follow_orders": {},
383 "close_trades": {},
384 },
385 ]
386 }
387
388 ordered_actions = [
389 "wait_for_recent", "prepare_trades", "prepare_orders",
390 "move_balances", "run_orders", "follow_orders",
ceb7fc4c 391 "close_trades", "print_tickers"]
1f117ac7
IB
392
393 def __init__(self, market):
394 self.market = market
395
396 def select_steps(self, scenario, step):
397 if step == "all":
398 return scenario
399 elif step == "before" or step == "after":
ceb7fc4c 400 return list(filter(lambda x: x.get(step, False), scenario))
1f117ac7
IB
401 elif type(step) == int:
402 return [scenario[step-1]]
403 elif type(step) == str:
404 return list(filter(lambda x: x["name"] == step, scenario))
405 else:
406 raise TypeError("Unknown step {}".format(step))
407
ceb7fc4c
IB
408 def can_process(self, scenario_name):
409 return scenario_name in self.scenarios
410
44518535 411 def process(self, scenario_name, steps="all", options={}):
ceb7fc4c
IB
412 if not self.can_process(scenario_name):
413 raise TypeError("Unknown scenario {}".format(scenario_name))
1f117ac7
IB
414 scenario = self.scenarios[scenario_name]
415 selected_steps = []
416
417 if type(steps) == str or type(steps) == int:
418 selected_steps += self.select_steps(scenario, steps)
419 else:
420 for step in steps:
421 selected_steps += self.select_steps(scenario, step)
422 for step in selected_steps:
44518535 423 self.process_step(scenario_name, step, options)
1f117ac7 424
44518535 425 def process_step(self, scenario_name, step, options):
1f117ac7
IB
426 process_name = "process_{}__{}_{}".format(scenario_name, step["number"], step["name"])
427 self.market.report.log_stage("{}_begin".format(process_name))
9b697863 428
bb127bc8 429 if "fetch_balances_begin" in step:
8e648fd5
IB
430 self.run_action("fetch_balances", step["fetch_balances_begin"],
431 dict(options, tag="{}_begin".format(process_name)))
1f117ac7
IB
432
433 for action in self.ordered_actions:
434 if action in step:
44518535 435 self.run_action(action, step[action], options)
1f117ac7 436
bb127bc8 437 if "fetch_balances_end" in step:
8e648fd5
IB
438 self.run_action("fetch_balances", step["fetch_balances_end"],
439 dict(options, tag="{}_end".format(process_name)))
bb127bc8 440
1f117ac7
IB
441 self.market.report.log_stage("{}_end".format(process_name))
442
443 def method_arguments(self, action):
444 import inspect
445
446 if action == "wait_for_recent":
ada1b5f1 447 method = Portfolio.wait_for_recent
1f117ac7
IB
448 elif action == "prepare_trades":
449 method = self.market.prepare_trades
450 elif action == "prepare_orders":
451 method = self.market.trades.prepare_orders
452 elif action == "move_balances":
453 method = self.market.move_balances
454 elif action == "run_orders":
455 method = self.market.trades.run_orders
456 elif action == "follow_orders":
457 method = self.market.follow_orders
458 elif action == "close_trades":
459 method = self.market.trades.close_trades
ceb7fc4c
IB
460 elif action == "print_tickers":
461 method = self.market.print_tickers
8e648fd5
IB
462 elif action == "fetch_balances":
463 method = self.market.balances.fetch_balances
1f117ac7
IB
464
465 signature = inspect.getfullargspec(method)
466 defaults = signature.defaults or []
467 kwargs = signature.args[-len(defaults):]
468
469 return [method, kwargs]
470
44518535 471 def parse_args(self, action, default_args, options):
1f117ac7 472 method, allowed_arguments = self.method_arguments(action)
44518535 473 args = {k: v for k, v in {**default_args, **options}.items() if k in allowed_arguments }
1f117ac7
IB
474
475 if "repartition" in args and "base_currency" in args["repartition"]:
476 r = args["repartition"]
477 r[args.get("base_currency", "BTC")] = r.pop("base_currency")
478
479 return method, args
480
44518535
IB
481 def run_action(self, action, default_args, options):
482 method, args = self.parse_args(action, default_args, options)
1f117ac7 483
ada1b5f1 484 method(**args)