1 from ccxt
import AuthenticationError
, ExchangeError
, NotSupported
, RequestTimeout
, InvalidNonce
2 import ccxt_wrapper
as ccxt
6 from cachetools
.func
import ttl_cache
7 from datetime
import datetime
9 from retry
import retry
19 def __init__(self
, ccxt_instance
, args
, **kwargs
):
21 self
.debug
= args
.debug
22 self
.ccxt
= ccxt_instance
23 self
.ccxt
._market
= self
24 self
.report
= ReportStore(self
, verbose_print
=(not args
.quiet
))
25 self
.trades
= TradeStore(self
)
26 self
.balances
= BalanceStore(self
)
27 self
.processor
= Processor(self
)
29 for key
in ["user_id", "market_id"]:
30 setattr(self
, key
, kwargs
.get(key
, None))
32 self
.report
.log_market(self
.args
)
35 def from_config(cls
, config
, args
, **kwargs
):
36 config
["apiKey"] = config
.pop("key", None)
38 ccxt_instance
= ccxt
.poloniexE(config
)
40 return cls(ccxt_instance
, args
, **kwargs
)
42 def store_report(self
):
43 self
.report
.merge(Portfolio
.report
)
44 date
= datetime
.datetime
.now()
45 if self
.args
.report_path
is not None:
46 self
.store_file_report(date
)
47 if dbs
.psql_connected() and self
.args
.report_db
:
48 self
.store_database_report(date
)
49 if dbs
.redis_connected() and self
.args
.report_redis
:
50 self
.store_redis_report(date
)
52 def store_file_report(self
, date
):
54 report_file
= "{}/{}_{}".format(self
.args
.report_path
, date
.isoformat(), self
.user_id
)
55 with open(report_file
+ ".json", "w") as f
:
56 f
.write(self
.report
.to_json())
57 with open(report_file
+ ".log", "w") as f
:
58 f
.write("\n".join(map(lambda x
: x
[1], self
.report
.print_logs
)))
59 except Exception as e
:
60 print("impossible to store report file: {}; {}".format(e
.__class
__.__name
__, e
))
62 def store_database_report(self
, date
):
64 report_query
= 'INSERT INTO reports("date", "market_config_id", "debug") VALUES (%s, %s, %s) RETURNING id;'
65 line_query
= 'INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);'
66 cursor
= dbs
.psql
.cursor()
67 cursor
.execute(report_query
, (date
, self
.market_id
, self
.debug
))
68 report_id
= cursor
.fetchone()[0]
69 for date
, type_
, payload
in self
.report
.to_json_array():
70 cursor
.execute(line_query
, (date
, report_id
, type_
, payload
))
74 except Exception as e
:
75 print("impossible to store report to database: {}; {}".format(e
.__class
__.__name
__, e
))
77 def store_redis_report(self
, date
):
79 for type_
, log
in self
.report
.to_json_redis():
80 key
= "/cryptoportfolio/{}/{}/{}".format(self
.market_id
, date
.isoformat(), type_
)
81 dbs
.redis
.set(key
, log
, ex
=31*24*60*60)
82 key
= "/cryptoportfolio/{}/latest/{}".format(self
.market_id
, type_
)
83 dbs
.redis
.set(key
, log
)
84 key
= "/cryptoportfolio/{}/latest/date".format(self
.market_id
)
85 dbs
.redis
.set(key
, date
.isoformat())
86 except Exception as e
:
87 print("impossible to store report to redis: {}; {}".format(e
.__class
__.__name
__, e
))
89 def process(self
, actions
, before
=False, after
=False):
91 self
.ccxt
.check_required_credentials()
92 for action
in actions
:
93 if bool(before
) is bool(after
):
94 self
.processor
.process(action
, steps
="all")
96 self
.processor
.process(action
, steps
="before")
98 self
.processor
.process(action
, steps
="after")
99 except AuthenticationError
:
100 self
.report
.log_error("market_authentication", message
="Impossible to authenticate to market")
101 except Exception as e
:
103 self
.report
.log_error("market_process", exception
=e
, message
=traceback
.format_exc())
107 @retry((RequestTimeout
, InvalidNonce
), tries
=5)
108 def move_balances(self
):
109 needed_in_margin
= {}
110 moving_to_margin
= {}
112 for currency
, balance
in self
.balances
.all
.items():
113 needed_in_margin
[currency
] = balance
.margin_in_position
- balance
.margin_pending_gain
114 for trade
in self
.trades
.pending
:
115 needed_in_margin
.setdefault(trade
.base_currency
, 0)
116 if trade
.trade_type
== "short":
117 needed_in_margin
[trade
.base_currency
] -= trade
.delta
118 for currency
, needed
in needed_in_margin
.items():
119 current_balance
= self
.balances
.all
[currency
].margin_available
120 moving_to_margin
[currency
] = (needed
- current_balance
)
121 delta
= moving_to_margin
[currency
].value
122 action
= "Moving {} from exchange to margin".format(moving_to_margin
[currency
])
124 if self
.debug
and delta
!= 0:
125 self
.report
.log_debug_action(action
)
129 self
.ccxt
.transfer_balance(currency
, delta
, "exchange", "margin")
131 self
.ccxt
.transfer_balance(currency
, -delta
, "margin", "exchange")
132 except (RequestTimeout
, InvalidNonce
) as e
:
133 self
.report
.log_error(action
, message
="Retrying", exception
=e
)
134 self
.report
.log_move_balances(needed_in_margin
, moving_to_margin
)
135 self
.balances
.fetch_balances()
137 self
.report
.log_move_balances(needed_in_margin
, moving_to_margin
)
139 self
.balances
.fetch_balances()
142 def fetch_fees(self
):
143 return self
.ccxt
.fetch_fees()
145 @ttl_cache(maxsize
=20, ttl
=5)
146 def get_tickers(self
, refresh
=False):
148 return self
.ccxt
.fetch_tickers()
152 @ttl_cache(maxsize
=20, ttl
=5)
153 def get_ticker(self
, c1
, c2
, refresh
=False):
157 "average": (1/ticker
["bid"] + 1/ticker
["ask"]) / 2,
160 def augment_ticker(ticker
):
163 "average": (ticker
["bid"] + ticker
["ask"] ) / 2,
167 tickers
= self
.get_tickers()
170 ticker
= augment_ticker(self
.ccxt
.fetch_ticker("{}/{}".format(c1
, c2
)))
171 except ExchangeError
:
173 ticker
= invert(augment_ticker(self
.ccxt
.fetch_ticker("{}/{}".format(c2
, c1
))))
174 except ExchangeError
:
177 if "{}/{}".format(c1
, c2
) in tickers
:
178 ticker
= augment_ticker(tickers
["{}/{}".format(c1
, c2
)])
179 elif "{}/{}".format(c2
, c1
) in tickers
:
180 ticker
= invert(augment_ticker(tickers
["{}/{}".format(c2
, c1
)]))
185 def follow_orders(self
, sleep
=None):
187 sleep
= 7 if self
.debug
else 30
189 self
.report
.log_debug_action("Set follow_orders tick to {}s".format(sleep
))
191 self
.report
.log_stage("follow_orders_begin")
192 while len(self
.trades
.all_orders(state
="open")) > 0:
195 open_orders
= self
.trades
.all_orders(state
="open")
196 self
.report
.log_stage("follow_orders_tick_{}".format(tick
))
197 self
.report
.log_orders(open_orders
, tick
=tick
)
198 for order
in open_orders
:
199 status
= order
.get_status()
201 self
.report
.log_order(order
, tick
, finished
=True)
203 order
.trade
.update_order(order
, tick
)
204 if status
== "error_disappeared":
205 self
.report
.log_error("follow_orders",
206 message
="{} disappeared, recreating it".format(order
))
207 new_order
= order
.trade
.prepare_order(
208 compute_value
=order
.trade
.tick_actions_recreate(tick
))
209 if new_order
is not None:
211 self
.report
.log_order(order
, tick
, new_order
=new_order
)
213 self
.report
.log_stage("follow_orders_end")
215 def prepare_trades(self
, base_currency
="BTC", liquidity
="medium",
216 compute_value
="average", repartition
=None, only
=None,
217 available_balance_only
=False):
219 self
.report
.log_stage("prepare_trades",
220 base_currency
=base_currency
, liquidity
=liquidity
,
221 compute_value
=compute_value
, only
=only
,
222 repartition
=repartition
, available_balance_only
=available_balance_only
)
224 if available_balance_only
:
225 repartition
, total_base_value
, values_in_base
= self
.balances
.available_balances_for_repartition(
226 base_currency
=base_currency
, liquidity
=liquidity
,
227 repartition
=repartition
, compute_value
=compute_value
)
229 values_in_base
= self
.balances
.in_currency(base_currency
,
230 compute_value
=compute_value
)
231 total_base_value
= sum(values_in_base
.values())
232 new_repartition
= self
.balances
.dispatch_assets(total_base_value
,
233 liquidity
=liquidity
, repartition
=repartition
)
234 if available_balance_only
:
235 for currency
, amount
in values_in_base
.items():
236 if currency
!= base_currency
and currency
not in new_repartition
:
237 new_repartition
[currency
] = amount
239 self
.trades
.compute_trades(values_in_base
, new_repartition
, only
=only
)
241 def print_tickers(self
, base_currency
="BTC"):
242 if base_currency
is not None:
243 self
.report
.print_log("total:")
244 self
.report
.print_log(sum(self
.balances
.in_currency(base_currency
).values()))
248 "wait_for_cryptoportfolio": [
254 "wait_for_recent": {},
259 "name": "print_balances",
261 "fetch_balances_begin": {
264 "add_portfolio": True
266 "print_tickers": { "base_currency": "BTC" }
,
275 "wait_for_recent": {},
278 "name": "make_orders",
282 "fetch_balances_begin": {},
283 "prepare_trades": { "compute_value": "average" }
,
284 "prepare_orders": { "compute_value": "average" }
,
289 "name": "print_balances",
293 "fetch_balances_begin": {
297 "add_portfolio": True
305 "wait_for_recent": {},
312 "fetch_balances_begin": {},
313 "fetch_balances_end": {},
314 "prepare_trades": {},
315 "prepare_orders": { "only": "dispose", "compute_value": "average" }
,
325 "fetch_balances_begin": {},
326 "fetch_balances_end": {
327 "checkpoint": "begin",
331 "prepare_trades": { "only": "acquire", "available_balance_only": True }
,
332 "prepare_orders": { "only": "acquire", "compute_value": "average" }
,
345 "fetch_balances_begin": {
349 "add_portfolio": True
351 "fetch_balances_end": {},
352 "prepare_trades": { "repartition": { "base_currency": (1, "long") }
},
353 "prepare_orders": { "compute_value": "average" }
,
363 "wait_for_recent": {},
370 "fetch_balances_begin": {},
371 "fetch_balances_end": {
372 "checkpoint": "begin",
376 "prepare_trades": { "available_balance_only": True }
,
377 "prepare_orders": { "compute_value": "average" }
,
387 "wait_for_recent", "prepare_trades", "prepare_orders",
388 "move_balances", "run_orders", "follow_orders",
389 "close_trades", "print_tickers"]
391 def __init__(self
, market
):
394 def select_steps(self
, scenario
, step
):
397 elif step
== "before" or step
== "after":
398 return list(filter(lambda x
: x
.get(step
, False), scenario
))
399 elif type(step
) == int:
400 return [scenario
[step
-1]]
401 elif type(step
) == str:
402 return list(filter(lambda x
: x
["name"] == step
, scenario
))
404 raise TypeError("Unknown step {}".format(step
))
406 def can_process(self
, scenario_name
):
407 return scenario_name
in self
.scenarios
409 def process(self
, scenario_name
, steps
="all", **kwargs
):
410 if not self
.can_process(scenario_name
):
411 raise TypeError("Unknown scenario {}".format(scenario_name
))
412 scenario
= self
.scenarios
[scenario_name
]
415 if type(steps
) == str or type(steps
) == int:
416 selected_steps
+= self
.select_steps(scenario
, steps
)
419 selected_steps
+= self
.select_steps(scenario
, step
)
420 for step
in selected_steps
:
421 self
.process_step(scenario_name
, step
, kwargs
)
423 def process_step(self
, scenario_name
, step
, kwargs
):
424 process_name
= "process_{}__{}_{}".format(scenario_name
, step
["number"], step
["name"])
425 self
.market
.report
.log_stage("{}_begin".format(process_name
))
427 if "fetch_balances_begin" in step
:
428 self
.market
.balances
.fetch_balances(tag
="{}_begin".format(process_name
),
429 **step
["fetch_balances_begin"])
431 for action
in self
.ordered_actions
:
433 self
.run_action(action
, step
[action
], kwargs
)
435 if "fetch_balances_end" in step
:
436 self
.market
.balances
.fetch_balances(tag
="{}_end".format(process_name
),
437 **step
["fetch_balances_end"])
439 self
.market
.report
.log_stage("{}_end".format(process_name
))
441 def method_arguments(self
, action
):
444 if action
== "wait_for_recent":
445 method
= Portfolio
.wait_for_recent
446 elif action
== "prepare_trades":
447 method
= self
.market
.prepare_trades
448 elif action
== "prepare_orders":
449 method
= self
.market
.trades
.prepare_orders
450 elif action
== "move_balances":
451 method
= self
.market
.move_balances
452 elif action
== "run_orders":
453 method
= self
.market
.trades
.run_orders
454 elif action
== "follow_orders":
455 method
= self
.market
.follow_orders
456 elif action
== "close_trades":
457 method
= self
.market
.trades
.close_trades
458 elif action
== "print_tickers":
459 method
= self
.market
.print_tickers
461 signature
= inspect
.getfullargspec(method
)
462 defaults
= signature
.defaults
or []
463 kwargs
= signature
.args
[-len(defaults
):]
465 return [method
, kwargs
]
467 def parse_args(self
, action
, default_args
, kwargs
):
468 method
, allowed_arguments
= self
.method_arguments(action
)
469 args
= {k: v for k, v in {**default_args, **kwargs}
.items() if k
in allowed_arguments
}
471 if "repartition" in args
and "base_currency" in args
["repartition"]:
472 r
= args
["repartition"]
473 r
[args
.get("base_currency", "BTC")] = r
.pop("base_currency")
477 def run_action(self
, action
, default_args
, kwargs
):
478 method
, args
= self
.parse_args(action
, default_args
, kwargs
)