4 import simplejson
as json
5 from decimal
import Decimal
as D
, ROUND_DOWN
6 from datetime
import date
, datetime
, timedelta
8 from json
import JSONDecodeError
9 from simplejson
.errors
import JSONDecodeError
as SimpleJSONDecodeError
11 __all__
= ["Portfolio", "BalanceStore", "ReportStore", "TradeStore"]
14 def __init__(self
, market
, verbose_print
=True):
16 self
.verbose_print
= verbose_print
21 def merge(self
, other_report
):
22 self
.logs
+= other_report
.logs
23 self
.logs
.sort(key
=lambda x
: x
["date"])
25 self
.print_logs
+= other_report
.print_logs
26 self
.print_logs
.sort(key
=lambda x
: x
[0])
28 def print_log(self
, message
):
30 message
= "{:%Y-%m-%d %H:%M:%S}: {}".format(now
, str(message
))
31 self
.print_logs
.append([now
, message
])
32 if self
.verbose_print
:
35 def add_log(self
, hash_
):
36 hash_
["date"] = datetime
.now()
37 self
.logs
.append(hash_
)
40 def default_json_serial(obj
):
41 if isinstance(obj
, (datetime
, date
)):
42 return obj
.isoformat()
46 return json
.dumps(self
.logs
, default
=self
.default_json_serial
, indent
=" ")
48 def to_json_array(self
):
49 for log
in (x
.copy() for x
in self
.logs
):
53 json
.dumps(log
, default
=self
.default_json_serial
, indent
=" ")
56 def set_verbose(self
, verbose_print
):
57 self
.verbose_print
= verbose_print
59 def log_stage(self
, stage
, **kwargs
):
62 return inspect
.getsource(element
).strip()
63 elif hasattr(element
, "as_json"):
64 return element
.as_json()
68 args
= { k: as_json(v) for k, v in kwargs.items() }
69 args_str
= ["{}={}".format(k
, v
) for k
, v
in args
.items()]
70 self
.print_log("-" * (len(stage
) + 8))
71 self
.print_log("[Stage] {} {}".format(stage
, ", ".join(args_str
)))
79 def log_balances(self
, tag
=None):
80 self
.print_log("[Balance]")
81 for currency
, balance
in self
.market
.balances
.all
.items():
82 self
.print_log("\t{}".format(balance
))
87 "balances": self
.market
.balances
.as_json()
90 def log_tickers(self
, amounts
, other_currency
,
94 if callable(compute_value
):
95 compute_value
= inspect
.getsource(compute_value
).strip()
97 for currency
, amount
in amounts
.items():
98 values
[currency
] = amount
.as_json()["value"]
99 rates
[currency
] = amount
.rate
102 "compute_value": compute_value
,
103 "balance_type": type,
104 "currency": other_currency
,
107 "total": sum(amounts
.values()).as_json()["value"]
110 def log_dispatch(self
, amount
, amounts
, liquidity
, repartition
):
113 "liquidity": liquidity
,
114 "repartition_ratio": repartition
,
115 "total_amount": amount
.as_json(),
116 "repartition": { k: v.as_json()["value"] for k, v in amounts.items() }
119 def log_trades(self
, matching_and_trades
, only
):
121 for matching
, trade
in matching_and_trades
:
122 trade_json
= trade
.as_json()
123 trade_json
["skipped"] = not matching
124 trades
.append(trade_json
)
129 "debug": self
.market
.debug
,
133 def log_orders(self
, orders
, tick
=None, only
=None, compute_value
=None):
134 if callable(compute_value
):
135 compute_value
= inspect
.getsource(compute_value
).strip()
136 self
.print_log("[Orders]")
137 self
.market
.trades
.print_all_with_order(ind
="\t")
141 "compute_value": compute_value
,
143 "orders": [order
.as_json() for order
in orders
if order
is not None]
146 def log_order(self
, order
, tick
, finished
=False, update
=None,
147 new_order
=None, compute_value
=None):
148 if callable(compute_value
):
149 compute_value
= inspect
.getsource(compute_value
).strip()
151 self
.print_log("[Order] Finished {}".format(order
))
152 elif update
== "waiting":
153 self
.print_log("[Order] {}, tick {}, waiting".format(order
, tick
))
154 elif update
== "adjusting":
155 self
.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order
, tick
, new_order
))
156 elif update
== "market_fallback":
157 self
.print_log("[Order] {}, tick {}, fallbacking to market value".format(order
, tick
))
158 elif update
== "market_adjust":
159 self
.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order
, tick
, new_order
))
165 "order": order
.as_json(),
166 "compute_value": compute_value
,
167 "new_order": new_order
.as_json() if new_order
is not None else None
170 def log_move_balances(self
, needed
, moving
):
172 "type": "move_balances",
173 "debug": self
.market
.debug
,
174 "needed": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in needed.items() }
,
175 "moving": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in moving.items() }
,
178 def log_http_request(self
, method
, url
, body
, headers
, response
):
179 if isinstance(response
, Exception):
181 "type": "http_request",
188 "error": response
.__class
__.__name
__,
189 "error_message": str(response
),
193 "type": "http_request",
198 "status": response
.status_code
,
199 "response": response
.text
202 def log_error(self
, action
, message
=None, exception
=None):
203 self
.print_log("[Error] {}".format(action
))
204 if exception
is not None:
205 self
.print_log(str("\t{}: {}".format(exception
.__class
__.__name
__, exception
)))
206 if message
is not None:
207 self
.print_log("\t{}".format(message
))
212 "exception_class": exception
.__class
__.__name
__ if exception
is not None else None,
213 "exception_message": str(exception
) if exception
is not None else None,
217 def log_debug_action(self
, action
):
218 self
.print_log("[Debug] {}".format(action
))
221 "type": "debug_action",
225 def log_market(self
, args
, user_id
, market_id
):
228 "commit": "$Format:%H$",
231 "market_id": market_id
,
235 def __init__(self
, market
):
239 def currencies(self
):
240 return self
.all
.keys()
242 def in_currency(self
, other_currency
, compute_value
="average", type="total"):
244 for currency
, balance
in self
.all
.items():
245 other_currency_amount
= getattr(balance
, type)\
246 .in_currency(other_currency
, self
.market
, compute_value
=compute_value
)
247 amounts
[currency
] = other_currency_amount
248 self
.market
.report
.log_tickers(amounts
, other_currency
,
252 def fetch_balances(self
, tag
=None):
253 all_balances
= self
.market
.ccxt
.fetch_all_balances()
254 for currency
, balance
in all_balances
.items():
255 if balance
["exchange_total"] != 0 or balance
["margin_total"] != 0 or \
256 currency
in self
.all
:
257 self
.all
[currency
] = portfolio
.Balance(currency
, balance
)
258 self
.market
.report
.log_balances(tag
=tag
)
260 def dispatch_assets(self
, amount
, liquidity
="medium", repartition
=None):
261 if repartition
is None:
262 repartition
= Portfolio
.repartition(liquidity
=liquidity
)
263 sum_ratio
= sum([v
[0] for k
, v
in repartition
.items()])
265 for currency
, (ptt
, trade_type
) in repartition
.items():
266 amounts
[currency
] = ptt
* amount
/ sum_ratio
267 if trade_type
== "short":
268 amounts
[currency
] = - amounts
[currency
]
269 self
.all
.setdefault(currency
, portfolio
.Balance(currency
, {}))
270 self
.market
.report
.log_dispatch(amount
, amounts
, liquidity
, repartition
)
274 return { k: v.as_json() for k, v in self.all.items() }
277 def __init__(self
, market
):
283 return list(filter(lambda t
: t
.pending
, self
.all
))
285 def compute_trades(self
, values_in_base
, new_repartition
, only
=None):
287 base_currency
= sum(values_in_base
.values()).currency
288 for currency
in self
.market
.balances
.currencies():
289 if currency
== base_currency
:
291 value_from
= values_in_base
.get(currency
, portfolio
.Amount(base_currency
, 0))
292 value_to
= new_repartition
.get(currency
, portfolio
.Amount(base_currency
, 0))
294 if value_from
.value
* value_to
.value
< 0:
295 computed_trades
.append(self
.trade_if_matching(
296 value_from
, portfolio
.Amount(base_currency
, 0),
297 currency
, only
=only
))
298 computed_trades
.append(self
.trade_if_matching(
299 portfolio
.Amount(base_currency
, 0), value_to
,
300 currency
, only
=only
))
302 computed_trades
.append(self
.trade_if_matching(
303 value_from
, value_to
,
304 currency
, only
=only
))
305 for matching
, trade
in computed_trades
:
307 self
.all
.append(trade
)
308 self
.market
.report
.log_trades(computed_trades
, only
)
310 def trade_if_matching(self
, value_from
, value_to
, currency
,
312 trade
= portfolio
.Trade(value_from
, value_to
, currency
,
314 matching
= only
is None or trade
.action
== only
315 return [matching
, trade
]
317 def prepare_orders(self
, only
=None, compute_value
="default"):
319 for trade
in self
.pending
:
320 if only
is None or trade
.action
== only
:
321 orders
.append(trade
.prepare_order(compute_value
=compute_value
))
322 self
.market
.report
.log_orders(orders
, only
, compute_value
)
324 def close_trades(self
):
325 for trade
in self
.all
:
328 def print_all_with_order(self
, ind
=""):
329 for trade
in self
.all
:
330 trade
.print_with_order(ind
=ind
)
332 def run_orders(self
):
333 orders
= self
.all_orders(state
="pending")
336 self
.market
.report
.log_stage("run_orders")
337 self
.market
.report
.log_orders(orders
)
339 def all_orders(self
, state
=None):
340 all_orders
= sum(map(lambda v
: v
.orders
, self
.all
), [])
344 return list(filter(lambda o
: o
.status
== state
, all_orders
))
346 def update_all_orders_status(self
):
347 for order
in self
.all_orders(state
="open"):
351 def __enter__(self
, *args
):
353 def __exit__(self
, *args
):
357 def __init__(self
, value
):
358 self
.lock
= NoopLock()
361 def start_lock(self
):
363 self
.lock
= threading
.Lock()
365 def set(self
, value
):
369 def get(self
, key
=None):
371 if key
is not None and isinstance(self
.val
, dict):
372 return self
.val
.get(key
)
376 def __getattr__(self
, key
):
378 return getattr(self
.val
, key
)
381 URL
= "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
382 data
= LockedVar(None)
383 liquidities
= LockedVar({})
384 last_date
= LockedVar(None)
385 report
= LockedVar(ReportStore(None))
387 worker_started
= False
392 def start_worker(cls
, poll
=30):
395 cls
.worker
= threading
.Thread(name
="portfolio", daemon
=True,
396 target
=cls
.wait_for_notification
, kwargs
={"poll": poll}
)
397 cls
.worker_notify
= threading
.Event()
398 cls
.callback
= threading
.Event()
400 cls
.last_date
.start_lock()
401 cls
.liquidities
.start_lock()
402 cls
.report
.start_lock()
404 cls
.worker_started
= True
408 def is_worker_thread(cls
):
409 if cls
.worker
is None:
413 return cls
.worker
== threading
.current_thread()
416 def wait_for_notification(cls
, poll
=30):
417 if not cls
.is_worker_thread():
418 raise RuntimeError("This method needs to be ran with the worker")
419 while cls
.worker_started
:
420 cls
.worker_notify
.wait()
421 cls
.worker_notify
.clear()
422 cls
.report
.print_log("Fetching cryptoportfolio")
423 cls
.get_cryptoportfolio(refetch
=True)
428 def notify_and_wait(cls
):
430 cls
.worker_notify
.set()
434 def wait_for_recent(cls
, delta
=4, poll
=30):
435 cls
.get_cryptoportfolio()
436 while cls
.last_date
.get() is None or datetime
.now() - cls
.last_date
.get() > timedelta(delta
):
437 if cls
.worker
is None:
439 cls
.report
.print_log("Attempt to fetch up-to-date cryptoportfolio")
440 cls
.get_cryptoportfolio(refetch
=True)
443 def repartition(cls
, liquidity
="medium"):
444 cls
.get_cryptoportfolio()
445 liquidities
= cls
.liquidities
.get(liquidity
)
446 return liquidities
[cls
.last_date
.get()]
449 def get_cryptoportfolio(cls
, refetch
=False):
450 if cls
.data
.get() is not None and not refetch
:
452 if cls
.worker
is not None and not cls
.is_worker_thread():
453 cls
.notify_and_wait()
456 r
= requests
.get(cls
.URL
)
457 cls
.report
.log_http_request(r
.request
.method
,
458 r
.request
.url
, r
.request
.body
, r
.request
.headers
, r
)
459 except Exception as e
:
460 cls
.report
.log_error("get_cryptoportfolio", exception
=e
)
463 cls
.data
.set(r
.json(parse_int
=D
, parse_float
=D
))
464 cls
.parse_cryptoportfolio()
465 except (JSONDecodeError
, SimpleJSONDecodeError
):
467 cls
.last_date
.set(None)
468 cls
.liquidities
.set({})
471 def parse_cryptoportfolio(cls
):
472 def filter_weights(weight_hash
):
473 if weight_hash
[1][0] == 0:
475 if weight_hash
[0] == "_row":
479 def clean_weights(i
):
480 def clean_weights_(h
):
481 if h
[0].endswith("s"):
482 return [h
[0][0:-1], (h
[1][i
], "short")]
484 return [h
[0], (h
[1][i
], "long")]
485 return clean_weights_
487 def parse_weights(portfolio_hash
):
488 if "weights" not in portfolio_hash
:
490 weights_hash
= portfolio_hash
["weights"]
492 for i
in range(len(weights_hash
["_row"])):
493 date
= datetime
.strptime(weights_hash
["_row"][i
], "%Y-%m-%d")
494 weights
[date
] = dict(filter(
496 map(clean_weights(i
), weights_hash
.items())))
499 high_liquidity
= parse_weights(cls
.data
.get("portfolio_1"))
500 medium_liquidity
= parse_weights(cls
.data
.get("portfolio_2"))
502 cls
.liquidities
.set({
503 "medium": medium_liquidity
,
504 "high": high_liquidity
,
506 cls
.last_date
.set(max(
507 max(medium_liquidity
.keys(), default
=datetime(1, 1, 1)),
508 max(high_liquidity
.keys(), default
=datetime(1, 1, 1))